Getting a Dynamically-Generated Pivot-Table into a Temp Table - sql

I've seen this, so I know how to create a pivot table with a dynamically generated set of fields. My problem now is that I'd like to get the results into a temporary table.
I know that in order to get the result set into a temp table from an EXEC statement you need to predefine the temp table. In the case of a dynamically generated pivot table, there is no way to know the fields beforehand.
The only way I can think of to get this type of functionality is to create a permanent table using dynamic SQL. Is there a better way?

Ran in to this issue today, and posted on my blog. Short description of solution, is to create a temporary table with one column, and then ALTER it dynamically using sp_executesql. Then you can insert the results of the dynamic PIVOT into it. Working example below.
CREATE TABLE #Manufacturers
(
ManufacturerID INT PRIMARY KEY,
Name VARCHAR(128)
)
INSERT INTO #Manufacturers (ManufacturerID, Name)
VALUES (1,'Dell')
INSERT INTO #Manufacturers (ManufacturerID, Name)
VALUES (2,'Lenovo')
INSERT INTO #Manufacturers (ManufacturerID, Name)
VALUES (3,'HP')
CREATE TABLE #Years
(YearID INT, Description VARCHAR(128))
GO
INSERT INTO #Years (YearID, Description) VALUES (1, '2014')
INSERT INTO #Years (YearID, Description) VALUES (2, '2015')
GO
CREATE TABLE #Sales
(ManufacturerID INT, YearID INT,Revenue MONEY)
GO
INSERT INTO #Sales (ManufacturerID, YearID, Revenue) VALUES(1,2,59000000000)
INSERT INTO #Sales (ManufacturerID, YearID, Revenue) VALUES(2,2,46000000000)
INSERT INTO #Sales (ManufacturerID, YearID, Revenue) VALUES(3,2,111500000000)
INSERT INTO #Sales (ManufacturerID, YearID, Revenue) VALUES(1,1,55000000000)
INSERT INTO #Sales (ManufacturerID, YearID, Revenue) VALUES(2,1,42000000000)
INSERT INTO #Sales (ManufacturerID, YearID, Revenue) VALUES(3,1,101500000000)
GO
DECLARE #SQL AS NVARCHAR(MAX)
DECLARE #PivotColumnName AS NVARCHAR(MAX)
DECLARE #TempTableColumnName AS NVARCHAR(MAX)
DECLARE #AlterTempTable AS NVARCHAR(MAX)
--get delimited column names for various SQL statements below
SELECT
-- column names for pivot
#PivotColumnName= ISNULL(#PivotColumnName + N',',N'') + QUOTENAME(CONVERT(NVARCHAR(10),YearID)),
-- column names for insert into temp table
#TempTableColumnName = ISNULL(#TempTableColumnName + N',',N'') + QUOTENAME('Y' + CONVERT(NVARCHAR(10),YearID)),
-- column names for alteration of temp table
#AlterTempTable = ISNULL(#AlterTempTable + N',',N'') + QUOTENAME('Y' + CONVERT(NVARCHAR(10),YearID)) + ' MONEY'
FROM (SELECT DISTINCT [YearID] FROM #Sales) AS Sales
CREATE TABLE #Pivot
(
ManufacturerID INT
)
-- Thats it! Because the following step will flesh it out.
SET #SQL = 'ALTER TABLE #Pivot ADD ' + #AlterTempTable
EXEC sp_executesql #SQL
--execute the dynamic PIVOT query into the temp table
SET #SQL = N'
INSERT INTO #Pivot (ManufacturerID, ' + #TempTableColumnName + ')
SELECT ManufacturerID, ' + #PivotColumnName + '
FROM #Sales S
PIVOT(SUM(Revenue)
FOR S.YearID IN (' + #PivotColumnName + ')) AS PivotTable'
EXEC sp_executesql #SQL
SELECT M.Name, P.*
FROM #Manufacturers M
INNER JOIN #Pivot P ON M.ManufacturerID = P.ManufacturerID

you could do this:
-- add 'loopback' linkedserver
if exists (select * from master..sysservers where srvname = 'loopback')
exec sp_dropserver 'loopback'
go
exec sp_addlinkedserver #server = N'loopback',
#srvproduct = N'',
#provider = N'SQLOLEDB',
#datasrc = ##servername
go
declare #myDynamicSQL varchar(max)
select #myDynamicSQL = 'exec sp_who'
exec('
select * into #t from openquery(loopback, ''' + #myDynamicSQL + ''');
select * from #t
')
EDIT: addded dynamic sql to accept params to openquery

Let me try this explanation of select into instead. I'm running SQL Server 2005 as well. Because you have PIVOT tables I'm going to assume the same or 2008.
select
o.*,
OtherField1,
OtherField2
INTO #temp
FROM
OriginalOtherData as ood
PIVOT (
MAX([Value])
FOR Field in (OtherField1, OtherField2)
) as piv
RIGHT OUTER join
Original o on o.OriginalSD = piv.OriginalSD
select * from #temp
Drop table #temp
The only difference between a normal select and a select into is that INTO #table part.

for query (select col1, col2, col3 from tablename
col1 becomes rowlabels
col2 becomes columnheaders
col3 is the dataset
also gets rid of the global table
if OBJECT_ID('tempdb..#3') is not null drop table #3
if OBJECT_ID('tempdb..##3') is not null drop table ##3
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT distinct ',' + QUOTENAME( col2 ) from tablename FOR XML PATH(''), col2).value('.', 'NVARCHAR(MAX)'),1,1,'')
set #query = 'SELECT col1, ' + #cols + ' into ##3 from ( select col1, col2, col3 from tablename ) x pivot ( max(col3)for col2 in (' + #cols + ')) p '
execute(#query)
select * into #3 from ##3 if OBJECT_ID('tempdb..##3') -- is not null drop table ##3

Related

Dynamic pivot in SQL server: insert spaces in concatenation and referencing a pivot

I have a table in long format which I convert to wide format dynamically.
The code was heavily influenced by: SQL Server dynamic PIVOT query?
create table #temp
(
ID int,
category varchar(15),
Answer varchar (5)
)
insert into #temp values ('1', 'breakfast','yes')
insert into #temp values ('1', 'lunch','no')
insert into #temp values ('1', 'dinner','yes')
insert into #temp values ('2', 'breakfast','no')
insert into #temp values ('2', 'lunch', 'yes')
insert into #temp values ('2', 'dinner', 'no')
select * from #temp
Which I can convert into wide format:
DECLARE #cols AS VARCHAR(MAX)='';
DECLARE #query AS VARCHAR(MAX)='';
SELECT #cols = #cols + QUOTENAME(category) + ',' FROM (select distinct category from #temp ) as tmp
select #cols = substring(#cols, 0, len(#cols))
exec (
'SELECT ID, '+#cols+', concat('+#cols+' )as NewCol from
(
select ID, category,answer from #temp
) pivotexample
pivot
(
max(Answer) for category in (' + #cols + ')
) as pivotexample2'
)
drop table #temp
The distinct values in the category column can change so I needed a dynamic solution (as above). This give the below pivoted output:
The issue I have is how can I insert a separator in the concatenation part that creates NewColumn in the pivot.
Also when I then run a select * from pivotexample2 query, it says Invalid object name 'pivotexample2'. I don't understand why this is, because this is the alias I have given it and want to reference it for things like joins further in the pipeline. How can I give it an alias so I can refence it again? Is it possible to put the pivot within a CTE so I can refence it again?
You can use concat_ws:
DECLARE #cols AS VARCHAR(MAX)='';
DECLARE #query AS VARCHAR(MAX)='';
SELECT #cols = #cols + QUOTENAME(category) + ',' FROM (select distinct category from #temp ) as tmp
select #cols = substring(#cols, 0, len(#cols))
exec (
'SELECT ID, '+#cols+', concat_ws('','', '+#cols+' )as NewCol from
(
select ID, category,answer from #temp
) pivotexample
pivot
(
max(Answer) for category in (' + #cols + ')
) as pivotexample2'
)
drop table #temp
It would return:
ID
breakfast
dinner
lunch
NewCol
1
yes
yes
no
yes,yes,no
2
no
no
yes
no,no,yes
DBFiddle: https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=45dce502caf3b71662b963fb52dff94e

Reorder columns in final stored procedure SELECT / OUTPUT

I need to reorder columns in the final SELECT statement in a stored procedure. Column orders needs to be fetched from another table.
I have a solution based on dynamic SQL. Is there any better way to do it? I have around 100 columns to return with millions of rows for an Excel export. Is there any other performance optimized solution other than a dynamic query?
Please find sample code below for my current solution.
IF OBJECT_ID( 'tempdb..#TempColumns') IS NOT NULL
BEGIN
DROP TABLE #TempColumns
END
IF OBJECT_ID( 'tempdb..#TempColumnsOrder') IS NOT NULL
BEGIN
DROP TABLE #TempColumnsOrder
END
CREATE TABLE #TempColumns
(
ID INT IDENTITY,
FirstName VARCHAR(MAX),
LastName VARCHAR(MAX),
Gender VARCHAR(MAX)
)
INSERT INTO #TempColumns
VALUES ('ABC', 'DEF', 'MALE'), ('PR', 'ZA', 'FEMALE'), ('ERT', 'GFG', 'MALE')
CREATE TABLE #TempColumnsOrder
(
ID INT IDENTITY,
ColumnName VARCHAR(MAX),
ColumnOrder INT
)
INSERT INTO #TempColumnsOrder
VALUES ('FirstName', 3), ('LastName', 2), ('Gender', 1)
SELECT * FROM #TempColumns
SELECT * FROM #TempColumnsOrder
DECLARE #script VARCHAR(MAX)
SELECT #script = 'SELECT '
SELECT #script = #script + ColumnName + ','
FROM #TempColumnsOrder
ORDER BY ColumnOrder
PRINT #script
SELECT #script = SUBSTRING(RTRIM(#script), 1, LEN(RTRIM(#script)) - 1)
SELECT #script = #script + ' FROM #TempColumns'
EXEC (#script)
IF OBJECT_ID( 'tempdb..#TempColumns') IS NOT NULL
BEGIN
DROP TABLE #TempColumns
END
IF OBJECT_ID( 'tempdb..#TempColumnsOrder') IS NOT NULL
BEGIN
DROP TABLE #TempColumnsOrder
END
Thanks for reply, Is there any better way in Dynamic SQL other than what i did?
You can eliminate the unsupported string concatenation you are using, and modernize and simply the code:
DROP TABLE IF EXISTS #TempColumns
DROP TABLE IF EXISTS #TempColumnsOrder
CREATE TABLE #TempColumns
(
ID INT IDENTITY,
FirstName VARCHAR(MAX),
LastName VARCHAR(MAX),
Gender VARCHAR(MAX)
)
INSERT INTO #TempColumns
Values('ABC','DEF','MALE'),('PR','ZA','FEMALE'),('ERT','GFG','MALE')
CREATE TABLE #TempColumnsOrder
(
ID INT IDENTITY,
ColumnName VARCHAR(MAX),
ColumnOrder INT
)
INSERT INTO #TempColumnsOrder
Values('FirstName',3), ('LastName',2), ('Gender',1)
SELECT * FROM #TempColumns
SELECT * FROM #TempColumnsOrder
DECLARE #script VARCHAR(MAX) = concat(
'SELECT ',
(select STRING_AGG(QUOTENAME(ColumnName),', ') WITHIN GROUP (ORDER BY ColumnOrder)
FROM #TempColumnsOrder),
' FROM #TempColumns')
print #script
EXEC (#script)
DROP TABLE IF EXISTS #TempColumns
DROP TABLE IF EXISTS #TempColumnsOrder
SELECT #script = #script + ColumnName + ',' FROM #TempColumnsOrder
ORDER BY ColumnOrder
The behavior of aggregate string concatenation with the above technique is not guaranteed. The actual behavior is plan-dependent so you may not get the desired results.
In SQL Server 2017 and Azure SQL Database, STRING_AGG is the proper method:
SELECT STRING_AGG(ColumnName, ',') WITHIN GROUP(ORDER BY ColumnOrder)
FROM #TempColumnsOrder;
In older SQL Versions like SQL Server 2012, the best method is with XML PATH():
SELECT #script = #script +
STUFF((SELECT ',' + ColumnName
FROM #TempColumnsOrder
ORDER BY ColumnOrder
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'');
See this answer for details about how the above query works.

Moving Column names to rows

I have such a table with date as column name
but I would like to have these dates in one column in more than one row something like this:
Date Index
20170806 9206
20170813 8041
20170820 8861
20170827 8356
How can I do it in SQL Server
If you would like to go for more dynamic solution rather than hard coding all columns, the below scripts should work:
IF OBJECT_ID('TestTable') IS NOT NULL
DROP TABLE TestTable;
CREATE TABLE TestTable
(
[20170806] INT NOT NULL,
[20170813] INT NOT NULL,
[20170820] INT NOT NULL,
[20170827] INT NOT NULL
)
INSERT INTO TestTable VALUES (9206, 8041, 8861, 8356)
DECLARE #cols NVARCHAR(MAX),
#sql NVARCHAR(MAX)
SELECT #cols = COALESCE(#cols + ',', '') + QUOTENAME(c.COLUMN_NAME)
FROM INFORMATION_SCHEMA.[COLUMNS] AS c
WHERE c.TABLE_NAME = 'TestTable'
SET #sql = '
SELECT [Date],
[Index]
FROM TestTable
UNPIVOT([Index] FOR [Date] IN ('+ #cols +')) AS up'
exec sp_executesql #sql;
You can use UNPIVOT for this.
SELECT * FROM MyTable
UNPIVOT([Date] For [Index] IN( [20170806], [20170813], [20170820], [20170827])) UNPVT
In addition, if you want to make it dynamically, you can use this query too.
DECLARE #ColNames NVARCHAR(MAX)
= STUFF(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
(SELECT T.* FROM (VALUES(1)) AS DUMY(ID) LEFT JOIN MyTable T ON 1=2 FOR XML AUTO, ELEMENTS XSINIL )
,'<T xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">','')
,'</T>','')
,'_x0032_','2')
,' xsi:nil="true"/>','] ')
,'<',',[') ,1,1,'')
DECLARE #SqlQ NVARCHAR(MAX)
= 'SELECT * FROM MyTable UNPIVOT([Date] For [Index] IN( ' + #ColNames + ')) UNPVT'
EXEC sp_executesql #SqlQ
You could use pivot such as:
However, i dont know your exact table names
select field_names
from table_name
pivot
( index
for index in ( Date, Index)
) pivot
but a useful article to follow is
"https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx"
Designed the table (variable) structure as below.
Hopefully, it matches your table structure.
DECLARE #data TABLE
(
[20170806] INT,
[20170813] INT,
[20170820] INT,
[20170827] INT
)
INSERT INTO #data VALUES (9206, 8041, 8861, 8356)
SELECT * FROM #data
You can use UNPIVOT statement for this. If you have dynamic columns, check this.
SELECT [Date],[Index]
FROM
#data
UNPIVOT
(
[Index] FOR [Date] IN ([20170806], [20170813], [20170820], [20170827])
) AS unpivotTable;
and the output is

SQL Server 2005 - Dynamic PIVOT query

I require your kind help on a PIVOT query problem.
The scenario is I have a voting system. Comprises of 3 tables.
Elections, Candidates, Votes.
The PIVOT relates to PIVOTing the Candidate names as Columns and having the VOTE data as the data.
So far I have attemped this and not got it to work, I've gotten into a muddle with it :(
CREATE TABLE #MYELECTIONS (E_POSITION_CODE INT, E_POSITIONNAME VARCHAR(50))
INSERT INTO #MYELECTIONS VALUES (147,'MANAGER')
INSERT INTO #MYELECTIONS VALUES (148,'CHEF')
INSERT INTO #MYELECTIONS VALUES (149,'WAITER')
CREATE TABLE #MYCANDIDATES (C_CANDIDATE_CODE INT,
C_CANDIDATENAME VARCHAR (50), C_POSITION_CODE INT)
INSERT INTO #MYCANDIDATES VALUES (100,'TOM CRUISE', 147)
INSERT INTO #MYCANDIDATES VALUES (101,'MICKY MOUSE', 147)
INSERT INTO #MYCANDIDATES VALUES (103,'DONALD DUCK', 147)
INSERT INTO #MYCANDIDATES VALUES (100,'TOM CRUISE', 148)
CREATE TABLE #MYVOTES (V_POSITION_CODE INT,
V_CANDIDATE_CODE INT, VOTINGPREFERENCE SMALLINT)
INSERT INTO #MYVOTES VALUES (147,100,1)
INSERT INTO #MYVOTES VALUES (147,100,1)
INSERT INTO #MYVOTES VALUES (147,100,1)
INSERT INTO #MYVOTES VALUES (147,100,1)
INSERT INTO #MYVOTES VALUES (147,101,1)
INSERT INTO #MYVOTES VALUES (147,101,1)
INSERT INTO #MYVOTES VALUES (147,103,1)
INSERT INTO #MYVOTES VALUES (148,100,1)
INSERT INTO #MYVOTES VALUES (148,100,1)
DECLARE #DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE #ColumnName AS NVARCHAR(MAX)
DECLARE #MyPositionCode AS INT
SET #MyPositionCode = 147
DECLARE #MyOutput AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT #ColumnName = ISNULL(#ColumnName + ',','')
+ QUOTENAME(C_CANDIDATENAME)
FROM (SELECT TOP 100 PERCENT C_CANDIDATENAME
FROM #MYCANDIDATES
WHERE C_POSITION_CODE = #MyPositionCode
ORDER BY C_CANDIDATE_CODE) AS C_CANDIDATENAME
--Prepare the `PIVOT` query using the dynamic sql
SET #DynamicPivotQuery =
N'SELECT ROW_NUMBER() OVER (ORDER BY E_POSITIONNAME) AS Idnum,
E_POSITIONNAME AS [Position Name], ' + #ColumnName + '
FROM #MYVOTES
INNER JOIN #MYELECTIONS
ON (#MYVOTES.V_POSITION_CODE = #MYELECTIONS.E_POSITION_CODE)
PIVOT(SUM(VOTINGPREFERENCE))
FOR C_CANDIDATENAME IN (' + #ColumnName + ') AS PVTTable
WHERE #MYELECTIONS.E_POSITION_CODE = 147'
--Execute the Dynamic Pivot Query
EXEC sp_executesql #DynamicPivotQuery,
#MyOutput = #MyOutput OUTPUT
SELECT #MyOutput
DROP TABLE #MYELECTIONS
DROP TABLE #MYCANDIDATES
DROP TABLE #MYVOTES
It has to be a dynamic PIVOT as the Candidate Names that I want to Pivot as Columns, could be dynamic depending on how many Candidates there are for an Election position.
The desired output for the above would be like this:-
Election #MyPositionCode = 147
Idnum Position_Name TOM CRUISE MICKY MOUSE DONALD DUCK...
1 MANAGER 4 2 1
Election #MyPositionCode = 148
Idnum Position_Name TOM CRUISE MICKY MOUSE DONALD DUCK...
1 CHEF 2 0 0
Try this
DECLARE #MyPositionCode AS INT
SET #MyPositionCode = 147
Declare the variables for selecting dynamic columns
DECLARE #DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE #ColumnName AS NVARCHAR(MAX)
DECLARE #cols NVARCHAR (MAX)
SELECT #cols = COALESCE (#cols + ',[' + C_CANDIDATENAME + ']', '[' + C_CANDIDATENAME + ']')
FROM
(
SELECT TOP 100 PERCENT C_CANDIDATENAME
FROM #MYCANDIDATES
WHERE C_POSITION_CODE = #MyPositionCode
ORDER BY C_CANDIDATE_CODE
) PV
ORDER BY C_CANDIDATENAME desc
If you want to replace NULL with zero
DECLARE #NulltoZeroCols NVARCHAR (MAX)
SELECT #NullToZeroCols = SUBSTRING((SELECT ',ISNULL(['+C_CANDIDATENAME+'],0) AS ['+C_CANDIDATENAME+']'
FROM
(
SELECT TOP 100 PERCENT C_CANDIDATENAME
FROM #MYCANDIDATES
WHERE C_POSITION_CODE = #MyPositionCode
ORDER BY C_CANDIDATE_CODE
)TAB
ORDER BY C_CANDIDATENAME desc FOR XML PATH('')),2,8000)
Now pivot it dynamically. I have written the logic inside
DECLARE #query NVARCHAR(MAX)
SET #query = '-- You can apply ROW_NUMBER() here which is the data after pivot
SELECT ROW_NUMBER() OVER (ORDER BY E_POSITIONNAME) AS Idnum,
,E_POSITIONNAME,'+#NullToZeroCols+'
FROM
(
-- Select data before pivot
SELECT TOP 100 PERCENT ME.E_POSITIONNAME,MC.C_CANDIDATENAME,
COUNT(MC.C_CANDIDATENAME) OVER(PARTITION BY ME.E_POSITIONNAME,MC.C_CANDIDATENAME) CNT
FROM #MYELECTIONS ME
JOIN #MYCANDIDATES MC ON ME.E_POSITION_CODE=MC.C_POSITION_CODE
JOIN #MYVOTES MV ON MC.C_CANDIDATE_CODE=MV.V_CANDIDATE_CODE
AND MV.V_POSITION_CODE=MC.C_POSITION_CODE
WHERE MC.C_POSITION_CODE = ' + CAST(#MyPositionCode AS VARCHAR(30)) + '
) x
PIVOT
(
MIN(CNT)
FOR C_CANDIDATENAME IN (' + #cols + ')
) p
;'
EXEC SP_EXECUTESQL #query
Click the below link. If the result is not auto-generated, press RUN QUERY button.
Click here to view result

Way to put pivote sql result into temptable

work on sql server .Write one pivotal sql ,bellow is my tables and pivotal sql syntax.MY problem is failed to put this pivotal value in Temp table .
-----------------Table-1-------------
CREATE TABLE Table1 (ColId INT,ColName VARCHAR(10))
INSERT INTO Table1 VALUES(1, 'Country')
INSERT INTO Table1 VALUES(2, 'MONTH')
INSERT INTO Table1 VALUES(3, 'Day')
----------------Table-2----------------------------
CREATE TABLE Table2 (tID INT,ColID INT,Txt VARCHAR(10))
INSERT INTO Table2 VALUES (1,1, 'US')
INSERT INTO Table2 VALUES (1,2, 'July')
INSERT INTO Table2 VALUES (1,3, '4')
INSERT INTO Table2 VALUES (2,1, 'US')
INSERT INTO Table2 VALUES (2,2, 'Sep')
INSERT INTO Table2 VALUES (2,3, '11')
INSERT INTO Table2 VALUES (3,1, 'US')
INSERT INTO Table2 VALUES (3,2, 'Dec')
INSERT INTO Table2 VALUES (3,3, '25')
--------------
----------------Pivotal sql----------------------------
DECLARE #query NVARCHAR(4000)
DECLARE #cols NVARCHAR(2000)
SELECT #cols = STUFF(( SELECT DISTINCT TOP 100 PERCENT
'],[' + t2.ColName
FROM Table1 AS t2
ORDER BY '],[' + t2.ColName
FOR XML PATH('')
), 1, 2, '') + ']'
SET #query = N'SELECT tID, '+
#cols +'
FROM
(SELECT t2.tID
, t1.ColName
, t2.Txt
FROM Table1 AS t1
JOIN Table2 AS t2 ON t1.ColId = t2.ColID) p
PIVOT
(
MAX([Txt])
FOR ColName IN
( '+
#cols +' )
) AS pvt
ORDER BY tID;'
EXECUTE(#query)
After execute bellow command want to use this value for rest of work ,so I need to put this command result value in temp table
EXECUTE(#query)
If you are able to do the rest of your procedure by working with EXECUTE(#Querys) you coud do something like that
Declare #TabName Varchar(40)
Select #TabName='##'+Replace(CAST(NEWID() as Varchar(40)),'-','')
DECLARE #query NVARCHAR(4000)
DECLARE #cols NVARCHAR(2000)
SELECT #cols = STUFF(( SELECT DISTINCT TOP 100 PERCENT
'],[' + t2.ColName
FROM Table1 AS t2
ORDER BY '],[' + t2.ColName
FOR XML PATH('')
), 1, 2, '') + ']'
SET #query = N'SELECT tID, '+
#cols +' into ' +#TabName + '
FROM
(SELECT t2.tID
, t1.ColName
, t2.Txt
FROM Table1 AS t1
JOIN Table2 AS t2 ON t1.ColId = t2.ColID) p
PIVOT
(
MAX([Txt])
FOR ColName IN
( '+
#cols +' )
) AS pvt
ORDER BY tID;'
Print #Query
EXECUTE(#query)
Select #query = 'Select * from ' + #Tabname
EXECUTE(#query)
Select #query = 'Drop Table ' + #Tabname
EXECUTE(#query)
If you dont want to do that, you could use a "hard" ##temptable, but you would not be able using this save withing a multiuser environment.
Try this :
Declare #Sample table
(
tID int,
Country VARCHAR(10),
Day int ,
MONTH VARCHAR(10)
)
Insert into #Sample
EXECUTE(#query)
select * from #Sample
In the same way you can create a temp table instead of table variable and insert it into it