SQL 服务器:字符串到带分隔符的行?
SQL Server : string to rows with delimiter?
在 SQL Server 2016 中有一个名为 STRING_SPLIT
(Transact-SQL) 的函数。
我的问题的答案适用于此功能。
很遗憾,我们只有 SQL Server 2012。
SELECT
email,
[Special ftg],
[Special OrgCode],
[Special SalaryCode]
FROM
Employee
我怎样才能得到这个?
email Special ftg Special OrgCode Special SalaryCode
-----------------------------------------------------------------------------------------
test@gmail.com 4;200;210;220;250;275;1100;1101;1102 14000000000 1
进入这个:
分隔符是分号,所有列都应该是分号。
您可以将 [Special ftg]
转换为 XML 然后使用 OUTER APPLY:
;WITH cte AS (
SELECT email,
CAST('<p>'+REPLACE([Special ftg],';','</p><p>')+'</p>'as xml) as [Special ftg],
[Special OrgCode],
[Special SalaryCode]
FROM Employee
)
SELECT c.email,
t.c.value('.','int') [Special ftg],
NULL [Special OrgCode],
NULL [Special SalaryCode]
FROM cte c
OUTER APPLY [Special ftg].nodes('/p') as t(c)
UNION ALL
SELECT c.email,
NULL,
c.[Special OrgCode],
NULL
FROM cte c
UNION ALL
SELECT c.email,
NULL,
NULL,
c.[Special SalaryCode]
FROM cte c
ORDER BY email,[Special SalaryCode],[Special OrgCode],[Special ftg]
输出:
email Special ftg Special OrgCode Special SalaryCode
test@gmail.com 4 NULL NULL
test@gmail.com 200 NULL NULL
test@gmail.com 210 NULL NULL
test@gmail.com 220 NULL NULL
test@gmail.com 250 NULL NULL
test@gmail.com 275 NULL NULL
test@gmail.com 1100 NULL NULL
test@gmail.com 1101 NULL NULL
test@gmail.com 1102 NULL NULL
test@gmail.com NULL 14000000000 NULL
test@gmail.com NULL NULL 1
在 SQL Server 2016 中有一个名为 STRING_SPLIT
(Transact-SQL) 的函数。
我的问题的答案适用于此功能。
很遗憾,我们只有 SQL Server 2012。
SELECT
email,
[Special ftg],
[Special OrgCode],
[Special SalaryCode]
FROM
Employee
我怎样才能得到这个?
email Special ftg Special OrgCode Special SalaryCode
-----------------------------------------------------------------------------------------
test@gmail.com 4;200;210;220;250;275;1100;1101;1102 14000000000 1
进入这个:
分隔符是分号,所有列都应该是分号。
您可以将 [Special ftg]
转换为 XML 然后使用 OUTER APPLY:
;WITH cte AS (
SELECT email,
CAST('<p>'+REPLACE([Special ftg],';','</p><p>')+'</p>'as xml) as [Special ftg],
[Special OrgCode],
[Special SalaryCode]
FROM Employee
)
SELECT c.email,
t.c.value('.','int') [Special ftg],
NULL [Special OrgCode],
NULL [Special SalaryCode]
FROM cte c
OUTER APPLY [Special ftg].nodes('/p') as t(c)
UNION ALL
SELECT c.email,
NULL,
c.[Special OrgCode],
NULL
FROM cte c
UNION ALL
SELECT c.email,
NULL,
NULL,
c.[Special SalaryCode]
FROM cte c
ORDER BY email,[Special SalaryCode],[Special OrgCode],[Special ftg]
输出:
email Special ftg Special OrgCode Special SalaryCode
test@gmail.com 4 NULL NULL
test@gmail.com 200 NULL NULL
test@gmail.com 210 NULL NULL
test@gmail.com 220 NULL NULL
test@gmail.com 250 NULL NULL
test@gmail.com 275 NULL NULL
test@gmail.com 1100 NULL NULL
test@gmail.com 1101 NULL NULL
test@gmail.com 1102 NULL NULL
test@gmail.com NULL 14000000000 NULL
test@gmail.com NULL NULL 1