使用内部联接的分隔值拆分列

时间:2014-11-10 11:17:18

标签: sql-server sql-server-2008 tsql

我需要对包含分隔值的列执行内部联接,例如:

123;124;125;12;3433;35343;

现在我正在做的是:

ALTER procedure [dbo].[GetFruitDetails]
(
    @CrateID int
)
AS

SELECT Fruits.*, Fruits_Crates.CrateID 
    FROM Fruits_Crates INNER JOIN Fruits 
    ON Fruits_Crates.FruitID = Fruits.ID
    WHERE Fruits_Crates.CrateID = @CrateID

现在问题是我以这种方式保存数据:

FruitCrateID  FruitID 
1             1;
2             1;2;3;4
3             3;

我如何将FruitsIDs内部加入水果表以获取水果详情?

1 个答案:

答案 0 :(得分:1)

使用 this answer 中发布的方法,您可以将分隔的字符串转换为临时表的行,然后加入到:

SQL Fiddle

架构设置

CREATE TABLE Fruits_Crates
    ([FruitCrateID] int, [FruitID] varchar(10))
;

INSERT INTO Fruits_Crates
    ([FruitCrateID], [FruitID])
VALUES
    (1, '1;'),
    (2, '1;2;3;4;'),
    (3, '3;')
;

CREATE TABLE Fruits
    ([FruitID] int, [FruitName] varchar(10))
;

INSERT INTO Fruits
    ([FruitID], [FruitName])
VALUES
    (1, 'Apple'),
    (2, 'Banana'),
    (3, 'Orange'),
    (4, 'Pear')
;

插入临时表

 SELECT A.[FruitCrateID],  
     Split.a.value('.', 'VARCHAR(100)') AS FruitId  
 INTO #fruits
 FROM  (SELECT [FruitCrateID],  
         CAST ('<M>' + REPLACE([FruitID], ';', '</M><M>') + '</M>' AS XML) AS String  
     FROM  Fruits_Crates) AS A CROSS APPLY String.nodes ('/M') AS Split(a)

将临时表加入查找

SELECT t1.*, t2.FruitName
FROM #Fruits t1
INNER JOIN Fruits t2 on t1.FruitId = t2.FruitId

<强> Results

| FRUITCRATEID | FRUITID | FRUITNAME |
|--------------|---------|-----------|
|            1 |       1 |     Apple |
|            2 |       1 |     Apple |
|            2 |       2 |    Banana |
|            2 |       3 |    Orange |
|            2 |       4 |      Pear |
|            3 |       3 |    Orange |