2010-05-06 56 views
4

嗨我的同事來找我這個錯誤,現在我迷上了,並試圖找出它,希望有些專家可以幫助我們! 非常感謝! 當我執行第六步:我們得到這個錯誤:SQL數據透視表錯誤使用變量給出語法錯誤

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 
+0

+1用於發佈有用的DDL! – 2010-05-06 21:35:33

+0

+1耶!我同意馬丁! – Claudia 2010-05-07 17:21:40

回答

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 
0

@馬丁·史密斯將是正確的......當你到你的下一個錯誤。 :-)

至於@cols附近的錯誤,我認爲你可以把整個東西包裝在括號中。例如:

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, '') + ']' 
       )