-2

请参阅下面的代码。除了创建数据透视表的部分之外,一切都在执行。相反,我收到以下错误:

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)
4

1 回答 1

3

@DistinctPagesEXEC(@query) EXEC 中使用从调用查询中使用单独的上下文,这就是您收到对象错误的原因。考虑切换到临时表,或者在你的变量中重新定义表变量@query,另外,如果这是 SQL Server 2008,你可以定义一个自定义表类型,并传递@DistinctPages给你的临时查询。

于 2013-09-11T22:19:38.603 回答