I would like to export the results of a dynamic query with dynamic columns to a temporary table. Since the columns are dynamic I cannot pre-define the schema.
Tried using temporary table by using the Select.. Into however that does not work and no table is outputted.
declare @start DATETIME = (select DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-13, 0))
declare @end DATETIME = (select DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0))
declare @v_columns varchar(max)
declare @v_sql varchar(max)
;with months (v_date)
AS
(
SELECT @start
UNION ALL
SELECT DATEADD(month,1,v_date)
from months
where DATEADD(month,1,v_date)<=@end
)
select @v_columns=stuff((select','+QUOTENAME(DATENAME(month,v_date)+cast(year(v_date) as varchar)) from months for xml path('')),1,1,'')
print @v_columns
set @v_sql='
;with months (v_date)
AS
(
SELECT cast('''+convert(varchar(10),@start,101)+''' as date)
UNION ALL
SELECT DATEADD(month,1,v_date)
from months
where DATEADD(month,1,v_date)<='''+convert(varchar(10),@end,101)+'''
)
SELECT
INVOICECUSTOMERACCOUNTNUMBER, ORGANIZATIONNAME,'+@v_columns+'
INTO #newtbl FROM
(
SELECT
b.INVOICECUSTOMERACCOUNTNUMBER, c.ORGANIZATIONNAME,SUM(a.LINEAMOUNTMST) [LineAmount],DATENAME(month,a.invoicedate)+cast(year(a.invoicedate) as varchar) as v_date
from dbo.Table1 a
inner join dbo.Table2 b
on a.INVOICEID=b.INVOICENUMBER
inner join dbo.Table3 c
on b.INVOICECUSTOMERACCOUNTNUMBER=c.CUSTOMERACCOUNT
group by b.INVOICECUSTOMERACCOUNTNUMBER,c.ORGANIZATIONNAME,a.INVOICEDATE) as x
PIVOT
(
SUM(LineAmount) FOR v_date IN ('+@v_columns+')
) PVT; SELECT * FROM #newtbl'
print @v_sql
EXEC (@v_sql)
A table which is created dynamically with dynamic column names and its values.