创建一个插入触发器

时间:2011-04-05 10:21:51

标签: database sql-server-2008 triggers

如何在SQL Server中编写一个触发器,帮助我在将某些数据插入另一个表时将值插入表中?我还想在第二个表中使用插入的数据来插入第一个表。

有表A和表B,

当一行插入表B(TBLP1ISLEM)

我想从此插入中插入几个单元格,

进入表A(TBLP1DOVIZKURU)。

表B,已插入

触发帮助=>表A,插入

谢谢。

CREATE TRIGGER [dbo].[Deneme] 
   ON  [dbo].[TBLP1ISLEM] 
   FOR INSERT
AS 
IF(SELECT ID FROM inserted)>0
BEGIN
    SET NOCOUNT ON;
    INSERT INTO TBLP1DOVIZKURU(ISLEM_ID,DOVIZBIRIM,KUR) 
    SELECT ID, PARABIRIMI, KUR FROM inserted


END

3 个答案:

答案 0 :(得分:1)

在表B上添加触发器以进行插入。它将允许您捕获插入的数据并随意执行任何操作。您可以使用插入的数据,您可以查询另一个表...等...

CREATE TRIGGER trigger_Insert_TableB
ON TableB
FOR INSERT
AS
Begin
    Select * FROM Inserted //This will give you the inserted data
End

答案 1 :(得分:1)

CREATE TRIGGER your_trigger_name
ON  [TableB]
FOR INSERT
AS 
BEGIN

INSERT INTO TableA (tA_field1,tA_field2,tA_other_fields)  SELECT tB_field1,tB_field2,tB_other_fields FROM Inserted

END

答案 2 :(得分:1)

SYSTEM@valeh> create table emp_list (id number, name varchar2(20));
 SYSTEM@valeh> insert into emp_list values (1,'Valeh');
 SYSTEM@valeh> create table emp_age (age_id number, emp_id number, emp_age number);
 SYSTEM@valeh> create view emp_view as select * from emp_list el,emp_age age where el.id=age.emp_id;


create or replace trigger view_trigger
 instead of insert on emp_view
 referencing new as new old as old
 declare
 v_id VARCHAR(20);
 begin
 if :new.id is not null then
 insert into emp_list (id,name) values (:new.id,:new.name);
 insert into emp_age (age_id,emp_id,emp_age) values (:new.age_id,:new.emp_id,:new.emp_age)
 returning :new.id into v_id;
 else
 raise_application_error (-20999, 'Cannot create employee without name');
 end if;
 end;


SYSTEM@valeh> insert into emp_view values (2,'taleh',2,2,20);

SYSTEM@valeh> select * from emp_view;