给定一个包含行和数据的Promotion
表,如:
PromotionId Codes
1 a,b
2 c
3 d,e,f
我怎么能写一个查询来返回它:
PromotionId Codes
1 a
1 b
2 c
3 d
3 e
3 f
基本上我想将代码字符串拆分成多行。
答案 0 :(得分:9)
您可以使用Split
表值函数,例如:
CREATE FUNCTION [dbo].[Split]
(
@ItemList NVARCHAR(MAX),
@delimiter CHAR(1)
)
RETURNS @IDTable TABLE (Item VARCHAR(50))
AS
BEGIN
DECLARE @tempItemList NVARCHAR(MAX)
SET @tempItemList = @ItemList
DECLARE @i INT
DECLARE @Item NVARCHAR(4000)
SET @tempItemList = REPLACE (@tempItemList, ' ', '')
SET @i = CHARINDEX(@delimiter, @tempItemList)
WHILE (LEN(@tempItemList) > 0)
BEGIN
IF @i = 0
SET @Item = @tempItemList
ELSE
SET @Item = LEFT(@tempItemList, @i - 1)
INSERT INTO @IDTable(Item) VALUES(@Item)
IF @i = 0
SET @tempItemList = ''
ELSE
SET @tempItemList = RIGHT(@tempItemList, LEN(@tempItemList) - @i)
SET @i = CHARINDEX(@delimiter, @tempItemList)
END
RETURN
END
然后您可以使用CROSS APPLY
加入它:
SELECT PromotionId, CodeList.Item AS Codes
FROM Promotion p
CROSS APPLY dbo.Split(Codes, ',') CodeList
修改:这是您数据的小提琴:http://sqlfiddle.com/#!3/85f8b/1/0
结果:
PROMOTIONID CODES
1 a
1 b
2 c
3 d
3 e
3 f
答案 1 :(得分:2)
如何将SQL与XML一起使用如下:
declare @X xml
SET @X= (SELECT CONVERT(xml,'<s id="'+cast(PromotionId as varchar)+'">' + REPLACE(Codes,',','</s><s id="'+cast(PromotionId as varchar)+'">') + '</s>') FROM t1
FOR XML RAW)
SELECT c.value('(@id)[1]','int') as PromotionId, c.value('.','varchar(50)') as Code
FROM @X.nodes('/row/s') T(c)
它会更高效,更快
答案 2 :(得分:1)
我认为在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