2013-03-08 49 views
0

我有這樣的記錄在一個名爲「項」表:環與內環和分裂

TABLE: Entry 

ID  Tags 
---  ------------------------------------------------------ 
1  Coffee, Tea, Cake, BBQ 
2  Soda, Lemonade 

...等。

表:標籤

ID  TagName 
---- ----------- 
1  Coffee 
2  Tea 
3  Soda 
... 

TABLE: TagEntry 

ID TAGID ENTRYID 
--- ----- ------- 
1  1  1 
2  2  1 
3  3  2 
.... 

我需要遍歷每個記錄在進入整個表,然後爲每一行循環的逗號分隔標籤,因爲我需要拆分每個標籤然後以此爲基礎標籤查找在標籤名稱上抓取TagID,然後最終將TagID,EntryID插入到名爲TagEntry的橋接表中,用於每個逗號分隔標籤

不確定如何去解決這個問題。

回答

0

試試這個

;with entry as 
(
    select 1 id, 'Coffee, Tea, Cake, BBQ' tags 
    Union all 
    select 2, 'Soda, Lemonade' 
), tags as 
(
    select 1 id,'Coffee' TagName union all 
    select 2,'Tea' union all 
    select 3,'Soda' 
), entryxml as 
(
    SELECT id, ltrim(rtrim(r.value('.','VARCHAR(MAX)'))) as Item from (
    select id, CONVERT(XML, N'<root><r>' + REPLACE(tags,',','</r><r>') + '</r></root>') as XmlString 
    from entry) x 
    CROSS APPLY x.XmlString.nodes('//root/r') AS RECORDS(r) 
) 
select e.id EntryId, t.id TagId from entryxml e 
inner join tags t on e.Item = t.TagName 
+0

不錯,沒有想到使用CTE爲這件好東西。 – PositiveGuy 2013-03-09 01:38:47

+0

沒有得到你的XML部分正在做什麼... – PositiveGuy 2013-03-09 01:39:24

+0

@CoffeeAddict,它將你的入口值分割成行,嘗試從entryxml中選擇*並查看結果 – 2013-03-09 04:27:11

0

SQL語句將分割你的項目表中,以便連接到其他:

with raw as (
    select * from (values 
    (1, 'Coffee, Tea, Cake, BBQ'), 
    (2, 'Soda, Lemonade') 
) Entry(ID,Tags) 
) 
, data as (
    select ID, Tag = convert(varchar(255),' '), Tags, [Length] = len(Tags) from raw 
    union all 
    select 
     ID = ID, 
     Tag = case when charindex(',',Tags) = 0 then Tags else convert(varchar(255), substring(Tags, 1, charindex(',',Tags)-1)) end, 
     Tags = substring(Tags, charindex(',',Tags)+1, 255), 
     [Length] = [Length] - case when charindex(',',Tags) = 0 then len(Tags) else charindex(',',Tags) end 
    from data 
    where [Length] > 0 
) 
select ID, Tag = ltrim(Tag) 
from data 
where Tag <> '' 

,並返回該給定輸入:

ID   Tag 
----------- ------------ 
2   Soda 
2   Lemonade 
1   Coffee 
1   Tea 
1   Cake 
1   BBQ