5

给定一个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

基本上我想将代码拆分为多行。

4

3 回答 3

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
于 2012-10-18T12:15:20.447 回答
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)

它将更高效、更快

SQLFiddle 演示

于 2012-10-18T13:08:13.287 回答
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
于 2012-10-18T12:51:14.583 回答