有没有一种基于条件添加到表中的方法?

时间:2019-12-18 18:47:13

标签: database oracle oracle11g

几天来,我一直在尝试使用Oracle 11g主页项目数据库解决此问题。我似乎无法解决这个问题。也许我缺少明显的东西。

我试图根据表中已有数据的多个条件,向表中添加一行。例如,只要该时间段尚未接管或与另一个时间段重叠,则将1pm到2pm的时间表添加。 Oracle没有布尔函数,我可以用来检查表是否已经包含此类信息。如果有时间段,我应该创建另一个临时表并尝试向左或向右联接两个表吗?

INSERT INTO Room(Building_Name, RoomNum, CourseNum, StaffID, Season, Year, 
Course_Days, Start_Time, End_Time)  
VALUES (buildingName, roomNum, courseNum, staffID, season, year, courseDays, 
startTime, endTime)  
Where EXISTS (Select * 
  From Room
      Where (StaffID = 12312 AND Start_Time < 14:00 AND End_Time < 14:00);  

谢谢

2 个答案:

答案 0 :(得分:2)

使用SELECT ... FROM DUAL代替VALUES:

INSERT INTO Room(Building_Name, RoomNum, CourseNum, StaffID, Season, Year, Course_Days, Start_Time, End_Time)  
SELECT buildingName, roomNum, courseNum, staffID, season, year, courseDays, startTime, endTime
FROM DUAL
WHERE EXISTS (
  SELECT 1 FROM Room
  WHERE StaffID = 12312 AND Start_Time < '14:00' AND End_Time < '14:00'
);

答案 1 :(得分:0)

好的,我想我明白您的要求了。我不清楚这些值从哪里来(buildingName等)-它是PL / SQL块的一部分吗?但是我会这样重写它:

INSERT INTO Room (Building_Name, RoomNum, CourseNum, StaffID, Season, Year, 
    Course_Days, Start_Time, End_Time)  
SELECT (buildingName, roomNum, courseNum, staffID, season, year, courseDays, 
    startTime, endTime)  
From dual
Where NOT EXISTS (Select * 
      From Room
      Where (StaffID = 12312 AND Start_Time < 14:00 AND End_Time < 14:00); 

我经常使用手动插入来执行此操作,在该操作中我指定了所有值,但是我想确保它们在表中不存在。在这种情况下,它可能更像:

INSERT INTO Room (Building_Name, RoomNum, CourseNum, StaffID, Season, Year, 
    Course_Days, Start_Time, End_Time)  
SELECT 'Building1', 117, 9782, 12312 as sid, 'Spring', 2020, 'MWF', 
    '1300' as startTime, '1400' as endTime 
From dual d
Where NOT EXISTS (Select * 
      From Room
      Where (StaffID = d.sid AND (d.startTime between Start_Time and End_Time-1
                                  OR d.endTime between Start_Time+1 and End_Time));