Reputation: 89
I have the following query.
declare @column_names varchar(1000)
declare @result varchar(1000)
set @column_names='id,firstname,lastname,age,city,country'
set @result=''
select @result=@result+@column_names +','+from studenttable where id='1'
But this query returns id,firstname,lastname,age,city,country
as result
and not like 1,john,j,21,newyork,us
.
How to change query so that @result
will contain actual entries in comma-separated form?
Please reply. Thanks.
Upvotes: 0
Views: 75
Reputation: 10264
To execute dynamic T-SQL statements use sp_executesql as:
EXECUTE sp_executesql
N'SELECT ' +@column_names +' FROM studenttable
WHERE id= @id',
N'@id tinyint',
@id= 1;
Upvotes: 2