循环与内循环和分裂

时间:2013-03-08 23:06:19

标签: tsql

我在名为“Entry”的表格中有这样的记录:

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
....

我需要循环遍历整个表中的每个记录以进行Entry,然后为每个行循环使用逗号分隔的标记,因为我需要拆分每个标记然后根据标记名称执行标记查找以获取TagID,然后最终在每个逗号分隔标记

的名为TagEntry的桥接表中插入TagID,EntryID

不知道该怎么做。

2 个答案:

答案 0 :(得分: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 

答案 1 :(得分:0)

此SQL将拆分您的Entry表,以便加入其他表:

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