简体   繁体   English

每次插入一行时的SQL更新列

[英]Sql update column every time a row is inserted

Ok, so I have this table: VersionsEditor with id - bigint version - integer startdate- date endDate - date bookId - integer 好的,所以我有了这个表:具有ID的VersionsEditor-bigint版本-整数startdate-日期endDate-日期bookId-整数

My problem: When I insert a new row for a certain book the endDate value must be "In progress". 我的问题:当我为某本书插入新行时,endDate值必须为“进行中”。 So I think I can't have date as the column type.. The logic is when the I have the greatest version for a certain book, then the endDate must be "In progress" 因此,我认为我不能将日期作为列类型。逻辑是当我拥有某本书的最高版本时,那么endDate必须为“进行中”

Why would you use a date column for status? 为什么要使用日期列作为状态? Instead, you want a another column for status. 相反,您需要另一列状态。 I might suggest a view: 我可能会建议一个观点:

create view v_book as
    select b.*,
           (case when startDate is null then 'NotStarted'
                 when endDate is null then 'InProgress'
                 else 'Done'
            end) as Status
    from books

What about Triggers (Oracle DB) like that ... 那样的触发器(Oracle DB)呢?

CREATE OR REPLACE TRIGGER t
  BEFORE
    INSERT OR
    UPDATE OF salary, department_id OR
    DELETE
  ON employees
BEGIN
  CASE
    WHEN INSERTING THEN
      DBMS_OUTPUT.PUT_LINE('Inserting');
    WHEN UPDATING('salary') THEN
      DBMS_OUTPUT.PUT_LINE('Updating salary');
    WHEN UPDATING('department_id') THEN
      DBMS_OUTPUT.PUT_LINE('Updating department ID');
    WHEN DELETING THEN
      DBMS_OUTPUT.PUT_LINE('Deleting');
  END CASE;
END;
/

A date should be a date and not an integer or varchar. 日期应该是日期,而不是整数或varchar。 If the meaning of "in progress" is that there cannot be any date specified, then just set it to null when in progress. 如果“进行中”的含义是不能指定任何日期,则在进行中时将其设置为null。 You can query it thus: 您可以这样查询它:

select coalesce( to_char(enddate, 'DD-MM-YYYY') , 'In progress' ) as end_date
from mytable
where ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM