简体   繁体   中英

SQL SERVER 2008: Populate the column names as values in a new column when the data in the data in the rest of the columns meets a certain condition

I am a newbie to SQL and just know enough to get the basic stuff done.I am sure my "problem" might sound real real idiotic, but any help is really appreciated.

I have a table with 4 columns, all the columns filled with data. All I need to do to add a new column and update it with the "column names" of the columns in which the data meets a specific condition.

For example,

The table that I have is of the below format

  1            2         3         4
150000         -       250000      -   
250000      200000       -         -   
 -          170000         -    200000   
150000      250000     300000  175000

The Output that I am expecting (considering the condition to the data in the columns > 100000)

 1          2        3         4         5 
 150,000    -       250,000    -        1,3 
 250,000  200,000    -         -        1,2 
 -        170,000    -       200,000    2,4 
 150,000  250,000   300,000  175,000    1,2,3,4 

The column 5 needs to be inserted (which can be taken care of by using ALTER TABLE, ADD COLUMN), I am going on a merry go round trying to populate the the column names (names of the columns 1,2,3,4 when the values in the column > 100000).

Btw, I need to perform this operation on 60 columns.


Hope the explanation of issue helps enlighting my ignorance

Here is something to get you started:

DECLARE @Columns TABLE (ColName VARCHAR(100))
DECLARE @Result TABLE (ColName VARCHAR(MAX))

INSERT INTO @Columns (ColName)
SELECT COLUMN_NAME col
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'YourTable'
    AND DATA_TYPE = 'int'

DECLARE @sql NVARCHAR(MAX) =
STUFF(
(
    SELECT  'SELECT 
             CASE WHEN EXISTS (SELECT 1 
                                FROM YourTable 
                                WHERE ' + ColName + ' > 100000) 
             THEN ''' + ColName + ''' 
             ELSE ''''
             END'
    FROM    @Columns
    FOR     XML PATH('')
), 1, 1, '')

INSERT @Result
EXEC(@sql)

SELECT *
FROM @Result
WHERE ColName IS NOT NULL

The only part of this that doesn't work is the fact that > gets encoded by FOR XML PATH , which results in an error; you'll need to figure out a way to prevent that. If you replace the > with = (and select a value that exists) you will see it working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM