0

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.

2

1 Answer 1

2

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.