查找aaa,bbb,ccc,ddd,eee,fff中逗号间隔的数据不在表中
我有一数据aaa,bbb,ccc,ddd,eee,fff
然后有个表,里面有一列是用来存放数据 aaa bbb ccc 这样的数据
我现在想查询,我上面的数据aaa,bbb,ccc,ddd,eee,fff
哪几个不在表中?
这个数据aaa,bbb,ccc,ddd,eee,fff中逗号里面的内容去和表里的内容比较
CREATE TABLE [dbo].[Table_1](
[a] [varchar](50) NULL
) ON [PRIMARY]
insert into [Table_1](a) values('aaa');
insert into [Table_1](a) values('bbb');
insert into [Table_1](a) values('eee');
----------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-08-14 12:36:43
-- Version:
-- Microsoft SQL Server 2014 (CTP1) - 11.0.9120.5 (X64)
--Jun 10 2013 20:09:10
--Copyright (c) Microsoft Corporation
--Enterprise Evaluation Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: ) (Hypervisor)
--
----------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([key] varchar(23))
insert [huang]
select 'aaa,bbb,ccc,ddd,eee,fff'
CREATE?TABLE?[dbo].[Table_1](
????[a]?[varchar](50)?NULL
)?ON?[PRIMARY]
insert?into?[Table_1](a)?values('aaa');
insert?into?[Table_1](a)?values('bbb');
insert?into?[Table_1](a)?values('eee');
--------------开始查询--------------------------
SELECT * FROM
(
SELECT distinct
SUBSTRING([key],number,CHARINDEX(',',[key]+',',number)-number) as [key]
from
[huang] a,master..spt_values
where
number >=1 and number<len([key])
and type='p'
and substring(','+[key],number,1)=','
EXCEPT
SELECT a
FROM [Table_1])a
----------------结果----------------------------
/*
key
--------------------------------------------------
ccc
ddd
fff
*/
CREATE TABLE [dbo].[Table_1](
[a] [varchar](50) NULL
) ON [PRIMARY]
insert into [Table_1](a) values('aaa');
insert into [Table_1](a) values('bbb');
insert into [Table_1](a) values('eee');
DECLARE @i NVARCHAR(100)
SET @i = 'aaa,bbb,ccc,ddd,eee,fff'
DECLARE @idoc int;
DECLARE @doc xml;
set @doc=cast('<Root><item><S>'+replace(@i,',','</S></item><item><S>')+'</S></item></Root>' as xml)
EXEC sp_xml_preparedocument @Idoc OUTPUT, @doc
SELECT *
FROM ( SELECT *
FROM OPENXML (@Idoc, '/Root/item',2)
WITH (
[S] VARCHAR(10)
)
) A
WHERE NOT EXISTS ( SELECT 1
FROM Table_1 B
WHERE A.s = B.a )
CREATE TABLE [dbo].[Table_1](
[a] [varchar](50) NULL
) ON [PRIMARY]
insert into [Table_1](a) values('aaa');
insert into [Table_1](a) values('bbb');
insert into [Table_1](a) values('eee');
DECLARE @string VARCHAR(MAX)
SET @string = 'aaa,bbb,ccc,ddd,eee,fff'
SELECT b.string
FROM
(SELECT string=CONVERT(XML, '<root><v>'+replace(@string,',','</v><v>')+'</v></root>')) a
OUTER APPLY
(SELECT string = C.v.value('.','NVARCHAR(MAX)') FROM a.string.nodes('/root/v') C(v)) b
WHERE NOT EXISTS(SELECT 1 FROM dbo.table_1 m WHERE m.[a] = b.string)
/*
string
ccc
ddd
fff
*/