select @numOfColumns = count(distinct Col) from #b
SET @sql2=
'SELECT'+ @columns +'+= QUOTENAME(Col) + '',''
from (SELECT DISTINCT top @numOfColumns Col FROM #b ORDER BY Col) A';
EXECUTE sp_executesql @sql2;
I am trying to get this stored procedure to work. Trying to pass @numOfColumns to the statement then assign the values from QUOTENAME(Col) to @columns and Then Exec the statement.
Script
DECLARE
@columns NVARCHAR(MAX) = '',
@sql NVARCHAR(MAX) = '',
@sql2 NVARCHAR(MAX) = '',
@numOfColumns int = 0;
SELECT customerid, curbal, Col = CAST (ROW_NUMBER() OVER (PARTITION BY
convert(int,customerid) ORDER BY convert(float,curbal) desc) as int)
into #b
FROM [sav acc]
select @numOfColumns = count(distinct Col) from #b
SET @sql2= 'SELECT '+ @columns+' += QUOTENAME(Col) + '','' from (SELECT
DISTINCT top (@numOfColumns) Col FROM #b ORDER BY Col) A';
EXECUTE sp_executesql @sql2, N'@numOfColumns', @numOfColumns int;
This is origin of post. ORIGINAL POST . The solution did work, But i tested it with the Source data it would positions column at [3], [2], 1 and and I wanted the columns as 1,[2],[3]