不知道如何将Oracle触发器转换为Microsoft SQL Server Management Studio触发器

时间:2018-12-19 07:27:31

标签: sql sql-server oracle ddl

我真的不熟悉使用MS SQL的触发器。 这是我使用Oracle SQL进行的触发。

create or replace trigger a4history
after update or delete on STUDENT
for each row
begin
    if updating then
        insert into SHISTORY (SHistoryID,StudentID,RoomNo,Event)
 VALUES ('SH' || sseq.nextval,:old.StudentID,:old.RoomNo,'UPDATE');
    elsif deleting then
        insert into SHISTORY (SHistoryID,StudentID,RoomNo,Event)
 VALUES ('SH' || sseq.nextval,:old.StudentID,:old.RoomNo,'DELETE');
    end if;
end;

create or replace trigger b4student
before insert on STUDENT
for each row
declare
    noroom number;
begin
    select RoomNo INTO noroom
    FROM ROOM
    where RoomID = :new.RoomID;
    :new.RoomNo := noroom;
end;

在MS SQL中触发之后还是之前?

2 个答案:

答案 0 :(得分:1)

这是您可以使用的示例插入触发器模板,请注意,所有更改的行都在临时表INSERTED中。如果要编写更新触发器而不是插入触发器,则仍然必须使用INSERTED表来查找更改。祝你好运

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[tbl_Mydata_INSERT]
   ON [dbo].[tbl_Mydata]
   AFTER INSERT
AS 
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Update basedata after insert
    UPDATE 
        E SET 
        E.Field = 'something'
    FROM [tbl_Mydata] E
        INNER JOIN INSERTED I ON I.ID = E.ID


END

答案 1 :(得分:0)

相应的触发器将是instead of触发器:

create or replace trigger b4student instead of insert as
begin
    insert into b4student ( . . ., roomid, . . . )
        select . . ., r.roomid, . . .
        from inserted i join
             room r
             on i.roomid = r.roomid;
end;

我认为您也可以这样做:

create or replace trigger b4student instead of insert as
begin
    insert into b4student
        select i.*;

    update b
        set roomid = r.roomno
        from b4student b join
             inserted i
             on b.<primary key> = i.<primary key> join  -- whatever the primary key is
             room r
             on i.roomid = r.roomid;
end;