带有WHERE EXISTS的SQL UPDATE语句

时间:2012-01-26 19:15:52

标签: sql sql-server

我试图写一个更新日期的查询,只有当我更新的组的LINE_CD为50.我会这样做吗?

UPDATE EMPLOYER_ADDL  
SET EMPLOYER_ADDL.GTL_UW_APPRV_DT = EMPLOYER_ADDL.DNTL_UW_APPRV_DT 
WHERE EXISTS
    ( 
      SELECT EMP_PLAN_LINE_INFO.LINE_CD
      FROM EMP_PLAN_LINE_INFO
      Where EMP_PLAN_LINE_INFO.GR_NBR = EMPLOYER_ADDL.GR_NBR and
       EMP_PLAN_LINE_INFO.LINE_CD = 50
     )

6 个答案:

答案 0 :(得分:13)

UPDATE ea
  SET GTL_UW_APPRV_DT = DNTL_UW_APPRV_DT
  FROM EMPLOYER_ADDL AS ea
  WHERE EXISTS
  (
    SELECT 1
      FROM EMP_PLAN_LINE_INFO AS ep
      WHERE ep.GR_NBR = ea.GR_NBR
      AND ep.LINE_CD = 50
  );

但是,如果您可以从查询中获取此信息,为什么要更新表?似乎这样必须经常运行,否则风险就会过时。

答案 1 :(得分:9)

这个怎么样?

UPDATE ea  
SET ea.GTL_UW_APPRV_DT = ea.DNTL_UW_APPRV_DT 
FROM EMPLOYER_ADDL ea
    INNER JOIN EMP_PLAN_LINE_INFO ei ON(ei.GR_NBR = ea.GR_NBR)
WHERE 
ei.LINE_CD = 50

答案 2 :(得分:6)

我相信这会给你相同的结果。

UPDATE ea
  SET GTL_UW_APPRV_DT = DNTL_UW_APPRV_DT
  FROM EMPLOYER_ADDL AS ea
  INNER JOIN EMP_PLAN_LINE_INFO AS ep
      ON ep.GR_NBR = ea.GR_NBR
      AND ep.LINE_CD = 50

答案 3 :(得分:4)

假设GR_NBR是一个PK而且在EMP_Plan_line_Info中是不同的:

UPDATE  EA
SET     GTL_UW_APPRV_DT = DNTL_UW_APPRV_DT
FROM    EMPLOYER_ADDL EA
        INNER JOIN EMP_PLAN_LINE_INFO EP
            ON EP.GR_NBR = EA.GR_NBR
               AND EP.LINE_CD = 50

答案 4 :(得分:2)

也尝试这个。我认为这对你来说是新的吗?

UPDATE ADDL   
SET ADDL.GTL_UW_APPRV_DT = ADDL.DNTL_UW_APPRV_DT 
From EMPLOYER_ADDL ADDL
Inner Join  EMP_PLAN_LINE_INFO INFO on INFO.GR_NBR = ADDL.GR_NBR
Where INFO.LINE_CD = 50

答案 5 :(得分:1)

我认为存在需要一个通配符:

UPDATE EMPLOYER_ADDL  
SET EMPLOYER_ADDL.GTL_UW_APPRV_DT = EMPLOYER_ADDL.DNTL_UW_APPRV_DT 
WHERE EXISTS
    ( 
      SELECT *
      FROM EMP_PLAN_LINE_INFO
      Where EMP_PLAN_LINE_INFO.GR_NBR = EMPLOYER_ADDL.GR_NBR and
       EMP_PLAN_LINE_INFO.LINE_CD = 50
     )

我更喜欢使用IN。有些人认为它可能会更慢,但是如果字段是非空字段,我在2005年发现了SQL优化器,并且更高的使得IN工作与EXISTS相同。

UPDATE EMPLOYER_ADDL  
SET EMPLOYER_ADDL.GTL_UW_APPRV_DT = EMPLOYER_ADDL.DNTL_UW_APPRV_DT 
WHERE EMPLOYER_ADDL.GR_NBR IN
    ( 
      SELECT EMP_PLAN_LINE_INFO.GR_NBR
      FROM EMP_PLAN_LINE_INFO
      Where EMP_PLAN_LINE_INFO.LINE_CD = 50
     )