如何在sql中插入增加日期

时间:2013-11-21 15:21:24

标签: sql oracle oracle11g sql-insert

我有以下查询,我需要按递增顺序插入开始日期,例如01/01 / 01,01 / 02 / 1000,01 / 03/1000,......

Insert into person_location(address,person,city,country,
  startdate,enddate,source) 
Select  distinct de.P_address,
  A.ID,
  de.P_city, 
  de.P_Country,
  to_date('01/01/1000','DD/MM/YYYY'),
  to_date('31/12/3999','DD/MM/YYYY'),
  de.source
from data_excel de, person A
where de.P_name in ( Select Distinct name from person)
and ID > 6571

2 个答案:

答案 0 :(得分:0)

我建议您创建一个正确命名和规范化的数据库模式。以下是粗略布局。请注意,每个表都有一个主键,以附加了“ID”的表命名。我认为通过使用这样的数据库模式可以回答您的问题。

人员表:

PersonID long not null primary key    
FirstName varchar255 not null
MiddleName varchar255 nullable
Lastname varchar255 not null

PersonAddress表:

PersonAddressID long not null primary key
PersonID long not null foreign key to the Person table  ((note: not unique, since a person may have more than one address))
StreetAddress varchar255 not null
CityID long not null foreign key to the City table
CountryID long not null foreign key to the Country table
StartDate Date not null  //when the person first moved to this address
EndDate Date nullable //when the person left this address. Null if still lives there

城市表:

CityID long not null primary key
Name varchar255 not null, unique

国家/地区表:

CountryID long not null primary key
Name varchar255 not null, unique

答案 1 :(得分:0)

创建一个序列,例如:

CREATE SEQUENCE start_Date_seq START WITH 1 INCREMENT BY 1 NOCACHE  NOCYCLE;

然后创建一个这样的触发器:

CREATE OR REPLACE TRIGGER person_location_insert
   BEFORE INSERT ON person_location

   BEGIN
     :new.startdate := ADD_MONTHS(TO_DATE('01/01/1000','DD/MM/YYYY'), start_Date_seq.nextval);
END;
相关问题