一个表a,里面的记录
id nameid
1 4
2 4/5/6
3 14
4 104
其中nameid的内容是表b的id的组合,现在我想找nameid包含4的记录找出来,也就是要将 4 和 4/5/6 这两条记录找出来,怎么组织sql语句
id nameid
1 4
2 4/5/6
3 14
4 104
其中nameid的内容是表b的id的组合,现在我想找nameid包含4的记录找出来,也就是要将 4 和 4/5/6 这两条记录找出来,怎么组织sql语句
select * from A
where charindex('4', nameid)>0
from A
where charindex('/4/',"/" + nameid +"/")>0
select *
from A
where charindex('/4/',"/" + nameid +"/")>0
insert A select 1, '4'
union all select 2, '4/5/6'
union all select 3, '14'
union all select 4, '104'
declare @nameid varchar(20)
set @nameid='4'
select * from A
where charindex('/'+@nameid+'/', '/'+nameid+'/')>0--result
id nameid
----------- --------------------
1 4
2 4/5/6(2 row(s) affected)
Insert A Select 1, '4'
Union All Select 2, '4/5/6'
Union All Select 3, '14'
Union All Select 4, '104'
GO
--方法一:
Select * From A
Where CharIndex('/4/', '/' + nameid + '/') > 0
--方法二:
Select * From A
Where '/' + nameid + '/' Like '%/4/%'
Go
Drop Table A
--Result
/*
ID nameid
1 4
2 4/5/6
*/
Insert A Select 1, '4'
Union All Select 2, '4/5/6'
Union All Select 3, '14'
Union All Select 4, '104'
GO
Declare @nameid Int
Select @nameid = 4
--方法一:
Select * From A
Where CharIndex('/' + Rtrim(@nameid) + '/', '/' + nameid + '/') > 0
--方法二:
Select * From A
Where '/' + nameid + '/' Like '%/' + Rtrim(@nameid) + '/%'
Go
Drop Table A
--Result
/*
ID nameid
1 4
2 4/5/6
*/
建議樓主用子表(即明細表)存儲b表的id,其查詢效率會高很多
where charindex('/A/', '/'+nameid+'/')>0--or:select * from A
where '/'+nameid+'/' like '%/4/%'