代码之家  ›  专栏  ›  技术社区  ›  sjain

在插入和更新行时填充当前日期的数据库触发器不起作用

  •  1
  • sjain  · 技术社区  · 9 年前

    功能-

    CREATE函数:

    -- Function: created_func()
    
    CREATE OR REPLACE FUNCTION created_func()
      RETURNS trigger AS
    $BODY$
        BEGIN
            -- Remember who changed the payroll when
            NEW.created_ts := current_timestamp;
            RETURN NEW;
        END;
    $BODY$
      LANGUAGE plpgsql VOLATILE
      COST 100;
    ALTER FUNCTION created_func()
      OWNER TO postgres;
    

    UPDATE函数:

    -- Function: updated_func()
    
    CREATE OR REPLACE FUNCTION updated_func()
      RETURNS trigger AS
    $BODY$
        BEGIN
            -- Remember who changed the payroll when
            NEW.updated_ts := current_timestamp;
            RETURN NEW;
        END;
    $BODY$
      LANGUAGE plpgsql VOLATILE
      COST 100;
    ALTER FUNCTION updated_func()
      OWNER TO postgres;
    

    触发器-

    CREATE触发器:

    -- Trigger: created_func on drcschema.dr_event
    
    CREATE TRIGGER created_func
      BEFORE INSERT
      ON drcschema.dr_event
      FOR EACH ROW
      EXECUTE PROCEDURE created_func();
    

    UPDATE触发器:

    -- Trigger: update_func on drcschema.dr_event
    
    CREATE TRIGGER update_func
      AFTER UPDATE
      ON drcschema.dr_event
      FOR EACH ROW
      EXECUTE PROCEDURE updated_func();
    

    列-

    创建时间:

    --列:created_ts

    ALTER TABLE drcschema.dr_event ADD COLUMN created_ts timestamp without time zone;
    

    更新的ts:

    --列:updated_ts

    ALTER TABLE drcschema.dr_event ADD COLUMN updated_ts timestamp without time zone;
    

    DrEvent.hbm.xml:

    <property name="createdTs" type="timestamp" generated="insert">
       <column name="created_ts" length="29" />
    </property>
    <property name="updatedTs" type="timestamp" generated="always">
       <column name="updated_ts" length="29" />
    </property>
    

    但我还是没能把日期弄进去 updated_ts 插入和更新行后的列,如下所示-

    enter image description here

    1 回复  |  直到 9 年前
        1
  •  1
  •   Patrick    9 年前

    你需要一个 BEFORE UPDATE 触发器,否则更改将不会持久存在表中。

    除此之外,对于如此相似的触发器函数,最好将它们合并为一个,这样“业务逻辑”就在一个地方,从而更容易维护:

    CREATE OR REPLACE FUNCTION ins_upd_func() RETURNS trigger AS $BODY$
    BEGIN
      -- Remember who changed the payroll when
      IF TG_OP = 'INSERT' THEN
        NEW.created_ts := current_timestamp;
      ELSE
        NEW.updated_ts := current_timestamp;
      END IF;
      RETURN NEW;
    END; $BODY$ LANGUAGE plpgsql VOLATILE;
    

    触发器:

    CREATE TRIGGER ins_upd_tr
    BEFORE INSERT OR UPDATE ON drcschema.dr_event
    FOR EACH ROW EXECUTE PROCEDURE ins_upd_func();