简体   繁体   中英

Oracle Sql: How to set a default column value on insert select

In my Oracle 11 database, I have a sql script for inserting(migrating) data from one table into another, this is a problem I encounter a lot, for instance :

INSERT INTO TargetTable (eventname, eventplace, eventdate)
SELECT  name, eventplace, "How to insert time here?"   FROM SourceTable;

The SourceTable don't have the eventdate column, and it is "Not Nullable" in TargetTable, so I have to insert something there, in this case I just want to just use the current time for all rows. How can I do this?

ps Not only for dates, This could also be a missing varchar column and I might to set a default value in target database.

Try this:

INSERT INTO TargetTable (
  eventname, 
 eventplace, 
  eventdate)
 SELECT name, 
        eventplace, 
        SysDate -- <- Current Date and Time
   FROM SourceTable;

modify the table definition like this:

create table table_name
(
col1 varchar2(10),
default_date_col date default sysdate
);

this way u dont need to include the date column in the insert in case u dont need it.

对于日期字段,只需使用sysdate,对于varchar文件,我认为您做对了,请在选择工作后添加“默认值”。

If you Want date format into varchar2 column use

 TO_CHAR(SYSDATE,'YYYY.MM.DD HH24:MI:SS');

You can play with functions how you like

example

TO_DATE(TO_CHAR(2013) || TO_CHAR(SYSDATE,'.MM.DD HH24:MI:SS'), 'YYYY.MM.DD HH24:MI:SS');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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