有没有办法一条SQL返回数据
表A
ID  NAME
1 A
2 B
3 C
4 D字符串由NAME组成,根据字符串返回ID
字符串ABCD返回1234
字符串AB返回12
字符串BC返回23
字符串BCD返回234
字符串BAD返回214
…………
现在我的做法是循环一个一个取,有没有办法一条SQL搞定呢?字符串是变化的

解决方案 »

  1.   

    Name為固定字符長度可以如:固定1個字符declare @s nvarchar(1000)
    set @s=''
    select @s=@s+rtrim(ID) from tab where 'ABCD' like '%'+Name +'%'
      

  2.   

    看看这个有么有帮助
    http://blog.csdn.net/xys_777/archive/2010/06/30/5703874.aspx
      

  3.   

    说下我的相法。
    想了一阵,在sql的语句中没找到能多个字符一起替换的方法Method。所以觉得lz提到的要求肯定是不可实现的。
    不过可以做个替换的存储过程。动态的实现lz需要的功能。
    到时候就能一条sql写出来了。不过在逻辑处理上是相同的。都是一条条替换的。如例子是替换4回。
      

  4.   

    Create table test
    (
    id int,
    name varchar(10)
    )
    Go
    insert into test
    select 1,'A'
    union all
    select 2,'B'
    union all
    select 3,'C'
    union all
    select 4,'D'select distinct replace(STUFF((select ','+name from test where id like '[1234]%' for xml path('')),1,1,''),',','') as name
    from test
      

  5.   

    简单。见红字部分
    declare @a table(id char(1), name char(1));insert @a
    select '1','a' union 
    select '2','b' union
    select '3','c' union
    select '4','d'declare @string varchar(100)
    select @string = 'abcd'SELECT @string=REPLACE(@string,name,id) from @a
    select @string
      

  6.   


    declare @c varchar(10)='ABD';
    declare @t table(id int ,name char(1));
    insert into @t select 1,'A'
    union all select 2,'B' 
    union all select 3,'C'
    union all select 4,'D';
    --select * from @t;select cast((select ''+cast(id as varchar(10)) from @t where CHARINDEX(name,@c)>0 for xml path('')) as varchar(10))----------
    124