I think, like the comments also say, you should use Dynamic SQL with a PIVOT table. It can probably be done more efficiently than this.
Create the table and put some data in it:
create table invoiceTable (
InvoiceNum int,
Product_Description nvarchar(20)
)
insert into invoiceTable values (1, 'inv1 row 1'),(1, 'inv1 row 2'),(1, 'inv1 row 3'),(2, 'inv2 row 1'),(2, 'inv2 row 2')
declare the necessary variables
declare @maxNo int
declare @query nvarchar(max)
declare @i int = 0
find the max row number:
select @maxNo = max(seq) from
(
Select
InvoiceNum
,Product_Description
,Row_Number() Over(Partition by InvoiceNum Order by InvoiceNum) - 1 seq
From
invoiceTable
) maxRowNo
Build the dynamic query
set @query =
'
Select
*
From
(
Select
InvoiceNum
,Product_Description
,Row_Number() Over(Partition by InvoiceNum Order by InvoiceNum) - 1 seq
From
invoiceTable
) d
pivot
(
min(Product_Description)
for seq in (
'
while (@i <= @maxNo)
begin
if (@i > 0) set @Query += ','
set @query += '['+CAST(@i as nvarchar)+']'
set @i += 1;
end
set @query +=
')
) pvt
'
Execute the query
exec sp_executesql @query
This gives the following resultset:
InvoiceNum 0 1 2
1 inv1 row 1 inv1 row 2 inv1 row 3
2 inv2 row 1 inv2 row 2 NULL