How to Delete using INNER JOIN with SQL Server?

后端 未结 16 1751
刺人心
刺人心 2020-11-22 10:50

I want to delete using INNER JOIN in SQL Server 2008.

But I get this error:

Msg 156, Level 15, State 1, Line 15<

16条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 11:28

    You don't specify the tables for Company and Date, you might want to fix that.

    Standard SQL using MERGE:

    MERGE WorkRecord2 T
       USING Employee S
          ON T.EmployeeRun = S.EmployeeNo
             AND Company = '1'
             AND Date = '2013-05-06'
    WHEN MATCHED THEN DELETE;
    

    The answer from @Devart is also Standard SQL though incomplete, should look more like this:

    DELETE 
      FROM WorkRecord2
      WHERE EXISTS ( SELECT *
                       FROM Employee S
                      WHERE S.EmployeeNo = WorkRecord2.EmployeeRun
                            AND Company = '1'
                            AND Date = '2013-05-06' );
    

    The important thing to note about the above is it is clear the delete is targeting a single table, as enforced in the second example by requiring a scalar subquery.

    For me the various proprietary syntax answers are harder to read and understand. I guess the mindset for is best described in the answer by @frans eilering i.e. the person writing the code doesn't necessarily care about the person who will read and maintain the code.

提交回复
热议问题