【问题标题】:T-SQL Using Cross-Apply with Delete Statement使用带有删除语句的交叉应用的 T-SQL
【发布时间】:2012-10-13 05:02:46
【问题描述】:

我有以下表格:

RecordID
101
102
103
104
105
106

TableOne
101
102
103
104

TableTwo


TableThree
101
102

并且我需要删除未包含在其他表中的 RecordsID 行。请注意,有时 TableOne、TableTwo、TableThree 表之一可能为空,此时不应删除任何记录。

结果表应该是:

RecordID
101
102

由于空表,我无法使用 INNER JOIN。而且因为我在函数中使用这些代码,所以我无法创建仅包含带有记录的表的动态 SQL 语句并执行它。

我可以用 IF 语句做到这一点,但在我的实际情况下,我有很多案例要检查,很多表要加入,结果会出现很多代码重复。

这就是为什么我开始想知道有没有办法通过 CROSS APPLY 更聪明、更干净地做到这一点?

【问题讨论】:

  • 答案是 105 和 106,因为它们不包含在任何其他表格中..对吗?
  • 不,您应该只删除其他表中不符合的记录。

标签: tsql sql-server-2012 cross-apply


【解决方案1】:

我没有看到在这里使用 cross apply 有什么好处。这是一个简单的解决方案:

declare @t table(recordid int)
declare @tableone table(recordid int)
declare @tabletwo table(recordid int)
declare @tablethree table(recordid int)
insert @t values(101),(102),(103),(104),(105),(106)

insert @tableone values(101),(102),(103),(104)
insert @tablethree values(101),(102)

delete t
from @t t
where not exists (select 1 from @tableone where t.recordid = recordid)
and exists (select 1 from @tableone)
or not exists (select 1 from @tabletwo where t.recordid = recordid)
and exists (select 1 from @tabletwo)
or not exists (select 1 from @tablethree where t.recordid = recordid)
and exists (select 1 from @tablethree)

结果:

recordid
101
102

【讨论】:

    【解决方案2】:

    使用除外和联合

    declare @t table(recordid int) 
    declare @tableone table(recordid int) 
    declare @tabletwo table(recordid int) 
    declare @tablethree table(recordid int) 
    insert @t values(101),(102),(103),(104),(105),(106) 
    
    insert @tableone values(101),(102),(103),(104) 
    insert @tablethree values(101),(102)
    
    delete  
    from @t where recordid not in(
    select * from @t 
    except select * from 
    (select * from  @tableone union
    select * from  @tabletwo union
    select * from  @tablethree)x)
    
    select * from @t
    
    
    recordid
    105
    106
    

    【讨论】:

    • 答案应该是 101、102,因为它们存在于除空表之外的所有表中
    猜你喜欢
    • 2016-03-30
    • 1970-01-01
    • 2011-11-27
    • 2011-11-21
    • 2015-03-15
    • 1970-01-01
    • 2015-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多