我有一个带有参数的 SQL Server 2012 sql 查询:@Region 有一个 WHERE 子句,我想根据 @Region 值设置它的值

I have a SQL Server 2012 sql query that takes a parameter: @Region There's a WHERE clause that I want to set its value based on the @Region value

我有一个带有参数 @Region 的 SQL Server 2012 查询。有一个 WHERE 子句,我想根据 @Region 值设置它的值。下面是我尝试使用的代码

case 
    when @Region = 'SW' 
       then Transact.busloc_id in (3, 7, 11)
       else Transact.busloc_id in (1, 5, 7)
end

where 子句中,您需要这样的逻辑:

where ( @Region = 'SW' and Transact.busloc_id IN (3, 7, 11) ) or
      ( @Region <> 'SW' and Transact.busloc_id IN (1, 5, 7) )

不需要 case 表达式。

注意:这假设 @region 不是 NULL。这很容易处理。

在 SQL 中设置涉及 CASE 语句的变量值的一种方法具有以下语法:

SET @Variable = CASE WHEN [condition] THEN [scalar_value] ELSE [scalar_value] END

在您的 SQL 中,您有标量值应该是的条件。如果没有关于您尝试使用 IN 子句实现的目标的更多信息,我无法提供更多答案,但是您可以 go here 获取有关 CASE 语句语法的更多信息。