0

Below is the code where I am getting a columns name dynamically(example F8 is the column name) and storing it in @whcode. What i need is the value that is stored in this column for the where condition specified below. I can see the value stored in the column is 2 but I cannot get it. What it is returning me is the column name itself. How can I get the value in the column. Please help.

declare @count1 int
set @count1 = (select min(srno) from TEMP_STOCK_uPDATE)
declare @whcode varchar(20)
select * from TEMP_STOCK_uPDATE where srno='16091'
set @whcode=(SELECT COLUMN_NAME
            FROM Ecata_New.INFORMATION_SCHEMA.COLUMNS
            where Table_Name = 'TEMP_STOCK_uPDATE'  
            and COLUMN_NAME =(select whcode from dbo.temp_stock_map where func=(select func from dbo.temp_stock_map where sr_no=6)))
--select @whcode as 'abcd'



select @whcode as 'abc'
from TEMP_STOCK_uPDATE
where 
F1=(select F1 from dbo.TEMP_STOCK_uPDATE where srno=@count1) 
Ankur
  • 1,023
  • 7
  • 27
  • 42
  • 2
    This is only going to get messier and messier as you continue down this route. As I suggested in a comment to your previous question, instead of going down (what looks like) a blind alley, maybe you could present us with the overall *problem* to be solved, and we might, then, be able to offer an overall *solution* to the problem - rather than you continue to present us with the problems with the *solution* that you've already decided upon. – Damien_The_Unbeliever Jun 20 '13 at 09:45
  • @Damien_The_Unbeliever : http://stackoverflow.com/questions/17211611/converting-columns-to-row-and-updating . Is the link for my problem that you have asked for. Please visit the link. – Ankur Jun 20 '13 at 10:44
  • @Damien_The_Unbeliever : I got the answer , wrote 2 while loops and was able to fine the column name and its value dynamically. – Ankur Jun 21 '13 at 06:43

1 Answers1

1

You can build your SQL statement dynamically to do this. Build your statement in a varchar and then EXEC it.

DECLARE @SQL VARCHAR(4000)

SET @SQL = 'select ' + @whcode + ' from TEMP_STOCK_uPDATE where F1=(select F1 from dbo.TEMP_STOCK_uPDATE where srno=@count1)'

EXEC (@SQL)
NigelK
  • 8,255
  • 2
  • 30
  • 28