【问题标题】:case statement in WHERE clause with column name as the condition以列名作为条件的 WHERE 子句中的 case 语句
【发布时间】:2014-02-07 05:40:54
【问题描述】:

我正在尝试在 where 子句中进行选择,其中 case 语句的结果是列名。

这是我尝试过的:

declare @lang int -- this is passed to the stored procedure
declare @productname nvarchar(300) -- this is passed to the stored procedure

select productid from products where

    case 
    when @lang = 1 then producten
    when @lang = 2 then productit
    when @lang = 3 then productde
    end product like @productname

所以,对于英语 (@lang = 1) 我想要:

select productid from products where producten like @productname

虽然我遇到了错误,但不确定自己做错了什么。

【问题讨论】:

    标签: sql tsql


    【解决方案1】:

    你想这样表达:

    case when @lang = 1 then producten
         when @lang = 2 then productit
         when @lang = 3 then productde
    end like @productname
    

    或者,也许更清楚:

    when @lang = 1 and producten like @productname or
         @lang = 2 and productit like @productname or
         @lang = 3 and productde like @productname
    

    【讨论】:

      【解决方案2】:

      您可以将查询重写为:

      declare @lang int -- this is passed to the stored procedure
      declare @productname nvarchar(300) -- this is passed to the stored procedure
      
      select productid from products 
      where 1= case when @lang = 1 and @productname like producten then 1
                    when @lang = 2 and @productname like productit then 1
                    when @lang = 3 and @productname like productde then 1
               end
      

      【讨论】:

        猜你喜欢
        • 2014-09-08
        • 2011-08-21
        • 2020-03-26
        • 2017-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-09
        相关资源
        最近更新 更多