表A
----------------------------------
ids
2,21,23,27
1,7,11,12
5
6,8
----------------------------------
我现在传一个条件 2,9,11 如何判断这里里面的2和11已经在表A里面了
------解决方案--------------------
CHARINDEX
------解决方案--------------------
2,9,11 分割
然后再和ids匹配
------解决方案--------------------
- SQL code
select * from tb where charindex(',2,',','+ids+',')>0 or charindex(',11,',','+ids+',')>0
------解决方案--------------------
- SQL code
select * from tb where charindex(',2,',','+ids+',')>0 or charindex(',11,',','+ids+',')>0
------解决方案--------------------
- SQL code
create table A(ids varchar(100))insert into Aselect '2,21,23,27' union allselect '1,7,11,12' union allselect '5' union allselect '6,8'godeclare @M varchar(50), @N xml set @M='2,9,11'set @N=convert(xml,'<r><c>'+replace(@M,',','</c><c>')+'</c></r>');with cte as( select col=T.c.value('.[1]','varchar(20)') from @N.nodes('/r/c') T(c))select a.colfrom cte a left join A b on charindex(','+a.col+',',','+b.ids+',') > 0where b.ids is nulldrop table A/************col--------------------9(1 行受影响)
------解决方案--------------------
- SQL code
--> 测试数据:[A1]if object_id('[A1]') is not null drop table [A1]create table [A1]([ids] varchar(10))insert [A1]select '2,21,23,27' union allselect '1,7,11,12' union allselect '5' union allselect '6,8'create table #tt(ids varchar(2))declare @str varchar(100)set @str='1,9,11'select @str='insert #tt select '+REPLACE(@str,',',' union all select ')exec(@str)select * from #tt awhere exists(select 1 from [A1] b where CHARINDEX(','+a.ids+',',','+b.ids+',')>0)/*ids111*/
------解决方案--------------------
建议不要用一个字段存放多个数据的方法,这种会导致查询的时候效率特别低下,往往查询的时间通常在100毫秒以上,甚至达到秒级的查询速度。
如果改成单个表来描述数据关系,查询时间通常在10毫秒以内。