如何判断多个值在表中是否存在,并提示出不存在的值

qq35713304 2011-11-04 02:15:14
如何判断多个值在表中存在,并提示出不存在的值

例如
姓名:张三、李四、王五、马六

如何判断这4个人名在表中存在,并提示不存在的人名?



用 select xm from table where xm in('张三','李四','王五','马六');只能得到记录数,不能提示不存在的值

1个1个判断太麻烦了,有没有简单的办法?
...全文
114 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
TimZhuFaith 2011-11-04
  • 打赏
  • 举报
回复

if exists(select 1 from sysobjects where name = 'test' )
drop table test
go
create table test
(
id int identity(1,1),
name nvarchar(10)
)
insert test(name) select N'张三' union all select N'李四' union all select N'马六'
go
declare @m nvarchar(1000), @n nvarchar(200)

set @m = N'张三,李四,王五,马六'

declare @i int, @i2 int

create table #tmp(name nvarchar(10))

set @i = 0
while 1 = 1
begin
select @i2 = charindex(',', @m, @i)
if @i2 = 0
insert into #tmp select substring(@m, @i, len(@m) - @i + 1)
else
insert into #tmp select substring(@m, @i, @i2 - @i)
select @i = @i2 + 1
if @i2<= 0
break
end
declare @nothaving nvarchar(50)
select @nothaving = ''
select @nothaving = @nothaving + a.name + ',' from #tmp a where not exists( select 1 from test where a.name = name)
print @nothaving
drop table #tmp
TimZhuFaith 2011-11-04
  • 打赏
  • 举报
回复
拆分为临时表和实表比较
gogodiy 2011-11-04
  • 打赏
  • 举报
回复

select xm from table where xm in('张三','李四','王五','马六')
怎么会只显示记录数?

select distinct xm from table where xm not in('张三','李四','王五','马六')
显示不在这4个姓名中的其他姓名
jwdream2008 2011-11-04
  • 打赏
  • 举报
回复
 select T.xm  from 
(
select '张三' as xm
union all select '李四'
union all select '王五'
union all select '赵六'
) T
left join TB on TB.xm=T.xm
where TB.xm in('张三','李四','王五','马六')
AND TB.xm is null
--小F-- 2011-11-04
  • 打赏
  • 举报
回复
拆分了再合并。
中国风 2011-11-04
  • 打赏
  • 举报
回复


DECLARE @s NVARCHAR(2000)
SET @s=',张三,李四,王五,马六,'
select @s=REPLICATE(@s,','+xm+',',',')
from table1
SELECT @s
中国风 2011-11-04
  • 打赏
  • 举报
回复
select xm from table where xm not in('张三','李四','王五','马六');


?

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧