我正在尝试创建一个插入选择语句,该语句将数据从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
是一个Primairy键,应该是唯一的(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列插入只有两个列的目标表中。话虽这么说,我只会将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个字符,您的新表结构承担着丢弃大量信息的风险。目前尚不清楚您是否关心这个,但值得指出。
这是指您的SELECT
(类型,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
您的选择中有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