简体   繁体   English

存储过程-更新和插入

[英]Stored Procedures - Updating and Inserting

I'm new to using stored procedures, what is the best way to update and insert using stored procedures. 我是使用存储过程的新手,使用存储过程进行更新和插入的最佳方法是什么。 I have two tables and I can match them by a distinct ID, I want to update if the ID exists in both my load table and my destination table, and I want to insert if the item does not exist in my destination table. 我有两个表,并且可以通过一个唯一的ID进行匹配,如果负载表和目标表中都存在该ID,我想进行更新;如果目标表中不存在该项目,我想进行插入。 Just an example template would be very helpful, thanks! 只是一个示例模板将非常有帮助,谢谢!

You should look up the SQL MERGE statement. 您应该查询SQL MERGE语句。

It allows you to perform UPSERT's - ie INSERT if a key value does not already exist, UPDATE if the key does exist. 它允许您执行UPSERT-即,如果键值尚不存在,则执行INSERT;如果键值已存在,则执行UPDATE。

http://technet.microsoft.com/en-us/library/bb510625.aspx http://technet.microsoft.com/zh-CN/library/bb510625.aspx

However, your requirement to check for a key value in 2 places before you perform an update does make it more complex. 但是,您要求在执行更新之前先检查两个位置的键值,这确实使它变得更加复杂。 I haven't tried this but I would think a VIEW or a CTE could be used to establish if the ID exists in both your tables & then base the MERGE on the CTE/VIEW. 我没有尝试过,但是我认为可以使用VIEW或CTE来确定两个表中是否都存在ID,然后将MERGE基于CTE / VIEW。

But definitely start by looking at MERGE! 但绝对要先看一下MERGE!

If I understood well, you want to select values in one table and insert them in other table. 如果我很了解,您想在一个表中选择值,然后将其插入另一表中。 If the id exists in the second table, you need to update the row. 如果ID在第二张表中存在,则需要更新该行。 If I'm not wrong you need something like this: 如果我没看错,您需要这样的东西:

mysql> select * from table_1;
+----+-----------+-----------+
| id | name      | last_name |
+----+-----------+-----------+
|  1 | fagace    | acero     |
|  2 | ratangelo | saleh     |
|  3 | hectorino | josefino  |
+----+-----------+-----------+
3 rows in set (0.00 sec)

mysql> select * from table_2;
+----+-----------+-----------+
| id | name      | last_name |
+----+-----------+-----------+
|  1 | fagace    | acero     |
|  2 | ratangelo | saleh     |
+----+-----------+-----------+
2 rows in set (0.00 sec)

mysql> insert into table_2 select t1.id,t1.name,t1.last_name from table_1 t1 on duplicate key update name=t1.name, last_name=t1.last_name;
Query OK, 1 row affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> select * from table_2;
+----+-----------+-----------+
| id | name      | last_name |
+----+-----------+-----------+
|  1 | fagace    | acero     |
|  2 | ratangelo | saleh     |
|  3 | hectorino | josefino  |
+----+-----------+-----------+
3 rows in set (0.00 sec)

mysql> 

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

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