必须声明Scalar变量 - 参数中的错误

时间:2016-10-25 07:01:20

标签: sql-server reporting-services

我有一个数据集查询如下:

SELECT col1, col2
FROM Table
WHERE @DatabaseGrowth = 'DatabaseGrowthByLast7Days'

UNION ALL

SELECT col3, col4
FROM Table
WHERE @DatabaseGrowth = 'DatabaseGrowthByLast4Weeks'

并有一个名为DatabaseGrowth的参数。运行报告时,如果我选择DatabaseGrowthByLast7Days,则应返回7Days。但是,它显示错误

  

必须声明标量变量“@DatabaseGrowth”

我的数据集代码有什么问题? 上面的代码是我实际代码的示例代码。

编辑上面的代码。

3 个答案:

答案 0 :(得分:1)

尝试以下方式,如果您在SSRS数据集中使用它,则无需声明它。如果删除现有参数并将以下代码添加到数据集。它会自动创建一个名为DatabaseGrowth的参数。

SELECT col1, col2
FROM Table
WHERE 'DatabaseGrowthByLast7Days' = (@DatabaseGrowth)

UNION ALL

SELECT col3, col4
FROM Table
WHERE 'DatabaseGrowthByLast4Weeks' = (@DatabaseGrowth)

答案 1 :(得分:0)

declare @DatabaseGrowth varchar(500)= 'DatabaseGrowthByLast4Weeks'
SELECT '7Days' as val
WHERE @DatabaseGrowth = 'DatabaseGrowthByLast7Days'

UNION ALL

SELECT '4Weeks' as val
WHERE @DatabaseGrowth = 'DatabaseGrowthByLast4Weeks'

答案 2 :(得分:0)

首先,您需要声明变量@DatabaseGrowth。然后你可以使用CASE表达式:

  

评估条件列表并返回多个可能的结果表达式之一。

DECLARE @DatabaseGrowth nvarchar(max) = 'DatabaseGrowthByLast7Days'

SELECT CASE WHEN @DatabaseGrowth = 'DatabaseGrowthByLast4Weeks' THEN '4Weeks' 
            WHEN @DatabaseGrowth = 'DatabaseGrowthByLast7Days' THEN '7Days'  
            ELSE NULL END as val

或者:

SELECT CASE @DatabaseGrowth  
            WHEN 'DatabaseGrowthByLast4Weeks' THEN '4Weeks' 
            WHEN 'DatabaseGrowthByLast7Days' THEN '7Days'  
            ELSE NULL END as val

修改

根据您的修改:

DECLARE @DatabaseGrowth nvarchar(max) = 'DatabaseGrowthByLast4Weeks'

SELECT  [Col1], 
        [Col2]
FROM [Table]
WHERE @DatabaseGrowth = 'DatabaseGrowthByLast7Days'
UNION ALL
SELECT  [Col3], 
        [Col4]
FROM [Table]
WHERE @DatabaseGrowth = 'DatabaseGrowthByLast4Weeks'

请注意,[Col1]应与[Col3]的数据类型相同,[Col2][Col4]的数据类型相同。