SQL Oracle 自动添加当前日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13479229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 12:13:02  来源:igfitidea点击:

Oracle auto add current date

sqloracle

提问by Wizard

I want create a table 'product' and have a column date, is it possible that current date will be added when I add some info to table?

我想创建一个表“产品”并有一列date,当我向表中添加一些信息时,是否有可能添加当前日期?

If yes please example of this table

如果是,请举例此表

create table products (
id number not null,
date number not null
);

回答by Justin Cave

Assuming that

假如说

  1. Your column is not actually named datesince that is a reserved word
  2. Your column is actually defined as a daterather than as a number
  3. You want to populate the column when you insert a new row
  1. 您的列实际上并未命名,date因为这是一个保留字
  2. 您的列实际上被定义为 adate而不是 anumber
  3. 您想在插入新行时填充该列

you can define a default value for the column.

您可以为该列定义一个默认值。

SQL> ed
Wrote file afiedt.buf

  1  create table products (
  2  id number not null,
  3  dt date   default sysdate not null
  4* )
SQL> /

Table created.

SQL>
SQL> insert into products( id ) values( 1 );

1 row created.

SQL> select * from products;

        ID DT
---------- ---------
         1 20-NOV-12

If you want to modify the dtcolumn when you UPDATEthe row, you would need a trigger

如果要在行时修改dtUPDATE,则需要触发器

CREATE OR REPLACE TRIGGER trg_products
  BEFORE INSERT OR UPDATE ON products
  FOR EACH ROW
BEGIN
  :new.dt := sysdate;
END;

A trigger will override any value passed in as part of the INSERTor UPDATEstatement for the dtcolumn. A default value will not.

触发器将覆盖作为列的INSERTorUPDATE语句的一部分传入的任何值dt。默认值不会。