如何根据 T-SQL 中动态 SQL 语句的结果创建新的 table

How do I create a new table from the results of a dynamic SQL statement in T-SQL

我正在尝试使用这个动态 SQL 语句的结果来创建一个新的 table

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

SET @cols = STUFF((SELECT DISTINCT
                       ',' + QUOTENAME(c.[ClassCode])
                   FROM [Sandbox].[dbo].Test2 c 
                   FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)'), 1, 1, '');

SET @query = 'SELECT [Name_ID], ' + @cols + 
             'FROM (SELECT [Name_ID],
                           [ClassCodeYN] AS [amount],
                           [ClassCode] AS [category]
                    FROM [Sandbox].[dbo].[Test2]) x 
              PIVOT (COUNT(amount) FOR category IN (' + @cols + ')) p';

EXECUTE @query

我试过使用 INSERT INTOCREATE TABLE 并获得

Incorrect syntax near the keyword 'EXECUTE'

Must DECLARE @query

错误。

您应该可以将 into <table> 添加到现有查询中:

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

SET @cols = STUFF((SELECT DISTINCT
                       ',' + QUOTENAME(c.[ClassCode])
                   FROM [Sandbox].[dbo].Test2 c 
                   FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)'), 1, 1, '');

SET @query = 'SELECT [Name_ID], ' + @cols + 
             ' INTO MyTable' +
             ' FROM (SELECT [Name_ID],
                           [ClassCodeYN] AS [amount],
                           [ClassCode] AS [category]
                    FROM [Sandbox].[dbo].[Test2]) x 
              PIVOT (COUNT(amount) FOR category IN (' + @cols + ')) p';

Exec sp_executesql @query