0

我正在尝试创建一个 INSERT SELECT 语句,该语句将数据Imported_tableDestination_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.

提前致谢。

4

3 回答 3

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 
于 2018-02-22T14:04:26.150 回答
1

这意味着您的SELECT(genre,genre_name,description) 和INSERT(genre_name, description) 列表不匹配。您需要与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 
于 2018-02-22T14:04:17.183 回答
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 个字符宽,您的新表结构冒着丢弃大量信息的风险。目前尚不清楚您是否对此感到担忧,但值得指出。

于 2018-02-22T14:03:35.487 回答