SQL UPDATE statement with WHERE EXISTS

前端 未结 6 838
天涯浪人
天涯浪人 2021-02-07 10:09

Im trying to write a query that updates a date only if the group im updating has a LINE_CD of 50. Would i do it like this?

UPDATE EMPLOYER_ADDL  
SET EMPLOYER_A         


        
相关标签:
6条回答
  • 2021-02-07 10:27

    What about this?

    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
    
    0 讨论(0)
  • 2021-02-07 10:29

    Assuming that GR_NBR is a PK and distinct in 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
    
    0 讨论(0)
  • 2021-02-07 10:32

    I believe this will give you same result.

    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
    
    0 讨论(0)
  • 2021-02-07 10:33

    Try with this also. I think this is new for you ?

    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
    
    0 讨论(0)
  • 2021-02-07 10:44
    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
      );
    

    However, if you can derive this information from a query, why update the table? Seems like this will have to be run constantly else risk being out of date.

    0 讨论(0)
  • 2021-02-07 10:50

    I believe exists requires a wildcard:

    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
         )
    

    I prefer using IN though. Some argue that it can be slower, but I have found the SQL optimizer in 2005 and higher make IN work the same as EXISTS if the field is a non-null field.

    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
         )
    
    0 讨论(0)
提交回复
热议问题