请参阅下面的代码。除了创建数据透视表的部分之外,一切都在执行。相反,我收到以下错误:
Msg 1087, Level 15, State 2, Line 1
Must declare the table variable "@DistinctPages".
这是我的代码。请注意,有问题的表变量已声明。是什么赋予了?
--Declarations
DECLARE @groupids TABLE (groupid VARCHAR(10))
DECLARE @DistinctPages TABLE (pageno INT, groupid VARCHAR(10))
DECLARE @groupid varchar(10)
DECLARE @query NVARCHAR(MAX), @group_ids NVARCHAR(MAX), @colsNull as NVARCHAR(MAX)
--Grab groupids insert into table variable
INSERT INTO @groupids
SELECT DISTINCT groupid
FROM wv_xmlbuild
WHERE groupid <> 'wv_default'
--loop through pages by groupids insert results into table variable
WHILE EXISTS(SELECT * FROM @groupids)
BEGIN
SELECT @groupid = MIN(groupid) FROM @groupids
IF @groupid = 'FIRM'
INSERT INTO @DistinctPages (pageno, groupid)
SELECT DISTINCT wv1.pageno, wv1.groupid
FROM wv_xmlbuild wv1, wv_xmlbuild wv2
WHERE wv1.groupid = @groupid
AND wv2.groupid = 'wv_default'
AND wv1.pageno = wv2.pageno
AND wv1.n = wv2.n
AND ( wv1.x <> wv2.x or wv1.y <> wv2.y or wv1.o <> wv2.o or wv1.tb <> wv2.tb or wv1.l <> wv2.l )
ELSE
INSERT INTO @DistinctPages (pageno, groupid)
SELECT DISTINCT wv1.pageno, wv1.groupid
FROM wv_xmlbuild wv1, wv_xmlbuild wv2
WHERE wv1.groupid = @groupid
AND wv2.groupid = 'FIRM'
AND wv1.pageno = wv2.pageno
AND wv1.n = wv2.n
AND ( wv1.x <> wv2.x or wv1.y <> wv2.y or wv1.o <> wv2.o or wv1.tb <> wv2.tb or wv1.l <> wv2.l )
DELETE FROM @groupids
WHERE groupid = @groupid
END
--create pivot table
SELECT @group_ids = STUFF(( SELECT DISTINCT '],[' + LTRIM(groupid)
FROM @DistinctPages
ORDER BY '],[' + LTRIM(groupid)
FOR XML PATH('')
), 1,2, '') + ']'
SELECT @colsNull = STUFF((SELECT ', coalesce(' + QUOTENAME(groupid) +', ''--'') as '+QUOTENAME(groupid)
FROM @DistinctPages
GROUP BY groupid
ORDER BY groupid
FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'')
SET @query =
'SELECT pageno, ' + @colsNull + ' FROM (SELECT pageno, groupid, flag =''X'' FROM @DistinctPages)t
PIVOT (MAX(flag) FOR groupid
IN ('+@group_ids+')) AS CustomizedPagesPerGroups'
EXECUTE (@query)