数据表结构:
id name classid
1 三星 3,5,7
2 联想 1,7
3 索尼 43,3
4 漫步者 35
5 日立 5,7查询结果要求:
如:我要查询用逗号分隔的classid,给个条件classid中如果有3的要查询结果为
结果1为:
id name classid
1 三星 3,5,7
3 索尼 43,3
注:第4条语句不能查出来
给个条件classid中如果有5的要查询结果为
id name classid
1 三星 3,5,7
5 日立 5,7
id name classid
1 三星 3,5,7
2 联想 1,7
3 索尼 43,3
4 漫步者 35
5 日立 5,7查询结果要求:
如:我要查询用逗号分隔的classid,给个条件classid中如果有3的要查询结果为
结果1为:
id name classid
1 三星 3,5,7
3 索尼 43,3
注:第4条语句不能查出来
给个条件classid中如果有5的要查询结果为
id name classid
1 三星 3,5,7
5 日立 5,7
where charindex(',3,',','+classid+',')>0
set @id='3'select * from T
where charindex(','+@id+',',','+classid+',')>0
where ','+classid+',' like '%,5,%'
(
[id] int null,
[name] varchar(50),
[classid] varchar(50)
)
DECLARE @i int
INSERT INTO table1
SELECT 1,'三星','3,5,7' UNION ALL
SELECT 2,'联想','1,7' UNION ALL
SELECT 3,'索尼','43,3'UNION ALL
SELECT 4,'漫步者','35' UNION ALL
SELECT 5,'日立','5,7'SET @i=3
SELECT * FROM table1 WHERE CHARINDEX(','+CAST(@i AS VARCHAR)+',',','+[classid]+',')>0
DROP TABLE table1
--@i=3结果
id name classid
----------- -------------------------------------------------- --------------------------------------------------
1 三星 3,5,7
3 索尼 43,3
INSERT INTO @T
SELECT 1 , '三星', '3,5,7' UNION
SELECT 2 , '联想' , '1,7' UNION
SELECT 3 , '索尼', '43,3' UNION
SELECT 4 , '漫步者', '35' UNION
SELECT 5 , '日立' , '5, 7'SELECT * FROM @T A WHERE CHARINDEX('3',CLASSID)>0 AND SUBSTRING(CLASSID,CHARINDEX('3',CLASSID)+1,1)=','
对于如下表:table5
col1
a
a
b
b
b
c
c
我要得到
no col1
1 a
2 a
1 b
2 b
3 b
1 c
2 c
在下也有一个苯的方法
declare @i int
declare @s varchar(50)
declare @s1 varchar(50)
declare @table table (no int,col1 varchar(50))
set @i=1declare tempcursor cursor local for select * from table5 order by col1open tempcursorfetch next from tempcursor
into @s
insert into @table
values(@i,@s)
while @@fetch_status = 0
begin
fetch next from tempcursor
into @s1
if @s1=@s
begin
set @i=@i+1
set @s=@s1
end
else
begin
set @i=1
set @s=@s1
end
insert into @table
values(@i,@s)
endclose tempcursor
deallocate tempcursorselect * from @table
但是感觉很不爽,各位大侠可以指定好的方法吗?
insert T select 1, '三星', '3,5,7'
union all select 2, '联想', '1,7'
union all select 3, '索尼', '43,3'
union all select 4, '漫步者', '35'
union all select 5, '日立', '5,7'select * from T
where charindex(',3,', ','+classid+',')>0
--result
id name classid
----------- ---------- ----------
1 三星 3,5,7
3 索尼 43,3(2 row(s) affected)
select * from T
where charindex(',5,', ','+classid+',')>0
--result
id name classid
----------- ---------- ----------
1 三星 3,5,7
5 日立 5,7(2 row(s) affected)