将记录从一个表复制到另一个表时更改值

时间:2018-02-23 12:06:19

标签: sql sql-server tsql

我有以下代码将数据从一个表复制到另一个表:

INSERT INTO MyDb.Books (CategoryId, Author, Title)
SELECT 
  CategoryId, Author, Title
FROM MyDbBackup.Books

复制CategoryId值时,我需要应用以下转换:

+---------------------+-----------------+
|     Old CategoryId  |  New CategoryId |
+---------------------+-----------------+
|                  1  |               2 |
|                  2  |               1 |
|                  3  |               3 |
|                  4  |               4 |
|                  5  |               8 |
|                 14  |               6 |
|                 15  |               7 |
|                 18  |               5 |
|                 22  |               9 |
+---------------------+-----------------+

我该怎么做?

4 个答案:

答案 0 :(得分:1)

你可以在

时使用案例
INSERT INTO MyDb.Books (CategoryId, Author, Title)
SELECT 
  case when CategoryId = 1 then 2
       when CategoryId = 2 then 1
       when CategoryId = 5 then 8
       when CategoryId = 14  then 6
       when CategoryId = 15  then 7
       when CategoryId = 18  then 5
       when CategoryId = 22  then 9
       else cateogoryId end, Author, Title
FROM MyDbBackup.Books

或不那么冗长的方式

INSERT INTO MyDb.Books (CategoryId, Author, Title)
SELECT 
  case CategoryId 
       when  1 then 2
       when 2 then 1
       when 5 then 8
       when 14  then 6
       when 15  then 7
       when 18  then 5
       when 22  then 9
       else cateogoryId end, Author, Title
FROM MyDbBackup.Books

答案 1 :(得分:1)

正如Panagiotis Kanavos的评论所说,你需要使用CASE表达式:

CASE CategoryID WHEN 1 THEN 2
                WHEN 2 THEN 1
                WHEN 5 THEN 8
                WHEN 14 THEN 6
                WHEN 15 THEN 7
                WHEN 18 THEN 5
                WHEN 22 THEN 9
                ELSE CategoryID END

答案 2 :(得分:1)

一种方法是使用查找表join

select v.newid, b.author, b.title
from MyDbBackup.Books b join
     (values (1, 2), (2, 1), (3, 3), (4, 4), (5, 8), (14, 6), (15, 7), (18, 5), (22, 9)
     ) v(oldid, newid)
     on b.CategoryId = v.oldid;

另一种方法是使用case表达式。但是,使用join可确保只有具有旧ID的书籍集在结果集中。因此,它同时进行查找和过滤。

如果您不想进行过滤,可以使用left join代替内部联接。

答案 3 :(得分:1)

由于没有公式,因此必须逐个进行转换:

INSERT INTO MyDb.Books (CategoryId, Author, Title)
SELECT CASE CategoryID WHEN 1 THEN 2
                       WHEN 2 THEN 1
                       WHEN 5 THEN 8
                       WHEN 14 THEN 6
                       WHEN 15 THEN 7
                       WHEN 18 THEN 5
                       WHEN 22 THEN 9
                      ELSE CategoryId ID END AS CategoryId
       , Author, Title
FROM MyDbBackup.Books