Tsql 带内循环和拆分的循环
我在一个名为Entry的表中有这样的记录:Tsql 带内循环和拆分的循环,tsql,Tsql,我在一个名为Entry的表中有这样的记录: TABLE: Entry ID Tags --- ------------------------------------------------------ 1 Coffee, Tea, Cake, BBQ 2 Soda, Lemonade ……等等 表:标签 ID TagName ---- ----------- 1 Coffee 2 Tea 3 S
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,然后最终在名为TagEntry的桥接表中为每个逗号分隔的标记插入TagID,EntryID
不知道该怎么做。试试这个
;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
此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 <> ''
@CoffeeAddict,它正在将您的输入值拆分为行,请尝试从entryxml中选择*并查看结果
ID Tag
----------- ------------
2 Soda
2 Lemonade
1 Coffee
1 Tea
1 Cake
1 BBQ