简体   繁体   English

批量仅插入新行

[英]Bulk Insert Only New Rows

I have aa group of csv files that I'm using to populate a SQL database. 我有一组用于填充SQL数据库的csv文件。 I'm setting this up to be a daily process. 我将其设置为日常工作。 I've just discovered though that a handful of the files come in each day with all the historical data, not just the daily updates. 我刚刚发现,每天都有少量文件包含所有历史数据,而不仅仅是每日更新。

When I try to do the bulk insert this causes an error because the primary key is being violated. 当我尝试进行批量插入时,这会导致错误,因为违反了主键。

I thought that setting IGNORE_DUP_KEY = ON would stop the non-unique records from being inserted. 我认为设置IGNORE_DUP_KEY = ON会阻止非唯一记录的插入。

CREATE TABLE TABLE1
(
Column1 varchar(32),
Column2 varchar(32),
Column3 char(9),
Column4 int,
Column5 float(53),
Column6 date,
CONSTRAINT pk_One
    PRIMARY KEY (Column1, Column2, Column6)
    WITH (IGNORE_DUP_KEY = ON)
);

Then when I try to run the script that updates the tables I get the unhelpful error message "Associated statement is not prepared (0)." 然后,当我尝试运行更新表的脚本时,收到无用的错误消息“关联语句未准备好(0)”。

I could get around this by writing the results into a separate table, then writing the new rows into the table proper, but having separate handling for the different tables strikes me as painful, and ugly. 我可以通过将结果写入单独的表中,然后将新行正确写入表中来解决此问题,但是对不同的表进行单独的处理会让我感到既痛苦又丑陋。

Is there an easy way to just tell SQL to only write the rows that don't violate the primary key constraint? 有没有一种简单的方法可以告诉SQL只写不违反主键约束的行?

Insert into table1 (column1) value (value1) 将值(value1)插入表1(列1)

... So, if you just want to ignore inserts that fail, do INSERT IGNORE INTO. ...因此,如果您只想忽略失败的插入,请执行INSERT IGNORE INTO。 Then it'll try to insert the values, fail, and move on gracefully. 然后它将尝试插入值,失败并继续进行。 If you want it to replace the duplicate key values with the new values it attempted to insert, check out : (below, ignore optional, depends on if you want it to throw errors.) 如果希望它用尝试插入的新值替换重复的键值,请签出:(下面,忽略可选,取决于是否要抛出错误。)

INSERT [IGNORE] INTO table1 (column1) values (value1) ON DUPLICATE KEY UPDATE

so "insert ignore" is the answer, on inserts not on table creation. 因此,“插入忽略”是答案,而不是在表创建时。 refer to mysql docs . 参考mysql文档 and ON DUPLICATE KEY UPDATE is useful to know. 和ON DUPLICATE KEY UPDATE很有用。

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

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