pav*_*red 8 sql sql-server sql-server-2005
让我们考虑我有一个表'Tab',其中有一列'Col'
表'Tab'有这个数据 -
Col
1
2
3
4
5
Run Code Online (Sandbox Code Playgroud)
如果我有一组值(2,3,6,7).我可以通过起诉查询来查询表和列表中存在的值
Select Col from Tab where col IN (2,3,6,7)
Run Code Online (Sandbox Code Playgroud)
但是,如果我想返回列表中不存在于表中的值,即在这种情况下仅返回(6,7).我应该使用什么查询?
我认为问题在于你试图在陈述中找到你的价值观。您需要做的是将 in 语句转换为表格,然后您可以确定哪些值不同。
create table #temp
(
value int
)
insert into #temp values 1
insert into #temp values 2
insert into #temp values 3
insert into #temp values 4
select
id
from
#temp
where
not exists (select 1 from Tab where Col = id)
Run Code Online (Sandbox Code Playgroud)
更好的替代方法是创建一个表值函数,将逗号分隔的字符串转换为表。我手边没有任何代码,但在谷歌上应该很容易找到。在这种情况下,您只需要使用下面的语法。
select
id
from
dbo.SplitStringToTable('2,3,6,7')
where
not exists (select 1 from Tab where Col = id)
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助
归档时间: |
|
查看次数: |
16109 次 |
最近记录: |