2013-03-08 3 views
0

내가 "항목"라는 테이블이 같은 기록이 분할합니다.내부 루프와 루프 및

표 : 태그

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를 삽입하십시오.

잘 모르겠습니다.

답변

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

+0

XML 부분이 무엇을하는지 알지 못합니다 ... – PositiveGuy

+0

@CoffeeAddict, 항목 값을 행으로 나눠서'select * from entryxml'을 시도하고 결과를 봅니다 –

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