将sp_executesql与SSRS参数一起用作数据集

时间:2016-03-22 15:09:52

标签: sql sql-server-2008 reporting-services

我在SSRS数据集中使用以下查询来创建数据透视表,该数据表返回非特定年份的数据。即我总是返回过去3年的数据。

这是代码

IF @filter = 'All'
    BEGIN  
       DECLARE @SQLEXP1 AS NVARCHAR(MAX);
       DECLARE @Y1 AS INT;
       DECLARE @Y2 AS INT;
       DECLARE @Y3 AS INT;
       DECLARE @cols1 AS NVARCHAR(MAX);
       DECLARE @cols2 AS NVARCHAR(MAX);
       DECLARE @cols3 AS NVARCHAR(MAX);
       SET @Y1 = YEAR(GETDATE()) - 3;
       SET @Y2 = YEAR(GETDATE()) - 2;
       SET @Y3 = YEAR(GETDATE()) - 1;
       SET @cols1 = N'['+CAST(@Y1 AS NVARCHAR(10))+N']';
       SET @cols2 = N'['+CAST(@Y2 AS NVARCHAR(10))+N']';
       SET @cols3 = N'['+CAST(@Y3 AS NVARCHAR(10))+N']';
       SELECT CAST('' AS VARCHAR(20)) AS ITEMNMBR
           , CAST('' AS VARCHAR(80)) AS ITEMDESC
           , CAST(0 AS BIGINT) AS QTYAVAILABLE
           , CAST(0 AS BIGINT) AS QTYSOLDYTD
           , CAST(0 AS BIGINT) AS QTYSOLD
           , CAST(0 AS BIGINT) AS FISCALYEAR
           , CAST(0 AS BIGINT) AS YEAR1
           , CAST(0 AS BIGINT) AS YEAR2
           , CAST(0 AS BIGINT) AS YEAR3;
       SET @SQLEXP1 = 'SELECT * 
                    FROM (SELECT ITEMNMBR
                             ,ITEMDESC
                             ,QTYAVAILABLE
                             ,QTYSOLDYTD
                             ,QTYSOLD
                             ,FISCALYEAR 
                        FROM VIEW_SALES_ITEM_FOR_PLANNING_BY_YEAR 
                        WHERE FISCALYEAR >= YEAR(GETDATE())-3 ) T0 
                    PIVOT (sum(qtysold) for FISCALYEAR in ('+@cols1+','+@cols2+','+@cols3+')) T1 
                    WHERE itemnmbr in ( '+' '+@itemno+')';
       PRINT @SQLEXP1
       EXEC Sp_executesql @SQLEXP1;
    END;

我的问题是粗体项目。变量@itemno是SSRS参数。无论我如何配置它,我总是在运行报告时出错。在“,”附近有一个错误的结果。如何在使用sp_executesql命令的上下文中使用我的SSRS参数?

1 个答案:

答案 0 :(得分:0)

您必须将 itemno 转换为字符串并将其连接到查询字符串中。

'select * from table where itemno = '+cast(@itemno as varchar(10))+'''