Click here to Skip to main content
15,882,163 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I am struck at writing a query.i searched and didn't find any solution to this. Here i want to show the column name based on some specific value

For Instance , My table is like.

id | fruits |vegetables |softdrink
-----------------------
1 | apple | Onion | Pepsi
2 | mango | Potato | Coke
3 | banana | Bringal | RedBull

if i have a value "mango", then i should get the column name as fruit or

if i have a value "RedBull", then i should get the column name as softdrink


Below query is used in MySQL :

SQL
set @q= CONCAT('SELECT columns.column_name
                from table inner
                join information_schema.columns
                on columns.table_schema = "dbname"
                and columns.table_name = "table"
                and ((',
                (SELECT GROUP_CONCAT(CONCAT('columns.column_name="',column_name,'"',' and table.',column_name,' = "value','"') SEPARATOR ' OR ')
                FROM INFORMATION_SCHEMA.COLUMNS
                WHERE table_name = 'table'),
                '))');
prepare query from @q;
execute query;



I want write same query in sql server 2008 for Get column name dynamically by Specific row value.Solution appreciated.how to replace mysql query to sqlserver 2008
Posted

1 solution

You can try this:
SQL
set @q= CONCAT('SELECT columns.column_name
                from table inner
                join information_schema.columns
                on columns.table_schema = "yourDatabaseName"
                and columns.table_name = "table"
                and ((',
                (SELECT GROUP_CONCAT(CONCAT('columns.column_name="',column_name,'"',' and table.',column_name,' = "yourValue','"') SEPARATOR ' OR ')
                FROM INFORMATION_SCHEMA.COLUMNS
                WHERE table_name = 'table'),
                '))');
prepare query from @q;
execute query;


Refer: http://stackoverflow.com/questions/16621714/get-column-name-dynamically-by-specific-row-value[^]
 
Share this answer
 
Comments
Andrius Leonavicius 27-Mar-14 10:43am    
Have you read the question? OP is asking for a solution in SQL Server, not MySQL. Besides, you're giving identical code that OP has posted as example...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900