用一下UDF就比较简单, 可以吗?

解决方案 »

  1.   

    --测试数据
    create table ta(pkid int, name varchar(40))
    insert ta select 1, 'aa' 
    union all select 2, 'bb' 
    union all select 3, 'cc'
    create table tb(pkid int, name varchar(40), aid varchar(40))
    insert tb select 1, '河南', '1,2'
    union all select 2, '山东', '2,3'
    union all select 3, '广州', '1,2,3'
    go
    --定义一个UDF
    create function dbo.fun_tb(@taid int)
    returns varchar(100)
    as
    begin
    declare @str varchar(100)
    set @str=''
    select @str=@str+','+convert(varchar(20), pkid)
    from tb
    where charindex(','+convert(varchar(20), @taid)+','
    ,','+aid+',')<>0
    set @str=stuff(@str, 1, 1, '')
    return @str
    end
    go
    select *, bid=dbo.fun_tb(pkid)
    from ta
    where pkid=1
    --清除
    drop function dbo.fun_tb
    drop table ta
    drop table tb
      

  2.   

    /*注意表tb中的aid不能有多余的空格,否则结果可能出错。
    为了确保安全,你可以update一下tb表*/
    update tb
    set aid=replace(aid, ' ','')