I’m doing dynamic SQL to convert all columns in a table a string
so After after all I do
EXEC(@template);
where @template is the dynamic generated query so:
col1 col2 col3
---------------
1 7 13
2 8 14
3 9 15
4 10 16
5 11 17
6 12 18
(this results: 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18)
How do I assign to a variable the resulting string
something like?
DECLARE @result AS varchar(max);
SET @result = EXEC(@template);
You can use sp_executesql with output parameter.
Result:
Edit
In my sample
@Sis instead of your@template. As you can see I assign a value to@xso you need to modify@templateso it internally assigns the comma separated string to the variable you define in your second argument tosp_executesql. In my sampleN'@x int out'. You probably want avarchar(max)output parameter. Something likeN'@Result varchar(max) out'Here is another example building a comma separated string from master..spt_values