給個類似的例子給你參考
create table ta (id int, value varchar(20))
Insert into ta
select '1','aaa'
union all select '2','bbb'
union all select '3','ccc'create table tb (id int, value varchar(20))
Insert into tb 
select '1','aaa,bbb,'
union all select '2','bbb,ccc,'
union all select '3','aaa,bbb,ccc,'select * from ta
select * from tb--函數
create function dbo.fn_m(@vchstring varchar(1000))
returns varchar(1000)
as
begin
declare @intstart int,@intlocation int 
declare @s varchar(1000),@vchsubstring varchar(100)

select @intstart =1,@s='' 
select @intlocation = charindex(',',@vchstring,@intstart) 
while (@intlocation <>0 ) 
begin 
select @vchsubstring=substring(@vchstring,@intstart,@intlocation-@intstart)
select @s=@s+cast([id] as varchar)+',' from ta where value=@vchsubstring
select @intstart = @intlocation +1 
select @intlocation = charindex(',',@vchstring,@intstart) 
end 
return(@s)
end--刪除
drop table ta
drop table tb
drop function dbo.fn_mselect id, value=dbo.fn_m(value) from tb
--結果
id   value
------------------
1 1,2,
2 2,3,
3 1,2,3,

解决方案 »

  1.   

    select * from table_1 a
    where exists( select * from table_2 where charindex(';'+cast(a.id as varchar)+';',';'+ids+';')>0)
      

  2.   

    --或者:
    select distinct a.* 
    from table_1 a,table_2 b
    where charindex(';'+cast(a.id as varchar)+';',';'+b.ids+';')>0
      

  3.   

    --测试--测试数据
    create table table_1(id int)
    insert table_1 select 1
    union  all     select 2
    union  all     select 3create table table_2(ids varchar(8000))
    insert table_2 select '12;45;2;23;'
    union  all     select '11;8;7;5;'
    union  all     select '3;4;10;19;'
    go--查询方法1
    select * from table_1 a
    where exists( select * from table_2 where charindex(';'+cast(a.id as varchar)+';',';'+ids+';')>0)--查询方法2
    select distinct a.* 
    from table_1 a,table_2 b
    where charindex(';'+cast(a.id as varchar)+';',';'+b.ids+';')>0
    go--删除测试
    drop table table_1,table_2/*--测试结果id          
    ----------- 
    2
    3(所影响的行数为 2 行)id          
    ----------- 
    2
    3(所影响的行数为 2 行)
    --*/