声明表变量,其列与第二个表中的行一样

时间:2019-05-16 09:14:04

标签: sql sql-server

我在数据库中有一个ID为ID的表。我想声明表变量的列与id表中的id数量一样多(现在是16,但将来会更多)。

enter image description here

列名必须是id名称。

enter image description here

我尝试使用table_cursor和创建表变量的动态查询。它的工作,但在未来它带来了很多麻烦。无需动态查询就可以创建表变量吗?

1 个答案:

答案 0 :(得分:1)

尝试

IF OBJECT_ID('dbo.TempTable') IS NOT NULL
DROP TABLE TempTable
CREATE TABLE TempTable (Id INT IDENTITY,
                        Status_name varchar(30),
                        [Count] INT
                        )
INSERT INTO TempTable(Status_name,[Count])
SELECT 'in_Work'    , 28 UNION ALL
SELECT 'in_reserve' , 44 UNION ALL
SELECT 'Planned_Stop'   , 78 UNION ALL
SELECT '_empty' , 55 UNION ALL
SELECT 'Waiting'    , 43 

DECLARE @Sql nvarchar(max),
        @DynamicColumn nvarchar(max),
        @MaxDynamicColumn nvarchar(max)

SELECT @DynamicColumn = STUFF((SELECT DISTINCT', '+QUOTENAME(CAST(Id AS VARCHAR(10)))
FROM TempTable  FOR XML PATH ('')),1,1,'') 

SELECT @MaxDynamicColumn = STUFF((SELECT DISTINCT', '+'MAX('+QUOTENAME(CAST(Id AS VARCHAR(10)))+') AS '+QUOTENAME('_'+CAST(Id AS VARCHAR(10)))
FROM TempTable  FOR XML PATH ('')),1,1,'') 

SET @Sql='SELECT  '+ @MaxDynamicColumn+'
            FROM
            (
            SELECT *
            FROM TempTable o
            )AS src
            PIVOT 
            (
            MAX([Count]) FOR [Id] IN ('+@DynamicColumn+')
            ) AS Pvt
            '
EXEC (@Sql)
PRINT @Sql