现在有两张表
表一如下:表二如下:如何查询表一中code列的字符串包含表二中code值的数据
即应查到id为1,2,5的数据目前知道用instr  但是具体的where条件应该怎么写?

解决方案 »

  1.   

    自顶rtrt
      

  2.   

    Select * from t1 where  exists(
        Select 1 from t2 where t1.code like '%,'+t2.code+',%'
    )
    手机打,先这样吧
      

  3.   

    --测试数据
    if not object_id(N'Tempdb..#T1') is null
    drop table #T1
    Go
    Create table #T1([ID] int,[code] nvarchar(32))
    Insert #T1
    select 1,N',001,002,004,' union all
    select 2,N',002,003,' union all
    select 3,N',003,005,' union all
    select 4,N',006,' union all
    select 5,N',004,'
    GO
    if not object_id(N'Tempdb..#T2') is null
    drop table #T2
    Go
    Create table #T2([ID] int,[code] nvarchar(23))
    Insert #T2
    select 1,N'001' union all
    select 2,N'002' union all
    select 3,N'004'
    Go
    --测试数据结束
    SELECT  *
    FROM    #T1
    WHERE   EXISTS ( SELECT *
                     FROM   #T2
                     WHERE  CHARINDEX(',' + #T2.code + ',', #T1.code) > 0 )
      

  4.   

    使用like 或者 Partindex函数
      

  5.   

    SELECT t1.*
    FROM table1 AS t1
         INNER JOIN table2 AS t2 ON t1.code LIKE '%,'+t2.code+',%';
      

  6.   

    使用like 或者 Partindex函数