日期:2014-05-17 浏览次数:20537 次
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-12-25 17:27:29
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
-- Dec 28 2012 20:23:12
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[A]
if object_id('[A]') is not null drop table [A]
go
create table [A]([id] varchar(6))
insert [A]
select '12,2,3' union all
select '1,4,5'
--> 测试数据:[B]
if object_id('[B]') is not null drop table [B]
go
create table [B]([id] int)
insert [B]
select 1 union all
select 2 union all
select 3 union all
select 4 union all
select 5 union all
select 6 union all
select 7
--------------开始查询--------------------------
;WITH cte AS
(select
CONVERT(varchar(2),SUBSTRING([id],number,CHARINDEX(',',[id]+',',number)-number)) as [id]
from
[A] a,master..spt_values
where
number >=1 and number<=len([id])
and type='p'
and substring(','+[id],number,1)=',')
select b.* from [B] b LEFT JOIN cte a ON b.id=a.id
WHERE a.id IS NULL
/*
id
-----------
6
7
*/