2013-03-08 50 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