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
Oracle auto add current date
提问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
假如说
- Your column is not actually named
date
since that is a reserved word - Your column is actually defined as a
date
rather than as anumber
- You want to populate the column when you insert a new row
- 您的列实际上并未命名,
date
因为这是一个保留字 - 您的列实际上被定义为 a
date
而不是 anumber
- 您想在插入新行时填充该列
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 dt
column when you UPDATE
the row, you would need a trigger
如果要在行时修改dt
列UPDATE
,则需要触发器
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 INSERT
or UPDATE
statement for the dt
column. A default value will not.
触发器将覆盖作为列的INSERT
orUPDATE
语句的一部分传入的任何值dt
。默认值不会。