SQL循环列和将结果插入临时表

时间:2016-06-15 06:13:50

标签: sql sql-server

我在temp #CarIDs

中有一个Car ID列表
CREATE TABLE #CarIDs(
[CARID] [nvarchar] (60) NULL,
[Type] [nvarchar] (20) NULL,
[Flag] [nvarchar] (30) NULL) GO

INSERT INTO #CarIDs (CARID, Type, Flag) VALUES ('1111','',''), ('2222','',''), ('3333','',''), ('4444','',''), ('5555','',''), ('6666','','')

这给了我SELECT * FROM #CarIDs

+-------+-------+--------+
| CARID | Type  |  Flag  |
+-------+-------+--------+
|  1111 |       |        |
|  2222 |       |        |      
|  3333 |       |        |
|  4444 |       |        |
|  5555 |       |        |
|  6666 |       |        |
+-------+-------+--------+

如何遍历下表(CarHierarchy)以找出每个CARID的模型类型然后插入临时表?

+-------+-------+-------+
| Jeep  |Holden | Ford  |
+-------+-------+-------+
| 1111  |2222   | 3333  | 
| 4444  |6666   | 5555  |        
+-------+-------+-------+

我希望结果是#CarIDs:

+-------+-------+
| CARID | Type  | 
+-------+-------+
|  1111 |Jeep   |  
|  2222 |Holden |    
|  3333 |Ford   |     
|  4444 |Jeep   |    
|  5555 |Ford   |    
|  6666 |Holden |     
+------+--------+

1 个答案:

答案 0 :(得分:3)

您需要UNPIVOT首先#CarHierarchy表,然后在JOIN表上执行#CarIDs以获得正确的类型:

-- Unpivot the #CarHierarchy table using CROSS APPLY
WITH CteCarHierarchy AS(
    SELECT *
    FROM #CarHierarchy
    CROSS APPLY( VALUES
        (Jeep, 'Jeep'),
        (Holden, 'Holden'),
        (Ford, 'Ford')
    )t (CARID, Type)
)
SELECT
    ci.CARID,
    Type = cch.Type,
    ci.Flag
FROM #CarIDs ci
INNER JOIN CteCarHierarchy cch
    ON cch.CARID = ci.CARID

UPDATE声明:

ONLINE DEMO

WITH CteCarHierarchy AS(
    SELECT *
    FROM #CarHierarchy
    CROSS APPLY( VALUES
        (Jeep, 'Jeep'),
        (Holden, 'Holden'),
        (Ford, 'Ford')
    )t (CARID, Type)
)
UPDATE ci
    SET ci.Type = cch.Type
FROM #CarIDs ci
INNER JOIN CteCarHierarchy cch
    ON cch.CARID = ci.CARID

参考: