SQL Server trigger on insert and how to reference the data that was inserted(插入时的 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.
推荐答案
使用'inserted'表:
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 触发器以及如何引用插入的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:插入时的 SQL Server 触发器以及如何引用插入的数据
基础教程推荐
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 带更新的 sqlite CTE 2022-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
