[英]SQL Loop Through Columns and Insert Results into Temp Table
I have a list of Car IDs in a temp #CarIDs 我有一个临时#CarIDs的汽车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','','')
Which gives me SELECT * FROM #CarIDs
这给了我SELECT * FROM #CarIDs
+-------+-------+--------+
| CARID | Type | Flag |
+-------+-------+--------+
| 1111 | | |
| 2222 | | |
| 3333 | | |
| 4444 | | |
| 5555 | | |
| 6666 | | |
+-------+-------+--------+
How do I loop through the below table (CarHierarchy) to find out what model type is each CARID then insert into the temp table? 如何遍历下表(CarHierarchy)以找出每个CARID属于哪种模型类型,然后插入到临时表中?
+-------+-------+-------+
| Jeep |Holden | Ford |
+-------+-------+-------+
| 1111 |2222 | 3333 |
| 4444 |6666 | 5555 |
+-------+-------+-------+
I expect the results to be #CarIDs: 我希望结果是#CarIDs:
+-------+-------+
| CARID | Type |
+-------+-------+
| 1111 |Jeep |
| 2222 |Holden |
| 3333 |Ford |
| 4444 |Jeep |
| 5555 |Ford |
| 6666 |Holden |
+------+--------+
You need to UNPIVOT
first the #CarHierarchy
table and then do a JOIN
on the #CarIDs
table to get the correct type: 您需要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
The UPDATE
statement: 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
Reference: 参考:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.