SQL Server在插入时触发以及如何引用已插入的数据 [英] SQL Server trigger on insert and how to reference the data that was inserted

查看:94
本文介绍了SQL Server在插入时触发以及如何引用已插入的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

高级别,我有两个表需要镜像一些数据。我无法浏览并更改所有代码以将两者都写入,因此我认为只要将数据插入第一个表,就可以使用SQL触发器将数据插入第二个表。这是我遇到的问题:

High level I have two tables that need to have some of the data mirrored. I can't go through and change all of the code to write to both so I thought I'd use a SQL trigger to insert data into the 2nd table anytime data is inserted into the 1st. Here is where I am stuck:

CREATE TRIGGER new_trigger_INSERT
ON old_table
FOR INSERT
INSERT INTO new_table (id, first_name, last_name)
VALUES () --This is where I'm lost, I need to insert some of the data from the insert that executed this trigger

我们将不胜感激,如果有更好的方法可以做到这一点,请告诉我。

Any help is appreciated, also if there is a better way to accomplish this let me know.

推荐答案

使用 插入表:

CREATE TRIGGER new_trigger_INSERT 
ON old_table 
FOR INSERT 
INSERT INTO new_table (id, first_name, last_name) 
SELECT col1, col2, col3 FROM inserted

[PS:别忘了确保触发器处理多行...]

[PS: Don't forget to ensure your triggers handle multiple rows...]

参考创建触发器

好的文章:探索SQL Server触发器

这篇关于SQL Server在插入时触发以及如何引用已插入的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆