读书人

请问一个MSSQLSELECT语名的写法

发布时间: 2013-11-23 10:52:51 作者: rapoo

请教一个MSSQLSELECT语名的写法
表结构
id ids
1 3,8,83,92,215,7

传入一个值8,92要取出3,83,215,7
即是取出不存在于传入ID串其它所有ID都取出来.
请问这个SELECT 语语应该怎么写。谢谢啦 MSSQL
[解决办法]

drop table t
go

create table t(id int, ids varchar(100))

insert into t
select 1 , '3,8,83,92,215,7'
go



declare @a varchar(100) = '8,7'

;with tt
as
(
select id, ids,@a+',' as a,ids+',' as ids_t
from t
where ids like ('%' + REPLACE(@a,',', '%') + '%')
),

ttt
as
(
select id,ids,
cast(a as varchar(max)) as a,
cast(ids_t as varchar(max)) as ids_t ,
1 as level
from tt

union all

select id,ids,
cast(stuff(a,1,charindex(',',a),'') as varchar(max)) ,
cast(replace(ids_t,left(a,charindex(',',a)),'') as varchar(max)),
level + 1
from ttt
where charindex(',',a) > 0

)


select id, ids_t
from
(
select id, ids,left(ids_t,len(ids_t)-1) as ids_t,
ROW_NUMBER() over(partition by id order by level desc) as rownum
from ttt
)a
where rownum = 1
/*
idids_t
13,83,92,215
*/

[解决办法]
----------------------------------------------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2013-11-21 23:19:12
-- Version:
-- Microsoft SQL Server 2008 (SP3) - 10.0.5500.0 (Intel X86)
--Sep 22 2011 00:28:06
--Copyright (c) 1988-2008 Microsoft Corporation
--Enterprise Edition on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([id] int,[ids] varchar(15))
insert [tb]
select 1,'3,8,83,92,215,7'
--------------开始查询--------------------------
Select
a.id,ids=substring(a.ids,b.number,charindex(',',a.ids+',',b.number)-b.number)
into #tb
from
Tb a join master..spt_values b
ON B.type='p' AND B.number BETWEEN 1 AND LEN(A.ids)
where
substring(','+a.ids,b.number,1)=','

declare @str varchar(8000)

set @str = '8,105,7'

set @str = 'select ids='''+replace(@str,',',''''+' union all select ''')+''''


set @str='select ids into #temp from ('+@str+') a select * from #temp a where not exists(select 1 from #tb where ids=a.ids) drop table #tb,#temp'

exec(@str)
----------------结果----------------------------
/* ids
----
105

(1 行受影响)

*/

[解决办法]
引用:
唉呀,我真该死。我把问题给描述错了。应该是。
表结构
id ids
1 3,8,83,92,215,7

传入一个值8,105,7要取出105
即是传入的值不存在于数据库中就取出来
非常感谢上面的前辈,同时也非常抱歉,都怪我自己理解错,之前的描述错了。现在这样还能帮我解答吗?


这样:


drop table t
go

create table t(id int, ids varchar(100))

insert into t
select 1 , '3,8,83,92,215,7'
go



declare @a varchar(100) = '8,105,7'


;with tt
as
(
select
ids,
SUBSTRING(t.ids, number ,CHARINDEX(',',t.ids+',',number)-number) as v
from (select @a as ids)t,master..spt_values s
where s.number >=1
and s.type = 'P'
and SUBSTRING(','+t.ids,s.number,1) = ','
)

select tt.ids,tt.v


from tt
where not exists(select 1 from t
where CHARINDEX(','+tt.v+',',','+t.ids+',') > 0)
/*
ids v
8,105,7105
*/

读书人网 >SQL Server

热点推荐