日期:2014-05-18  浏览次数:20466 次

sql包含查询问题,求解决,个人感觉有点难
tableA

id info
1 1,2,3
2 1,3
3 4,5,6
4 2,4,16

如何用一句语句查出 info中包含 1,3,4的数据或是 2,3 的数据

1.查1时,第四行的16不能显示出来
2.查询的内容随机,可以用函数处理,但不能手工分解来写

如 select * from tablea where ','+info+',' like '%,1,%' or ','+info+',' like '%,2,%' 这样手工写不行,要自动处理


------解决方案--------------------
SQL code

--> 测试数据:[test]
if object_id('[test]') is not null 
drop table [test]
create table [test](
[id] int,
[info] varchar(6)
)
go
insert [test]
select 1,'1,2,3' union all
select 2,'1,3' union all
select 3,'4,5,6' union all
select 4,'2,4,16'
go


--写个存储过程:
if OBJECT_ID('pro_test')is not null
drop proc pro_test
go
create proc pro_test
(
@str varchar(20)
)
as
create table #test(
id int identity,
value int
)
--declare @str varchar(1000)
--set @str='1,2,3'
declare @sql varchar(1000)
set @sql='insert #test(value)
           select '+REPLACE(@str,',',' union all select ')
print @sql
exec(@sql)
select * from test a
where not exists(select 1 from #test b 
where CHARINDEX(','+ltrim(b.value)+',',','+a.info+',')<=0)
go
--主意,我理解的你的包含是指info字段同时包含所给字符串中的没一个数字
exec pro_test '1,3'
/*
id    info
1    1,2,3
2    1,3
*/