Assign result of dynamic sql to variable

Viewed 178266

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); 
5 Answers

You should try this while getting SEQUENCE value in a variable from the dynamic table.

DECLARE @temp table (#temp varchar (MAX));
DECLARE @SeqID nvarchar(150);
DECLARE @Name varchar(150); 

SET @Name = (Select Name from table)
SET @SeqID = 'SELECT NEXT VALUE FOR '+ @Name + '_Sequence'
insert @temp exec (@SeqID)

SET @SeqID = (select * from @temp )
PRINT @SeqID

Result:

(1 row(s) affected)
 1
Related