一个表a,里面的记录
id    nameid
1      4
2      4/5/6
3      14
4      104
其中nameid的内容是表b的id的组合,现在我想找nameid包含4的记录找出来,也就是要将  4  和 4/5/6  这两条记录找出来,怎么组织sql语句

解决方案 »

  1.   


    select * from A
    where charindex('4', nameid)>0
      

  2.   

    select * 
    from A
    where charindex('/4/',"/" + nameid +"/")>0
      

  3.   

    --nameId两边都加/,搜索 /4/
    select * 
    from A
    where charindex('/4/',"/" + nameid +"/")>0
      

  4.   

    create table A(id int, nameid varchar(20))
    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)
      

  5.   

    Create Table A(ID Int, nameid Varchar(20))
    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
    */
      

  6.   

    --如果輸入的參數來查詢Create Table A(ID Int, nameid Varchar(20))
    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
    */
      

  7.   

    來晚一步
    建議樓主用子表(即明細表)存儲b表的id,其查詢效率會高很多
      

  8.   

    select * from A
    where charindex('/A/', '/'+nameid+'/')>0--or:select * from A
    where '/'+nameid+'/' like '%/4/%'
      

  9.   

    select * from a where '/'+nameid+'/' like '%/4/%'