请参阅下面的代码。除了创建数据透视表的部分外,一切都在执行。相反,我收到以下错误:
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)
答案 0 :(得分:3)
您在@DistinctPages
中使用EXEC(@query)
EXEC使用来自调用查询的单独上下文,这就是您收到对象错误的原因。考虑切换到临时表,或者在@query
变量中重新定义表变量,如果这是SQL Server 2008,您可以定义自定义表类型,并将@DistinctPages
传递给您的ad-hoc查询。