我相信在 T-SQL 中拆分/联系事物的最快方法是使用 XML。这是我使用的解决方案:
;WITH CTE(PromotionID,Codes)
AS
(
SELECT PromotionID
,CAST(N'<r><![CDATA[' + REPLACE(Codes, ',', ']]></r><r><![CDATA[') + ']]></r>' AS XML) AS Codes
FROM @SourceTable
)
SELECT PromotionID
,Code
FROM CTE
CROSS APPLY (SELECT DISTINCT RTRIM(LTRIM(Tbl.Col.value('.', 'nvarchar(250)'))) AS Code FROM Codes.nodes('//r') Tbl(Col)) AS List
我已使用公用表表达式将代码转换为 XML。然后我只使用一种常用方法将 XML 拆分为单个元素。这是完整的工作示例:
SET NOCOUNT ON
GO
DECLARE @SourceTable TABLE
(
PromotionID INT,
Codes NVARCHAR(20)
)
INSERT INTO @SourceTable (PromotionID,Codes)
VALUES (1,'a,b')
,(2,'c')
,(3,'d,e,f')
;WITH CTE(PromotionID,Codes)
AS
(
SELECT PromotionID
,CAST(N'<r><![CDATA[' + REPLACE(Codes, ',', ']]></r><r><![CDATA[') + ']]></r>' AS XML) AS Codes
FROM @SourceTable
)
SELECT PromotionID
,Code
FROM CTE
CROSS APPLY (SELECT DISTINCT RTRIM(LTRIM(Tbl.Col.value('.', 'nvarchar(250)'))) AS Code FROM Codes.nodes('//r') Tbl(Col)) AS List
SET NOCOUNT OFF
GO