首页 > 解决方案 > 连接 SQL 变量中的 CASE 值

问题描述

我试图将匹配的大小写值放在 T-SQL 中的变量中。所以我的情况是,如果 case 是 MATCHED,那么它应该保存在 varibales 中,如果不是,则跳过 case 语句。所以我试图连接所有匹配的案例并将结果保存在一个 @Result 变量中。这是我的 sql 查询:

declare @result varchar(200)
set @result=''

select 
    case 
        when 1=1 then @result=@result+'CASE 1' 
        when 1=2 then @result=@result+'CASE 2' 
        when 2=2 then @result=@result+'CASE 3'
    end

在这里我需要一个类似的结果: CASE 1 ; CASE 3 因为 CASE 1 和 CASE 3 匹配,而 CASE 2 不匹配。

但是在运行这个查询之后,我得到了错误:

消息 102,级别 15,状态 1,第 8 行 '=' 附近的语法不正确。

谁能帮我运行这个查询?

标签: sqlsql-server

解决方案


你可以使用case这样的:

select @result = @result +
                 (case when 1=1 then 'CASE 1' else '' end) +
                 (case when 1=2 then 'CASE 2' else '' end) +
                 (case when 2=2 then 'CASE 3' else '' end) ;

推荐阅读