简体   繁体   English

将特定列从一个表复制到另一个

[英]Copy specific columns from one table to another

I have two tables InventoryOriginal and InventoryBackup.我有两个表 InventoryOriginal 和 InventoryBackup。 Both had 20 columns, but now InventoryOriginal has changed and has only 12 columns which are common with InventoryBackup.两者都有 20 列,但现在 InventoryOriginal 已更改,只有 12 列与 InventoryBackup 通用。 And I need to copy each month's data from InventoryOriginal to InventoryBackup, but it will give me an error because the column number do not match.而且我需要将每个月的数据从 InventoryOriginal 复制到 InventoryBackup,但它会给我一个错误,因为列号不匹配。

I use the simple statement to copy the data which is我使用简单的语句来复制数据

INSERT INTO InventoryBackup
Select * from  InventoryOriginal where Period  = '2020-01-01'

but now the number of columns has changed InventoryOriginal has 12 and InventoryBackup has 20. Can I copy the 12 columns from InventoryOriginal to InventoryBackup and the rest columns can be blank?但现在列数已更改 InventoryOriginal 为 12,InventoryBackup 为 20。我可以将 InventoryOriginal 中的 12 列复制到 InventoryBackup 并且 rest 列可以为空吗?

getting error - Column name or number of supplied values does not match table definition.出现错误 - 列名或提供的值的数量与表定义不匹配。

The general way you do this is to mention the target and source columns you want to use.您执行此操作的一般方法是提及您要使用的目标列和源列。 For example, for 3 columns you would use:例如,对于 3 列,您将使用:

INSERT INTO InventoryBackup (col1, col2, col3)
SELECT col1, col2, col3
FROM InventoryOriginal
WHERE Period = '2020-01-01';

Keep in mind that any columns in the target backup table for which were not mentioned would either be assigned a NULL value, or possibly a default value, if the table definition support that.请记住,目标备份表中未提及的任何列都将分配一个NULL值,或者如果表定义支持,则可能分配一个默认值。

The simple answer is yes, but you'll likely need to adjust your SQL statement to specify the columns.简单的答案是肯定的,但您可能需要调整 SQL 语句以指定列。 Eg.例如。

INSERT INTO InventoryBackup (col1, col2, col3, ...)
SELECT col1, col2, col3, ... FROM InventoryOriginal

This will be fine, as long as the extra columns in the "backup" table (that are no longer in the "orignal" table) allow NULLs.这会很好,只要“备份”表中的额外列(不再在“原始”表中)允许 NULL。 If they don't, then you'll need to specify a blank value (or 0, if they're numeric) when you insert.如果没有,那么您需要在插入时指定一个空白值(或 0,如果它们是数字)。 Eg.例如。

INSERT INTO InventoryBackup (col1, col2, col3, extra1, extra2, ...)
SELECT col1, col2, col3, '', 0, ... FROM InventoryOriginal

Hopefully that makes sense.希望这是有道理的。 The exact SQL statement that you're going to need is really going to depend on the actual structure of the "backup" table您将需要的确切 SQL 语句实际上取决于“备份”表的实际结构

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM