SQL Server 2008 Enterprise Edition.
I am getting some odd behavior trying to return results from a table variable, and concat them into a single string.
declare @SQLString nvarchar(max) ='';
declare @List table (ID smallint, Period smallint, Name nvarchar(4000), Value nvarchar(4000) );
insert into @List values(1, 0, 'Column1', 'Total Value');
insert into @List values(1, 0, 'Column2', 'Cost');
insert into @List values(1, 0, 'Column3/Column2', 'Qty');
insert into @List values(1, 0, 'Column4', 'Test');
select @SQLString = @SQLString + ',' + char(13) + char(9)
+ 'isnull('+Name + ',0) as [' + Value +']'
from @List order by Period, ID
At the moment, this is returning only the LAST result from @List
into @SQLString
.
If I remove the order by
, it works perfectly. Ie. it returns all rows into the string (eg. isnull(1,0), isnull(2,0) etc)
I have done this 1000 times for other purposes. What am I missing?
It does however, work on my local machine (running SQL Server 2008 Developer)