SQL Server选择case for when if then else语句

时间:2016-04-06 15:48:06

标签: sql sql-server

我正在为复杂的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

如果然后声明,我怎么能写这个逻辑?

由于

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

最干净,最简单的方法是编写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),...