首页 / SQL Server / 正文

[SQL Server]SQL Server数据库中从一张表的条件删除另张表数据的方法有哪些?

4037 发布于: 2018-01-10 读完约需4分钟

[SQL Server]SQL Server数据库中从一张表的条件删除另张表数据的方法有哪些?

问题描述

比如有类似如下的删除语句:

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

注:以上语句是错误的

方案一

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

方案二

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

方案三

DELETE FROM WorkRecord2 
       FROM Employee 
Where EmployeeRun=EmployeeNo
      And Company = '1' 
      AND Date = '2013-05-06'

方案四

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

或者

DELETE FROM dbo.WorkRecord2 
WHERE EXISTS(
    SELECT 1
    FROM dbo.Employee e
    WHERE EmployeeRun = e.EmployeeNo
        AND ....
)

方案五

QL Server 2008及以上版本,可以使用 MERGE 关键字:

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

版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。

上一篇: .NET[C#]LINQ中如何按实体的某个属性去重后返回不重复的集合?

下一篇: [SQL Server]SQL Server数据库中搜索包含指定关键字的所有表的数据集合的方法有哪些?

本文永久链接码友网 » [SQL Server]SQL Server数据库中从一张表的条件删除另张表数据的方法有哪些?

分享扩散:

发表评论

登录用户才能发表评论, 请 登 录 或者 注册