简体   繁体   中英

Inserting dynamic pivot Result into Temp table

I have the date and script below which calculate sales by item and year. It works fine But when I try to insert the result into temp table so that the temp table can be uses in another query. I have the following error

CREATE TABLE #TBL  (Dates DATE, [Year] INT, Amt MONEY,Item Varchar(100))
INSERT INTO #TBL VALUES 
('2018-06-01',2018,34,'Milk'),('2018-07-01',2018,99,'Rice'),('2018-08-01',2018,77,'Rice'),('2018-09-01',2018,26,'Rice'),
('2018-10-01',2018,75,'Orange'),('2018-11-01',2018,94,'Grapes'),('2018-12-01',2018,80,'Grapes'),('2019-01-01',2019,9,'Grapes'),
('2019-02-01',2019,52,'Milk'),('2019-03-01',2019,28,'Orange'),('2019-04-01',2019,61,'Orange'),('2019-05-01',2019,51,'Milk');

DECLARE @cols AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME( Item) 
            FROM #TBL 
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
 SET @query = 
      'SELECT 
       * 
       INTO #Final
       FROM (
     SELECT [Year],Amt ,Item
    FROM #TBL ) FG
    PIVOT
    (
    SUM(Amt) FOR Item IN ('+@cols+')
    ) pv'
EXEC(@query)
select * from #Final
 ;DROP TABLE #TBL

error Invalid object name '#Final'.

Is it possible to insert data from dynamic pivot into a temp table

您可以使用双#语法创建一个全局临时表:INTO ## Final,它将在动态sql之外具有作用域

Try this Query...

First Drop the #Final if exists....

then create the #Final table...

then Perfrom your old Query.....will not give error Invalid object name '#Final'. this type of error

CREATE TABLE #TBL  (Dates DATE, [Year] INT, Amt MONEY,Item Varchar(100))
INSERT INTO #TBL VALUES 
('2018-06-01',2018,34,'Milk'),('2018-07-01',2018,99,'Rice'),('2018-08-01',2018,77,'Rice'),('2018-09-01',2018,26,'Rice'),
('2018-10-01',2018,75,'Orange'),('2018-11-01',2018,94,'Grapes'),('2018-12-01',2018,80,'Grapes'),('2019-01-01',2019,9,'Grapes'),
('2019-02-01',2019,52,'Milk'),('2019-03-01',2019,28,'Orange'),('2019-04-01',2019,61,'Orange'),('2019-05-01',2019,51,'Milk');



IF OBJECT_ID('tempdb..#Final', 'U') IS NOT NULL
/*Then it exists*/
DROP TABLE #Final


CREATE TABLE #Final  ([Year] INT, Amt MONEY,Item Varchar(100))


DECLARE @cols AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME( Item) 
            FROM #TBL 
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
 SET @query = 
      'SELECT 
       * 
       INTO #Final
       FROM (
     SELECT [Year],Amt ,Item
    FROM #TBL ) FG
    PIVOT
    (
    SUM(Amt) FOR Item IN ('+@cols+')
    ) pv'
EXEC(@query)
select * from #Final

DROP TABLE #TBL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM