有数据表T_table,其中有字段z1。z1存储由空格分隔的多个字符串,例如:
    记录号     z1
    1       ab1 df1 ft1
    2       df1 ab1 ft1
    3       df1 ft1 ab1
    4       ab df1 ft1
    5       df1 ab ft1
    6       df1 ft1 ab
    希望检索z1中包含“ab”但不包含“ab1”的记录(只包含后3条记录),SQL语句是什么?

解决方案 »

  1.   

    select * from T_table where charindex('ab',z1)>0 and charindex('ab1',z1)=0
      

  2.   

    select * from T_table where charindex(' ab ',' '+z1+' ')>0 and charindex('ab1',' '+z1+' ')=0
      

  3.   

    写错了,应该是
    select * from T_table where charindex(' ab ',' '+z1+' ')>0 and charindex(' ab1 ',' '+z1+' ')=0
      

  4.   

    if object_id('pubs..tb') is not null
       drop table tb
    gocreate table tb(记录号 int,z1 varchar(20))
    insert into tb(记录号,z1) values(1,       'ab1 df1 ft1')
    insert into tb(记录号,z1) values(2,       'df1 ab1 ft1')
    insert into tb(记录号,z1) values(3,       'df1 ft1 ab1')
    insert into tb(记录号,z1) values(4,       'ab df1 ft1')
    insert into tb(记录号,z1) values(5,       'df1 ab ft1')
    insert into tb(记录号,z1) values(6,       'df1 ft1 ab')select * from tb where charindex('ab' , z1) > 0 and charindex('ab1' , z1) = 0 drop table tb/*
    记录号         z1                   
    ----------- -------------------- 
    4           ab df1 ft1
    5           df1 ab ft1
    6           df1 ft1 ab(所影响的行数为 3 行)
    */
      

  5.   

    kadboy的方法很好, 在字段z1的两端加空格,再在“ab”的两端加空格,然后用charindex搜索.其实不需要跟 and charindex(' ab1 ',' '+z1+' ')=0.
        我是用:
    WHERE cast(' '+f5+' ' as char(54))
     like '% ab %'
    效果相同.