SQL替換欄位字串

來源:互聯網
上載者:User
  1. ----------------------------
  2. --Author:旋風
  3. --Date:2008-10-23 15:19:49
  4. --Version:V1.0
  5. --Memo:SQL替換欄位字串
  6. ----------------------------
  7. --> Test Data: [A]
  8. if object_id('[A]') is not null drop table [A]
  9. create table [A] ([AutoID] int,[IDStr] varchar(50))
  10. insert into [A]
  11. select 1,'1,2,3,4' union all
  12. select 2,'1,2'
  13. --> Test Data: [B]
  14. if object_id('[B]') is not null drop table [B]
  15. create table [B] ([AutoID] int,[Value] varchar(3))
  16. insert into [B]
  17. select 1,'AAA' union all
  18. select 2,'BBB' union all
  19. select 3,'CCC' union all
  20. select 4,'DDD'
  21. Go
  22. if object_id('S_str') is not null
  23.     drop function S_str
  24. go
  25. create function S_str(@str nvarchar(100))
    returns nvarchar(100)
    as
    begin
        set @str=','+@str+','--加上兩邊逗號
        select @str=replace(@str,','+rtrim([AutoID])+',',','+[Value]+',') from B
        --where  @str like '%,'+rtrim([AutoID])+',%'
        WHERE CHARINDEX(','+RTRIM([AutoID])+',',@str)>0
        return substring(@str,2,len(@str)-2)--去掉兩邊逗號
    end
    go
    --Code
    --SQL2000用函數
    select [AutoID],[Value]=dbo.S_str([IDStr]) from A
  26. --SQL2005用XML
  27. SELECT [AutoID],
  28.        [Value]=CAST(STUFF((
  29.               SELECT ','+[Value]
  30.               FROM B 
  31.               WHERE CHARINDEX(','+RTRIM([AutoID])+',',','+a.[IDStr]+',')>0
  32.               FOR XML PATH(''))
  33.               ,1,1,'') AS VARCHAR(20)) 
  34. FROM A AS a
  35. --Drop
  36. drop table [A]
  37. drop function S_str
  38. --Result
  39. /*
  40. AutoID      Value
  41. ----------- ----------------------------------------------------------------------------------------------------
  42. 1           AAA,BBB,CCC,DDD
  43. 2           AAA,BBB
  44. */

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.