通过逗号动态查询T sql CONCAT

时间:2015-09-02 08:31:00

标签: sql-server tsql pivot

我有动态sql查询,如下所示。

DECLARE @cols   AS NVARCHAR(MAX) = '[0],[3],[11]',
        @query    AS NVARCHAR(MAX)

SET @query = N'SELECT * FROM 
                (
                   SELECT 
                   year(createdDate) as [year],month(createdDate) as [month],cp.product_Id as product_ID,cp.salesprice as Amount 
                   FROM customer_products cp               
               )s 
               PIVOT 
               (
               SUM(Amount) 
               FOR product_Id IN ( '+ @cols +' )) 
AS pvt;' 

EXECUTE(@query)

问题:

以上查询有效,但由于

,查询无法正常工作
 SELECT @cols = CONCAT(@cols, '[', cast(product_ID as varchar),']') FROM Product

code block.Error在

附近显示语法错误
DECLARE @cols   AS NVARCHAR(MAX)  = '',
        @query    AS NVARCHAR(MAX)

SELECT @cols = CONCAT(@cols, '[', cast(product_ID as varchar),'],') FROM Product

    SET @query = N'SELECT * FROM 
                    (
                       SELECT 
                       year(createdDate) as [year],month(createdDate) as [month],cp.product_Id as product_ID,cp.salesprice as Amount 
                       FROM customer_products cp               
                   )s 
                   PIVOT 
                   (
                   SUM(Amount) 
                   FOR product_Id IN ( '+ @cols +' )) 
    AS pvt;' 

    EXECUTE(@query)

从产品中选择productID时,我错过了上述查询中缺少的内容?

2 个答案:

答案 0 :(得分:2)

您需要从@cols删除最后,,添加

SET @cols = LEFT(@cols, LEN(@cols) - 1)

您可以考虑使用XML代替CONCAT,如:

SELECT @cols = STUFF((SELECT ',' + QUOTENAME(CAST(product_ID as VARCHAR(10)))
                      FROM Products
                      FOR XML PATH(''), TYPE
                     ).value('.', 'NVARCHAR(MAX)') 
                    , 1, 1, '');

定义cast(product_ID as varchar(10))

的长度是一种很好的做法

答案 1 :(得分:1)

您需要确保从选择列表中删除最后一个逗号,或者您将空值传递给# categories.yml Kategorie: sport: name: Sport muzyka: name: Muzyka internet: name: Internet

使用此:

PIVOT