How to Delete using INNER JOIN with SQL Server?

2019-01-01 06:13发布

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

But I get this error:

Msg 156, Level 15, State 1, Line 15
Incorrect syntax near the keyword 'INNER'.

My code:

DELETE FROM WorkRecord2 
INNER JOIN Employee ON EmployeeRun=EmployeeNo
WHERE Company = '1' AND Date = '2013-05-06'

16条回答
君临天下
2楼-- · 2019-01-01 06:27

Here's what I currently use for deleting or even, updating:

DELETE FROM      w
FROM             WorkRecord2   w,
                 Employee      e
WHERE            w.EmployeeRun = e.EmployeeNo
             AND w.Company = '1' 
             AND w.Date = '2013-05-06'
查看更多
旧人旧事旧时光
3楼-- · 2019-01-01 06:29

Try this, it might help

 DELETE WorkRecord2 
          FROM WorkRecord2 
    INNER JOIN Employee 
            ON EmployeeRun=EmployeeNo
         WHERE Company = '1' 
           AND Date = '2013-05-06';
查看更多
泛滥B
4楼-- · 2019-01-01 06:30

This version should works

DELETE WorkRecord2
FROM WorkRecord2 
INNER JOIN Employee ON EmployeeRun=EmployeeNo
Where Company = '1' AND Date = '2013-05-06'
查看更多
残风、尘缘若梦
5楼-- · 2019-01-01 06:30

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.

查看更多
姐姐魅力值爆表
6楼-- · 2019-01-01 06:31

Another way using CTE.

;WITH cte 
     AS (SELECT * 
         FROM   workrecord2 w 
         WHERE  EXISTS (SELECT 1 
                        FROM   employee e 
                        WHERE  employeerun = employeeno 
                               AND company = '1' 
                               AND date = '2013-05-06')) 
DELETE FROM cte 

Note : We cannot use JOIN inside CTE when you want to delete.

查看更多
萌妹纸的霸气范
7楼-- · 2019-01-01 06:32

Possible this be helpful for you -

DELETE FROM dbo.WorkRecord2 
WHERE EmployeeRun IN (
    SELECT e.EmployeeNo
    FROM dbo.Employee e
    WHERE ...
)

Or try this -

DELETE FROM dbo.WorkRecord2 
WHERE EXISTS(
    SELECT 1
    FROM dbo.Employee e
    WHERE EmployeeRun = e.EmployeeNo
        AND ....
)
查看更多
登录 后发表回答