SQL循環遍歷列並將結果插入臨時表

[英]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

從# carid中選擇*

+-------+-------+--------+
| 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:

我希望結果是# carid:

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

1 个解决方案

#1


3  

You need to UNPIVOT first the #CarHierarchy table and then do a JOIN on the #CarIDs table to get the correct type:

您需要先將#CarHierarchy表去掉軸,然后在#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語句:

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

Reference:

參考:


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/06/15/729d813ce705365b619a262df234be1b.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com