【问题标题】:SQL trigger to insert data from one table to another if a condition is met如果满足条件,SQL 触发器将数据从一个表插入到另一个表
【发布时间】:2020-09-24 13:06:24
【问题描述】:

我很遗憾未能构建一个 sql 触发器(在后台),如果满足某个条件,我想将数据从一个表插入到另一个表中,如下所示:

  1. 在表Invoice上创建触发器
  2. 如果inv_numberinv 开头
  3. 然后Insert into Document (var1,var2,var3) values (inv_number, inv_date, inv_amount)

谢谢

【问题讨论】:

  • 触发器是高度特定于供应商的 - 所以请添加标签以指定您使用的是mysqlpostgresqlsql-serveroracle 还是db2 - 或完全不同的东西。另外,请发布所涉及的两个表的表结构 - InvoiceDocument

标签: sql triggers


【解决方案1】:

如果您使用的是 SQL Server(正如我在 cmets 中所说的那样 - 触发器是 高度 特定于供应商的,所以如果您使用其他东西,您将必须根据需要进行调整),您可以使用以下内容:

CREATE TRIGGER trgInvoiceInsert
ON dbo.Invoice
AFTER INSERT    -- adapt if you need to run this after UPDATE or DELETE, too
AS 
BEGIN
    /* In SQL Server, if you inserting a bunch of rows 
       at once using an `INSERT INTO .... SELECT ....` 
       approach, then this trigger will be called only *ONCE*, 
       with all the inserted rows in the "Inserted" pseudo table.
       Handle it accordingly - in a set-based manner
    */
    INSERT INTO dbo.Document (col1, col2, col3)
        SELECT i.inv_number, i.inv_date, i.inv_amount)
        FROM Inserted i
        WHERE i.inv_number LIKE 'inv%'
END

更多详情,请查看official Microsoft documentation on SQL Server triggers

【讨论】:

    猜你喜欢
    • 2011-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-29
    • 2012-12-27
    • 1970-01-01
    相关资源
    最近更新 更多