gpt4 book ai didi

tsql - 使用带有删除语句的交叉应用的 T-SQL

转载 作者:行者123 更新时间:2023-12-04 05:27:29 25 4
gpt4 key购买 nike

我有以下表格:

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 做到这一点更聪明、更干净?

最佳答案

我认为在这里使用交叉应用没有任何优势。这是一个简单的解决方案,可以完成这项工作:

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

关于tsql - 使用带有删除语句的交叉应用的 T-SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13027482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com