SQL Pivot表错误使用变量给出了语法错误

时间:2010-05-06 21:15:19

标签: sql syntax pivot

嗨,我的同事带着这个错误来找我,现在我迷上了,试图弄明白,希望有些专家可以帮助我们! 非常感谢! 当我执行Step6时,我们收到此错误:

Msg 102, Level 15, State 1, Line 4
Incorrect syntax near '@cols'.

--Sample of pivot query

--Creating Test Table Step1
CREATE TABLE Product(Cust VARCHAR(25), Product VARCHAR(20), QTY INT)
GO
-- Inserting Data into Table Step2
INSERT INTO Product(Cust, Product, QTY)
VALUES('KATE','VEG',2)
INSERT INTO Product(Cust, Product, QTY)
VALUES('KATE','SODA',6)
INSERT INTO Product(Cust, Product, QTY)
VALUES('KATE','MILK',1)
INSERT INTO Product(Cust, Product, QTY)
VALUES('KATE','BEER',12)
INSERT INTO Product(Cust, Product, QTY)
VALUES('FRED','MILK',3)
INSERT INTO Product(Cust, Product, QTY)
VALUES('FRED','BEER',24)
INSERT INTO Product(Cust, Product, QTY)
VALUES('KATE','VEG',3)
GO
-- Selecting and checking entires in table Step3
SELECT *
FROM Product
GO
-- Pivot Table ordered by PRODUCT Step4

select *
FROM (
SELECT *
FROM Product) up
PIVOT (SUM(QTY) FOR CUST IN ([FRED], [KATE])) AS pvt
ORDER BY PRODUCT
GO

--dynamic pivot???? Step5

DECLARE @cols NVARCHAR(2000)
select @cols =   STUFF(( SELECT DISTINCT TOP 100 PERCENT
                                '],[' + b.Cust
                        FROM    (select top 100 Cust
        from tblProduct)b
                        ORDER BY '],[' + b.Cust
                        FOR XML PATH('')
                      ), 1, 2, '') + ']'

--Show Step6

SELECT *
FROM (SELECT *
FROM tblProduct) p
PIVOT (SUM(QTY) FOR CUST IN (@cols)) as pvt
Order by Product

2 个答案:

答案 0 :(得分:1)

不幸的是,你需要动态SQL。

declare @dyn nvarchar(max)
set @dyn = 'SELECT *
FROM (SELECT *
FROM Product) p
PIVOT (SUM(QTY) FOR CUST IN ('  +  @cols +')) as pvt
Order by Product
'
exec sp_executesql @dyn

答案 1 :(得分:0)

@Martin Smith将是正确的......当你遇到下一个错误时。 : - )

对于@cols附近的错误,我认为你可以将整个事物包裹在括号中。 E.g:

select @cols = (
                   STUFF(( SELECT DISTINCT TOP 100 PERCENT
                                '],[' + b.Cust
                           FROM    (select top 100 Cust
                                    from tblProduct)b
                           ORDER BY '],[' + b.Cust
                           FOR XML PATH('')
                        ), 1, 2, '') + ']'
               )