在更新或插入之前将数据复制到另一个表。使用存储过程?

时间:2013-09-17 02:51:12

标签: sql sql-server

我需要在数据库中更新两个表。我正在从另一个数据库中的数据更新这些表。如果表1中的记录得到更新,我需要将表1中的旧信息存储在表2中。我需要逻辑来进行比较,然后在需要时更新表2。我的问题是,最好的方法是什么?我在想存储过程是可行的,但我不确定。

这是一个更直观的解释。

    Table 1
Student    Grade
james       6
sarah       5



  Table 2
   EMPTY

让我们说下面的数据是我从另一个数据库中提取的数据。

   Other Database
  Student     Grade
   james        6
   sarah        4
   tom          7

这是一些草率的逻辑,可能有助于解释我需要做什么。

--If records match do nothing 
IF otherDatabase.student =  table1.student  AND  otherDatabase.grade = table1.grade THEN do nothing

--If partial match copy old data to table 2 and insert new data to table1
IF otherDatabase.student = table1.student AND otherDatabse.grade !=  table1.grade 
THEN copy table1.student to table2.student AND copy table1.grade to table2.grade THEN UPDATE table1.grade from otherDatabase.grade

--If no match copy new data to Table1
IF otherDatabase.student != table1.student AND otherDatabase.grade != table1.grade THEN INSERT otherDatabase.student AND otherDatabase.grade INTO table1

在我的例子中,詹姆斯不会被触及,莎拉会被移到表2然后插入表1中,新等级,汤姆将插入表1。

如果这没有意义,我很抱歉。如果需要,请允许我澄清。感谢

2 个答案:

答案 0 :(得分:1)

您可以使用存储过程执行此操作,但我会使用触发器。

使用存储过程,我会感觉到您使用otherDatabase表上的游标来读取记录并将每个记录与Table1中的值进行比较,以确定Table1的数据是否需要写入Table2,如果需要,则将其写入做到这一点。

使用触发器,我只需通过任何方式更新Table1中的数据,而无需考虑覆盖数据和触发器中的内容,

使用## Inserted&amp ;;使用旧值和新值。 ##删除(系统)表以确定是否需要将旧值(## Deleted)写入Table2。例如

INSERT Table2 (Student, Grade)
SELECT d.Student, d.Grade
FROM ##Deleted d LEFT JOIN ##Inserted i ON d.[Key] = i.[Key]
WHERE (d.Student <> i.Student OR d.Grade <> i.Grade) AND d.[Key] IS NOT NULL

答案 1 :(得分:0)

Drop procedure if exists getCID;
delimiter // 
CREATE PROCEDURE getCID(IN cid varchar(100))
BEGIN
    create table Temp as(select i.invoice_no,i.cust_id,b.tot_amount,b.paid_amount,b.bal_amount from invoice_item_info i,bill_info b where i.invoice_no=b.invoice_no and i.cust_id=cid);
select * from Temp;
select DISTINCT cust_id,count(invoice_no),sum(tot_amount),sum(paid_amount),sum(bal_amount) from Temp;
Drop table Temp;
END
//
delimiter ;