字串拆分,修改,再合併

2021-04-13 11:37:44 字數 1803 閱讀 4005

假設有2個表,需要組成乙個檢視,分別如下:

表1: [tags]

id      name

------------------------------

1        tag1

2        tag2

3        tag3

4        tag4

5        tag5

...

表2:[test]

id      title      tagid

------------------------------

1       標題1        1,4

2       標題2       1,3,4

3       標題3       2,5

4       標題4       3,4

5       標題5       2,3,4,5

...

如上例,如建立乙個檢視,並根據表[test]的[tagid]欄位的陣列,關聯表[tags]的[name]字段對應的行,得到如下檢視:

檢視1:[view_test]

id      title      tags

-----------------------------

1       標題1      tag1,tag4

2       標題2      tag1,tag3,tag4

3       標題3      tag2,tag5

4       標題4      tag3,tag4

5       標題5      tag2,tag3,tag4,tag5 

解決思路:是先把字串按逗號拆了,再根據tags表修改,最後再合併

if object_id('tempdb..#') is not null

drop table #

if object_id('tempdb..#t') is not null

drop table #t

if object_id('tempdb..#tb') is not null

drop table #tb

--按逗號分割

select top 2000 id=identity(int,1,1) into # from syscolumns a,syscolumns b

select a.id,a.title,tagid=substring(a.tagid,b.id,charindex(',',a.tagid+',',b.id)-b.id) into #t

from test a, # b

where substring(','+a.tagid,b.id,1)=',' order by a.id,b.id

--更新

update #t

set tagid=b.name

from #t a,tags b

where a.tagid=b.id

--合併

select *,cast(',' as varchar(8000)) as aa into #tb from #t order by id,tagid  

declare @id int,@name varchar(50)  

update #tb

set @name=case @id when id then @name+','+tagid else tagid end,aa=@name,@id=id 

select id,title,max(aa) as tagid from #tb group by id,title  

拆分字串

拆分乙個字串,獲取每一組的key與value。如字串 qq adf f qewr98 eer d9adf t ad34 f qewrqr u adf43 gggg 2344 按照物件導向理念來解決,建立乙個物件 這個是對物件物件,有key和value兩個特性。我們需要把拆分好的資料臨時儲存起來,現在...

拆分字串

本函式可以將 目標字串 以 指定字串 進行拆分,並通過表結構返回結果。如下 create or replace type str split is table of varchar2 4000 create or replace function splitstr p string in varch...

拆分字串

拆分乙個字串,獲取每一組的key與value。如字串 qq adf f qewr98 eer d9adf t ad34 f qewrqr u adf43 gggg 2344 按照物件導向理念來解決,建立乙個物件 這個是對物件物件,有key和value兩個特性。我們需要把拆分好的資料臨時儲存起來,現在...