需要写一个触发器

时间:2011-05-13 10:33:05

标签: sql oracle triggers

我想为表“TRANSACTION”写一个触发器。当插入一个新行时,我想触发将“TRANSACTIONID”字段更新为所有先前记录的最大值+1。

我对SQL知之甚少。有人能帮助我吗?

非常感谢

2 个答案:

答案 0 :(得分:6)

对于多用户环境来说,这是一个非常糟糕的主意,因为它会将插入序列化到表中。通常的方法是使用Oracle序列:

create sequence transaction_seq;

create trigger transaction_bir before insert on transaction
for each row
begin
    :new.id := transaction_seq.nextval;
end;

要编写实际获得最大当前值加1的基于触发器的解决方案,您需要编写复杂的3触发解决方案以避免“变异表”问题。或者您可以使用另一个表创建一个更简单的解决方案来保存当前最大值,如下所示:

create table transaction_max (current_max_id number);

insert into transaction_max values (0);

create trigger transaction_bir before insert on transaction
for each row
declare
    l_current_max_id number;
begin
    update transaction_max set current_max_id = current_max_id + 1
        returning current_max_id into l_current_max_id;
    :new.id := l_current_max_id;
end;

这将避免变异表问题并将序列化(减慢)插入,因此我认为这不会比使用序列有任何优势。

答案 1 :(得分:0)

CREATE TRIGGER trigger1 on TransactionTable
INSTEAD OF INSERT
AS
BEGIN

  DECLARE @MaxTranId INT

    SELECT
        @MaxTranId = MAX(TransactionId)
    FROM
        TransactionTable

  INSERT INTO TransactionTable
       SELECT 
            @MaxTranId + 1 ,
            RestOfYourInsertedColumnsHere , 
       FROM 
        inserted
END
GO
相关问题