动态SQL SQL Server 2012将结果输入#temp表

时间:2016-11-05 19:26:00

标签: sql sql-server tsql sql-server-2012

我正在使用SQL Server 2012.我希望将@sql的最终结果导入临时表。到目前为止,这是我的代码。谢谢你的帮助。

IF OBJECT_ID ('tempdb.dbo.#MY_DT_CTE') IS NOT NULL DROP TABLE #MY_DT_CTE
CREATE TABLE #MY_DT_CTE
([ROWID] INT NOT NULL IDENTITY (1,1)
,[YYYYMM] INT
)
; WITH MY_DT_CTE AS
(
SELECT CONVERT(INT,CONVERT(VARCHAR(6),EOMONTH(GETDATE(),-1),112)) AS [YYYYMM]
UNION
SELECT CONVERT(INT,CONVERT(VARCHAR(6),EOMONTH(GETDATE(),-2),112)) AS [YYYYMM]
UNION
SELECT CONVERT(INT,CONVERT(VARCHAR(6),EOMONTH(GETDATE(),-3),112)) AS [YYYYMM]
UNION
SELECT CONVERT(INT,CONVERT(VARCHAR(6),EOMONTH(GETDATE(),-4),112)) AS [YYYYMM]
UNION
SELECT CONVERT(INT,CONVERT(VARCHAR(6),EOMONTH(GETDATE(),-5),112)) AS [YYYYMM]
UNION
SELECT CONVERT(INT,CONVERT(VARCHAR(6),EOMONTH(GETDATE(),-6),112)) AS [YYYYMM]
)
INSERT INTO #MY_DT_CTE
SELECT [YYYYMM] FROM MY_DT_CTE
ORDER BY [YYYYMM] DESC;
-- SELECT * FROM #MY_DT_CTE

DECLARE @columns NVARCHAR(MAX), @sql NVARCHAR(MAX);
SET @columns = N'';
SELECT @columns += N', p.' + QUOTENAME(YYYYMM)
FROM (SELECT p.YYYYMM FROM #MY_DT_CTE AS p
GROUP BY p.YYYYMM) AS x;
SET @sql = N'
SELECT ' + STUFF(@columns, 1, 2, '') + '
FROM
(
SELECT p.YYYYMM FROM #MY_DT_CTE AS p
) AS j
PIVOT
(
COUNT(YYYYMM) FOR YYYYMM IN ('
+ STUFF(REPLACE(@columns, ', p.[', ',['), 1, 1,
'')
+ ')
) AS p;';
PRINT @sql;
EXEC sp_executesql @sql;

需要将此结果@sql引入临时表。 201605 201606 201607 201608 201609 201610

1 个答案:

答案 0 :(得分:1)

一种简单的方法是使用全局临时表。这可以在动态SQL作用域中selected into自动拥有所需的模式,并在退出后仍然可用。

SET @sql = N'
SELECT ' + STUFF(@columns, 1, 2, '') + '
INTO ##GlobalTemp
FROM
(
SELECT p.YYYYMM FROM #MY_DT_CTE AS p
) AS j
PIVOT
(
COUNT(YYYYMM) FOR YYYYMM IN (' + STUFF(REPLACE(@columns, ', p.[', ',['), 1, 1, '') + ')
) AS p;';

EXEC sp_executesql @sql;

SELECT *
FROM   ##GlobalTemp 

但是,如果代码同时执行,这可能会导致命名冲突问题。

可以使用本地临时表,但代码更复杂,因为它涉及在较高范围创建临时表,然后使用动态SQL将其更改为动态确定的模式,然后插入其中。

CREATE TABLE #T
  (
     Dummy INT
  );

SET @sql = 'ALTER TABLE #T ADD   Dummy2 INT' + REPLACE(REPLACE(@columns, 'p.', ''), ']', '] int') + ';
            ALTER TABLE #T DROP COLUMN Dummy, Dummy2;'

EXEC (@sql);

SET @sql = N'
INSERT INTO #T
SELECT ' + STUFF(@columns, 1, 2, '') + '
FROM
(
SELECT p.YYYYMM FROM #MY_DT_CTE AS p
) AS j
PIVOT
(
COUNT(YYYYMM) FOR YYYYMM IN (' + STUFF(REPLACE(@columns, ', p.[', ',['), 1, 1, '') + ')
) AS p;';

EXEC sp_executesql @sql;

SELECT *
FROM   #T