SQL 查询字段某个字符是否存在解决方法即in(字符解决)

来源:互联网 发布:kafka java heap space 编辑:程序博客网 时间:2024/05/30 23:40
sql查询字段某个字符是否存在
我有一个表
a b
1 1,110,20,220,200
2 10,110,2,22
2 10,110,202,20

我要查询b字段有1的所有记录
得到的数据是1 1,110,20,220,200

要查询b字段有2的所有记录
得到的数据应该是2 10,110,2,22

要查询b字段有20的所有记录
得到的数据是
1 1,110,20,220,200
2 10,110,202,20

要查询b字段有0的所有记录
得到的数据无


这样的sql怎么写????????


------ 参考示例1 -----------------------

--在指定字符列中返回字符3所在始位置(没找到为0)

SELECT charindex(','+ltrim('3')+',',',1,13,4,2,3,54,23,')
结果
10

------ 参考示例2 -----------------------

SELECT * FROM sys_user WHERE [user_id] IN (23,13,4,2,3,54,1)SELECT * FROM sys_user WHERE charindex(','+ltrim([user_id])+',',',23,13,4,2,3,54,1,')>0  --字符串形式查询


------解决方案--------------------
SQL code
select *from tbwhere charindex(',1,',','+b+',')>0 --有1的记录select *from tbwhere charindex(',2,',','+b+',')>0 --有2的记录select *from tbwhere charindex(',20,',','+b+',')>0 --有20的记录


------解决方案--------------------
SQL code
declare @t table (a int,b varchar(20))insert into @tselect 1,'1,110,20,220,200' union allselect 2,'10,110,2,22' union allselect 2,'10,110,202,20'declare @i int set @i=20 --这是参数select * from @t where charindex(','+ltrim(@i)+',',','+b+',')>0

/*
a              b
----------- --------------------
1              1,110,20,220,200
2              10,110,202,20
*/ 
0 0
原创粉丝点击