xml 一行变多行
-- create table
DECLARE @companies Table(
CompanyID INT,
CompanyCodes VARCHAR(100)
)
-- insert data
insert into @companies(CompanyID, CompanyCodes) values(1,'1|2')
insert into @companies(CompanyID, CompanyCodes) values(2,'1|2|3|4')
insert into @companies(CompanyID, CompanyCodes) values(3,'1|2')
--SELECT * FROM @companies
/*
CompanyID CompanyCodes
1 1|2
2 1|2|3|4
3 1|2
*/
/*
SELECT CompanyID,CAST('<i>' + REPLACE(CompanyCodes, '|', '</i><i>') + '</i>' AS XML) AS CompanyCodes
FROM @Companies
*/
/*
CompanyID CompanyCodes
1 <i>1</i><i>2</i>
2 <i>1</i><i>2</i><i>3</i><i>4</i>
3 <i>1</i><i>2</i>
*/
-- Query
;WITH cte AS (
SELECT
CompanyID,
CAST('<i>' + REPLACE(CompanyCodes, '|', '</i><i>') + '</i>' AS XML) AS CompanyCodes
FROM @Companies
)
SELECT
CompanyID,
x.i.value('.', 'VARCHAR(10)') AS CompanyCode
FROM cte
CROSS APPLY CompanyCodes.nodes('i') x(i)
/*
CompanyID CompanyCode
----------- -----------
1 1
1 2
2 1
2 2
2 3
2 4
3 1
3 2
*/
DECLARE @companies Table(
CompanyID INT,
CompanyCodes VARCHAR(100)
)
-- insert data
insert into @companies(CompanyID, CompanyCodes) values(1,'1|2')
insert into @companies(CompanyID, CompanyCodes) values(2,'1|2|3|4')
insert into @companies(CompanyID, CompanyCodes) values(3,'1|2')
--SELECT * FROM @companies
/*
CompanyID CompanyCodes
1 1|2
2 1|2|3|4
3 1|2
*/
/*
SELECT CompanyID,CAST('<i>' + REPLACE(CompanyCodes, '|', '</i><i>') + '</i>' AS XML) AS CompanyCodes
FROM @Companies
*/
/*
CompanyID CompanyCodes
1 <i>1</i><i>2</i>
2 <i>1</i><i>2</i><i>3</i><i>4</i>
3 <i>1</i><i>2</i>
*/
-- Query
;WITH cte AS (
SELECT
CompanyID,
CAST('<i>' + REPLACE(CompanyCodes, '|', '</i><i>') + '</i>' AS XML) AS CompanyCodes
FROM @Companies
)
SELECT
CompanyID,
x.i.value('.', 'VARCHAR(10)') AS CompanyCode
FROM cte
CROSS APPLY CompanyCodes.nodes('i') x(i)
/*
CompanyID CompanyCode
----------- -----------
1 1
1 2
2 1
2 2
2 3
2 4
3 1
3 2
*/