hello I want to know can we write a query where we give the column name as variable. for eg. table1( id , name, value) Set @var = 'name' Select @var from table1 or Set @var = 'id' Select @var form table1 or is there any other alternative for this. if u know comthing abt it pls do let me know Thanks in advance Pallavi
Hi, Yes you can pass column name dynamically and to do that you need to use dynamic SQL too. for eg. table1( id , name, value) Set @var = 'name' set @cmd='Select '+@var+' from table1' exec sp_executesql @cmd
Why do you need this? Refer this for more on Dynamic SQL http://www.sommarskog.se/dynamic_sql.html Madhivanan Failing to plan is Planning to fail
Hello thanks a lot Ranjit. But now i want to use this query for cursor or even if i can store the value from this column in a variable it will be ok for me Pls can u help me in this Pallavi
quote:Originally posted by pallavi Hello thanks a lot Ranjit. But now i want to use this query for cursor or even if i can store the value from this column in a variable it will be ok for me Pls can u help me in this Pallavi declare @var varchar(50),@cmd nvarchar(500),@var1 varchar(100) Set @var = 'aaiuserid' set @cmd='Select @var1=count('+@var+') from aaiusers' exec sp_executesql @cmd,N'@var1 varchar(100) OUTPUT',@var1 OUTPUT select @var1