从相应的表中删除记录

时间:2015-12-31 07:17:00

标签: sql sql-server sql-server-2008

我在数据库中有两个表,如屏幕截图所示...... enter image description here

请注意,第二个表中的LicenceType表现为GroupId,以便对记录组进行分类。

根据业务逻辑(客户端的要求),一些记录保存在tbCompanyAgent中,如第一个表所示。

现在,如果我们根据LicenceType(Group Id)从tbLicence中删除数据 然后应该从tbCompanyAghent中删除所有相应的数据。

为此,我写了以下查询

DELETE FROM tbLicence WHERE LicenceType = @LicenceType

DELETE FROM tbCompanyAgent

SELECT * FROM tbCompanyAgent INNER JOIN tbLicence ON tbCompanyAgent.LicenceNumber = tbLicence.LicenceNumber
    OR tbCompanyAgent.LicenceNumber = tbLicence.StateIssuedLicenseNumber
    OR tbLicence.LicenceType = @LicenceType

但它没有按要求执行。请帮忙!!!

2 个答案:

答案 0 :(得分:1)

      Delete from tbCompanyAgent  
      where LicenceNumber in (select distinct LicenceNumber 
      from tbLicence where LicenceType= @LicenceType)          

      Delete from tbLicence where LicenceType = @LicenceType 

答案 1 :(得分:0)

要避免子查询,可以试试这个吗

delete a from tblCompanyAgent a 
inner join tblLicence b on a.LicenceNumber = b.LicenceNumber 
where b.LicenceType = @licenceType