Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2546
  • Last Modified:

SQL Server Query Column Name

I need to get the column name from an SQL Server DB table named DataReferrals where a particular number resides in a specific row.  For example, if the number 22 is in a row, I would need to know the column name where the 22 is.  Is there a SELECT statement that can accomplish this?
0
cmerlo1
Asked:
cmerlo1
1 Solution
 
aesmikeCommented:
Not without using some looping code.  Your criteria has to be explicity stated in an SQL statement so you can't get away from specifying each column as criteria in your query.  You could do a loop that creates an SQL string to be executed dynamiclly (EXEC)--one for each column.  The SQL string could be constructed such that the output goes into a results table:
Insert into <Results Table> (<Key Fields>,Column_Name) Select <Key Fields To Identify Row>, 'Column1' as Column_Name from <your table> where Column1=22
If you had 15 fields, you would be executing 15 queries.  Then look at the results.

0
 
cmerlo1Author Commented:
Looping through worked...I had actually thought about doing it this way, but I was hoping it could be done the other way...thanks!
0
 
ripeshshahCommented:
Hi cmerlo1

It is possible in SQL, If you know the number of column in table. I make one query which will return column name.

Table:
consider Table1 has three column A, B, C. data in table1 is as follow
id   A         B          C
1   11       22         3 3
2   10       20         22    

You have to find out column name where value is 22 in first row

select * from information_schema.columns where ordinal_position  in (  
select case when A = 22  then 1 else 0 end  from table1 where id  = 1
union
select case when B = 22  then 2 else 0 end from table1where id  = 1
union
select case when C = 22  then 3 else 0 end from table1where id  = 1 )
and table_name = 'table1'

You can make this query dynamic in store procedure.

Hope it will work for you.
Devidas Gaikwad
+919892299766
0
 
qtrmile69Commented:
what about if you want to return the name of the column where you want to find the last non null field from a group of fields

Column  =    8              9        10         11           12            13        14         15
value =       12.3       13.5               13.2         20.1                     25.1



Column "14" was the last non null


Thanks
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now