如何正确使用案例陈述?如何使用case语句与where或join表?

时间:2014-10-10 17:32:20

标签: sql sql-server sql-server-2008 tsql

我试图用name1替换所有password1 = 1的显示值,用name2替换password2 = 1而不改变数据库中的实际值。但是当我执行代码时,系统返回:

“pg 4145,第15级,状态1,第22行 在预期条件的上下文中指定的非布尔类型的表达式,在“Order”附近。“

我有输出:


  • name1,name2,GateCode,password1,password2,state


  • Ryan,Lisa,1,3214,4564,FL

  • Brandon,Joan,2,5324,1,NV
  • Leo,Ben,3,1,1,WA

我想要的输出


  • name1,name2,GateCode,password1,password2,state


  • Ryan,Lisa,1,3214,4564,FL

  • Brandon,Joan,2,5324,Joan,NV
  • Leo,Ben,3,Leo,Ben,WA

这是我的代码:

Select Top 10 
   g.name1 as 'name1'
 , g.name1 as 'name2'
 , c.gateCode as GateCode
 , c.pas1 as 'password1'
 , c.pas2 as 'password2'
 , g.state as 'state'
from guest g
     Left code c
     on g.guest_cdoe = c.guest_code 
Where 
  CASE 
      WHEN password1 = 1 and g.guest_cdoe = c.guest_code
      Then ba.bank_name1
      WHEN password2 = 2 and g.guest_cdoe = c.guest_code
      Then ba.bank_name1
  End
Order by 3

1 个答案:

答案 0 :(得分:1)

我想这就是你想要的......很难说但是应该指出你正确的方向。您希望select语句中的case不是where语句。

Select Top 10 
   g.name1 as 'name1'
 , g.name2 as 'name2'
 , c.gateCode as GateCode
 , CASE 
      WHEN c.pas1 = 1 and g.guest_cdoe = c.guest_code
      THEN g.name1 
      ELSE c.pas1
   END
 , CASE 
      WHEN c.pas2 = 1 and g.guest_cdoe = c.guest_code
      THEN g.name2 
      ELSE c.pas2
   END
 , g.state as 'state'
from guest g
     Left code c
     on g.guest_cdoe = c.guest_code 
Order by 3