SQL Transact - 将INSERT触发到特定表

时间:2015-04-29 09:35:33

标签: sql tsql

如果调用INSERT,我需要编写一个执行简单任务的SQL Transact触发器,但仅当INSERT修改表t时(如果INSERT INTO t (...) VALUES (...)

我正在使用if (UPDATE[col])作为执行任务的触发器,但不经意的是,创建行时不是调用,我也需要管理这个案例。

我看过EVENT_DATEAFTER INSERT,但我不知道如果INSERT在特定的表t中运行,该如何执行它。

我可以举例说明如何做到这一点吗?

这是一个伪代码:

IF (new row is insert on T) OR (T.c is updated)
{
 My task
}

2 个答案:

答案 0 :(得分:0)

来自手册https://msdn.microsoft.com/en-GB/library/ms189799.aspx

-- SQL Server Syntax 
Trigger on an INSERT, UPDATE, or DELETE statement to a table or view (DML Trigger)

CREATE TRIGGER [ schema_name . ]trigger_name 
ON { table | view } 
[ WITH <dml_trigger_option> [ ,...n ] ]
{ FOR | AFTER | INSTEAD OF } 
{ [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] } 
[ WITH APPEND ]
[ NOT FOR REPLICATION ] 
AS { sql_statement  [ ; ] [ ,...n ] | EXTERNAL NAME <method specifier [ ; ] > }

所以你需要像

这样的东西
create trigger mytrigger 
on mytable
for insert, update
as 
   // stuff to do

或者如果你想写更新并单独插入

create trigger mytrigger_update
on mytable
for update
as 
   // stuff to do for update


create trigger mytrigger_insert
on mytable
for insert
as 
   // stuff to do for insert

答案 1 :(得分:0)

CREATE TRIGGER [ schema_name. ]trigger_name
ON T
AFTER INSERT
AS {
your statement here
} 

此语句在表T上创建一个名为trigger_name的triger,它将在此表上插入后触发