Home > database >  Dynamically generated patchwork made him there must be a column column
Dynamically generated patchwork made him there must be a column column

Time:01-23




Me how I can ensure that data splicing to the right after he has several fields exist, because if no one has three data then complains and how to process

CodePudding user response:

Similar to the following

 
DECLARE @ SQL VARCHAR (1000)

WITH CTE_1
AS
(SELECT *
The FROM
(SELECT *, ROW_NUMBER () OVER (PARTITION BY ID ORDER BY GETDATE ()) AS an RN FROM TABLEXXX) AS A)


SELECT @ SQL=ISNULL (@ SQL + ', ', ') + VALUE_TYPE + CAST (RN) AS VARCHAR (5))
The FROM
(SELECT ID, RN, NOTLESS AS COL_VALUE, 'NOTLESS AS VALUE_TYPE FROM CTE_1
UNION ALL
SELECT ID, RN, NOTMORE AS COL_VALUE, 'NOTMORE AS VALUE_TYPE FROM CTE_1
UNION ALL
SELECT ID, RN, PRICE AS COL_VALUE, 'PRICE AS VALUE_TYPE FROM CTE_1) AS A
GROUP BY VALUE_TYPE, RN)

CodePudding user response:

Hello, may I don't have a clearly stated, I has put them together, I in the subsequent left join this table take data because I have to take notless1, 2, 3 notmore1, 2, 3 of these data, but he does not necessarily exist column names cause error, so I wonder is there any solution to

reference 1st floor RINK_1 response:

similar to the following
 
DECLARE @ SQL VARCHAR (1000)

WITH CTE_1
AS
(SELECT *
The FROM
(SELECT *, ROW_NUMBER () OVER (PARTITION BY ID ORDER BY GETDATE ()) AS an RN FROM TABLEXXX) AS A)


SELECT @ SQL=ISNULL (@ SQL + ', ', ') + VALUE_TYPE + CAST (RN) AS VARCHAR (5))
The FROM
(SELECT ID, RN, c AS COL_VALUE, 'NOTLESS AS VALUE_TYPE FROM CTE_1
UNION ALL
SELECT ID, RN, NOTMORE AS COL_VALUE, 'NOTMORE AS VALUE_TYPE FROM CTE_1
UNION ALL
SELECT ID, RN, PRICE AS COL_VALUE, 'PRICE AS VALUE_TYPE FROM CTE_1) AS A
GROUP BY VALUE_TYPE, RN)

  • Related