您的位置:首页 > 其它

逗号链接的字符串模糊查询怎样写?

2013-04-19 12:05 302 查看
表名 table1

字段

id uid

1 1,2

2 2,6,11

3 2

4 3,4

5 4,5,7

6 6,9

如id=2,查询得到

id uid

1 1,2

2 2,6,11

3 2

CHARINDEX(',',NAME)-1指定某字段中逗号开始的位置,-1是去除‘,’本身的位置


SQL code

create table table1 (id int, uid varchar(10))
insert into table1 values(1 ,   '1,2')
insert into table1 values(2 ,   '2,6,11')
insert into table1 values(3 ,   '2')
insert into table1 values(4 ,   '3,4')
insert into table1 values(5 ,   '4,5,7')
insert into table1 values(6 ,   '6,9')
go
declare @uid as int
set @uid = 2

select * from table1 where charindex(','+cast(@uid as varchar) + ',' , ','+ uid +',') > 0
/*
id          uid
----------- ----------
1           1,2
2           2,6,11
3           2

(所影响的行数为 3 行)
*/
select * from table1 where ','+ uid +',' like '%,'+cast(@uid as varchar) + ',%'
/*
id          uid
----------- ----------
1           1,2
2           2,6,11
3           2

(所影响的行数为 3 行)
*/

drop table table1


http://bbs.csdn.net/topics/300156383
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: