【问题标题】:SQL Server select case when for complex if then else statementSQL Server select case when for complex if then else 语句
【发布时间】:2016-04-06 15:48:05
【问题描述】:

我正在为一个复杂的 If Then Else 语句编写一个 select case 语句,其中逻辑是

If (wp.LINE_OF_BUSINESS = 'A' or wp.LINE_OF_BUSINESS = 'U') and (wr.Relate_Code = 'in') then bf.age
else if (wp.LINE_OF_BUSINESS = 'A' or wp.LINE_OF_BUSINESS = 'U') and (wr.Relate_Code = 'je' or wr.Relate_Code = 'ji') then then bf.age2
else ba.age

如果发生 then 语句,我该如何编写这个逻辑?

谢谢

【问题讨论】:

  • 您认为哪里有困难?

标签: sql sql-server


【解决方案1】:

试试这个

 CASE WHEN wp.LINE_OF_BUSINESS IN ( 'A' , 'U')  and wr.Relate_Code = 'in' THEN bf.age
      WHEN wp.LINE_OF_BUSINESS IN ( 'A' , 'U')  and wr.Relate_Code IN ('je', 'ji') THEN bf.age2
      ELSE ba.age
 END

【讨论】:

  • or 周围使用() 否则将无法提供所需的结果。
  • 或改写为IN ('U','A')
【解决方案2】:

最干净和最简单的方法是写一个UDF

CREATE FUNCTION myAGE(@bType CHAR,  @code CHAR(2), @age1 int, @age2 int) RETURNS Int
AS 
BEGIN
 If (@bType = 'A' or @bType = 'U') and (@code = 'in') then 
    return @age1
else if (@bType = 'A' or @bType = 'U') and (@code = 'je' or @code = 'ji') then 
   return @age2
else 
   return @age1
END

然后简单地做

SELECT ..., myAge(wp.LINE_OF_BUSINESS, wr.Relate_Code, bf.age, bf.age2),...

【讨论】: