SQL Case语句

时间:2012-07-12 15:52:55

标签: sql-server-2008

更新1:这是我的数据。

EmployeeId    EmployeeName    Active
12312         bob             0
23432         rob             1
32312         dan             0
43432         jan             1
.........................
.........................

更新:

我正在照顾这样的事情。

EmployeeId    EmployeeName    Active
12312         bob             active
23432         rob             pending
.........................
.........................

我正在尝试解决以下sql语句并且它给我一个错误并且不确定这是否是正确的做法...

//错误: 关键字“SET”附近的语法不正确。

declare @currentStatus nvarchar(50)

Select EmployeeId,EmployeeName,Active,
       set @currentStatus = case when EmployeeId is not null and Active = 0 then "Active"  else "Pending" end as Status
from EmployeeTable

3 个答案:

答案 0 :(得分:1)

我想你应该试试这个:

SELECT EmployeeId, EmployeeName, CASE 
       WHEN (EmployeeId IS NOT NULL AND Active = 0) THEN 'Active' ELSE 'Pending' 
       END AS [Status]  
FROM EmployeeTable

答案 1 :(得分:0)

Select EmployeeId,EmployeeName,Active,
       case when EmployeeId is not null and Active = 0 then 'Active'  else 'Pending' end as Status
from EmployeeTable

如果您需要设置@CurrentStatus变量,那么您需要单独执行此操作:

Set @currentStatus = case when EmployeeId is not null and Active = 0 then 'Active'  else 'Pending' end 
from EmployeeTable

答案 2 :(得分:0)

要获得您在更新后的问题中显示的结果,这是您需要的唯一查询。我不知道为什么你认为你需要一个局部变量来保存每一行的case表达式的结果。

SELECT 
  EmployeeId,
  EmployeeName,
  Active,
  [Status] = CASE WHEN EmployeeId IS NOT NULL AND Active = 0 
     THEN 'Active' 
     ELSE 'Pending' END
FROM dbo.EmployeeTable;
使用提供的示例数据更新了

EDIT

DECLARE @e TABLE(EmployeeID INT, EmployeeName VARCHAR(32), Active BIT);

INSERT @e VALUES
(12312,'bob',0),
(23432,'rob',1),
(32312,'dan',0),
(43432,'jan',1);

SELECT 
  EmployeeId,
  EmployeeName,
  Active,
  [Status] = CASE WHEN EmployeeId IS NOT NULL AND Active = 0 
     THEN 'Active' 
     ELSE 'Pending' END
FROM @e;

结果:

EmployeeId  EmployeeName  Active  Status
12312       bob           0       Active
23432       rob           1       Pending
32312       dan           0       Active
43432       jan           1       Pending