0

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

TABLE: Entry

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

...ETC。

表:标签

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

不知道该怎么做。

4

2 回答 2

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 
于 2013-03-08T23:17:11.773 回答
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
于 2013-03-09T00:00:27.243 回答