使用不同的表/ col结构INSERT SELECT

时间:2018-02-22 14:00:48

标签: sql sql-server insert-select

我正在尝试创建一个INSERT SELECT语句,用于插入数据并将数据从Imported_table转换为Destination_table

Imported_table

+------------------+-----------------------+
| Id (varchar(10)) | genre (varchar(4000)) |
+------------------+-----------------------+
| 6                | Comedy                |
+------------------+-----------------------+
| 5                | Comedy                |
+------------------+-----------------------+
| 1                | Action                |
+------------------+-----------------------+

Destination_table (应该如何看待)

+-----------------------------+----------------------------+
| genre_name (PK,varchar(50)) | description (varchar(255)) |
+-----------------------------+----------------------------+
| Comedy                      | Description of Comedy      |
+-----------------------------+----------------------------+
| Action                      | Description of Action      |
+-----------------------------+----------------------------+
  • Imported_table.Id根本没有使用,但仍在此(旧)表中
  • Destination_table.genre_name是一个主要关键字,应该是唯一的(distinct)
  • Destination_table.description使用CONCAT('Description of ',genre)
  • 进行编译

我最好的尝试

INSERT INTO testdb.dbo.Destination_table (genre_name, description)
SELECT DISTINCT Genre,
       LEFT(Genre,50) AS genre_name,
       CAST(CONCAT('Description of ',Genre) AS varchar(255)) AS description
FROM   MYIMDB.dbo.Imported_table 

给出错误:The select list for the INSERT statement contains more items than the insert list. The number of SELECT values must match the number of INSERT columns.

提前致谢。

3 个答案:

答案 0 :(得分:1)

您的查询中最大的错误是您尝试将3列插入到只有两列的目标表中。话虽这么说,我只会使用LEFT来插入两个值,并占用新表所能容纳的空间:

INSERT INTO testdb.dbo.Destination_table (genre_name, description)
SELECT DISTINCT
    LEFT(Genre, 50),
    'Description of ' + LEFT(Genre, 240)    -- 240 + 15 = 255
FROM MYIMDB.dbo.Imported_table;

作为旁注,原始的genre字段宽度为4000个字符,并且您的新表结构存在丢弃大量信息的风险。目前尚不清楚你是否对此表示担忧,但值得指出。

答案 1 :(得分:1)

这意味着您的SELECT(流派,genre_name,说明)和INSERT(genre_name,说明)列表不匹配。您需要SELECT INSERT中指定的相同数量的字段。

试试这个:

INSERT INTO testdb.dbo.Destination_table (genre_name, description)
SELECT DISTINCT Genre,
       CAST(CONCAT('Description of ',Genre) AS varchar(255)) AS description
FROM   MYIMDB.dbo.Imported_table 

答案 2 :(得分:1)

您的SELECT中有3列,请尝试:

INSERT INTO testdb.dbo.Destination_table (genre_name, description)
SELECT DISTINCT LEFT(Genre,50) AS genre_name,
       CAST(CONCAT('Description of ',Genre) AS varchar(255)) AS description
FROM   MYIMDB.dbo.Imported_table