我在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 |
+------+--------+
答案 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
声明:
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
参考: