2

我现有的 SQL 语句

  UPDATE EMP 
  SET fte_adj = IIf((fte<1 Or fte Is Null) And [employment category] Like '*Full-Time*',1,
IIf((fte=0 Or fte Is Null) And [employment category] Like '*Part-Time*',0.25,fte));

它将更新表格EMP

set fte_adj=1
if Full time (and fte<1 or null)

set fte_adj=0.25
if part time (and fte=0 or null)

otherwise fte_adj=fte

如何添加案例以检查另一个表中是否存在employee_id 的任何记录SEC_EMP

如果没有记录(0 行),则set fte_adj=1

两个表都可以使用employee_id 作为键

谢谢

4

4 回答 4

2

我已经使用 CASE 重写了您的声明(但我意识到 IIF 在 2012 年有效):

UPDATE EMP 
SET fte_adj = 
  CASE WHEN (FTE < 1 OR FTE IS NULL) AND [employment category] Like '*Full-Time*'
    THEN 1
  ELSE
    CASE WHEN (FTE = 0 OR FTE IS NULL) AND [employment category] Like '*Part-Time*'
      THEN 0.25
    ELSE 
      CASE WHEN (SELECT COUNT(*) FROM SEC_EMP) = 0 
      THEN 1
      ELSE 
        FTE
      END
    END
  END

这是一些Fiddle示例。

如果您更喜欢 IIF 逻辑,请执行以下操作:

UPDATE EMP 
SET fte_adj = 
  IIF ( (FTE < 1 OR FTE IS NULL) AND [employment category] Like '*Full-Time*' , 1 ,
      IIF ( (FTE = 0 OR FTE IS NULL) AND [employment category] Like '*Part-Time*' , 0.25, 
          IIF ( (SELECT COUNT(*) FROM SEC_EMP) = 0 , 1 , FTE ) 
          )
       )

还有更多小提琴

- 编辑 -

如果我了解最新评论,您想更新仅存在于 SEC_EMP 表中的记录吗?如果是这样,只需像这样加入表:

UPDATE E 
SET fte_adj = 
  IIF ( (FTE < 1 OR FTE IS NULL) AND [employment category] Like '*Full-Time*' , 1 ,
      IIF ( (FTE = 0 OR FTE IS NULL) AND [employment category] Like '*Part-Time*' , 0.25, FTE 
          )
       )
FROM EMP E
  JOIN SEC_EMP SE ON E.employee_id = SE.employee_id 

还有更多小提琴

于 2013-02-15T15:54:42.690 回答
1

尝试这个:

UPDATE EMP 
SET fte_adj = CASE WHEN fte=1 Or fte Is Not Null And [employment category] Like '%Full-Time%'
THEN 1 ELSE .25 END AS 'Rate'

我还要补充

 WHERE [employment category] Like '%Full-Time%' OR [employment category] Like '%Part-Time%'

安全起见,取决于您的餐桌。这是针对 MS SQL 的,不知道 '* syntax *' 来自什么。

于 2013-02-15T15:50:34.977 回答
0

来自 sgeddes 的 case 语句的更简单版本。

UPDATE EMP 
SET fte_adj = 
    CASE WHEN (FTE < 1 OR FTE IS NULL) AND [employment category] Like '*Full-Time*'
      THEN 1
    WHEN (FTE = 0 OR FTE IS NULL) AND [employment category] Like '*Part-Time*'
      THEN 0.25
    WHEN (SELECT COUNT(*) FROM SEC_EMP) = 0 
      THEN 1
    ELSE 
        FTE
    END

与 IF 不同的 case 语句可以有多个分支。它们也会短路,所以第一个受到打击的分支就是它。所以例如

CASE WHEN 1=1
WHEN 2=2
END

永远不会越过 1=1 分支。

于 2013-02-15T16:01:16.103 回答
0

您可以IIF在相关的地方添加一个EXISTS声明:

IIF(NOT EXISTS(
    SELECT [some column] FROM [some table]
    WHERE [some condition]
), 1, [some value OR another IIF statement])
于 2013-02-15T15:43:37.210 回答