我在以下代码中不断遇到主键违规。如果我将主键放在Times
表中,那么所有内容都按预期填充,但我必须有一个主键。在我的CASE
声明中,我尝试删除了sale_day
字段,但之后因在主键中插入NULL
而收到了违规行为。在我的游标中,您将看到对Sales
表的引用,该表包含填充sale_date
表中sale_day
字段的Times
字段。我迷失了如何继续。
SQL> CREATE TABLE Times (
2 sale_day DATE NOT NULL,
3 day_type VARCHAR2(50) NOT NULL,
4 PRIMARY KEY (sale_day));
Table created.
SQL>
SQL>
SQL> CREATE OR REPLACE PROCEDURE Time_Procedure
2 AS
3 l_sale_date date;
4 temp_value varchar2(5);
5 CURSOR c1 IS SELECT SALE_DATE FROM SALES;
6
7 BEGIN
8 OPEN c1;
9 LOOP
10 FETCH c1 INTO l_sale_date;
11 EXIT WHEN c1%NOTFOUND;
12 SELECT to_char(to_date(l_sale_date), 'DY') into temp_value from dual;
13 CASE
14 WHEN l_sale_date LIKE '%-JAN-01' OR l_sale_date LIKE '%-JAN-21' OR l_sale_date LIKE '%-FEB-18' OR l_sale_date LIKE '%-MAY-28'
15 OR l_sale_date LIKE '%-JUL-04' OR l_sale_date LIKE '%-SEP-03' OR l_sale_date LIKE '%-OCT-08' OR l_sale_date LIKE '%-NOV-11'
16 OR l_sale_date LIKE '%-NOV-22' OR l_sale_date LIKE '%-DEC-25' THEN
17 INSERT INTO Times values(l_sale_date,'Holiday');
18 WHEN temp_value='MON' OR temp_value ='TUE' OR temp_value='WED' OR temp_value='THU' OR temp_value='FRI' THEN
19 INSERT INTO Times values (l_sale_date,'Weekday');
20 ELSE
21 INSERT INTO Times values (l_sale_date, 'Weekend');
22 END CASE;
23 END LOOP;
24 CLOSE c1;
25 END;
26 /
Procedure created.
SQL>
SQL> /* Populate table*/
SQL>
SQL> BEGIN
2 Time_Procedure;
3 END;
4 /
BEGIN
*
ERROR at line 1:
ORA-00001: unique constraint (SDEV350USER.SYS_C0013043) violated
ORA-06512: at "SDEV350USER.TIME_PROCEDURE", line 19
ORA-06512: at line 2
答案 0 :(得分:0)
SALES似乎不是唯一日期的来源。也许它包含有时间元素的日子?如果是这样,可能截断日期(删除时间元素)并应用DISTINCT将解决问题。
PL / SQL不需要填充TIMES,因为我们可以在SQL中使用CASE。
insert into times
select sale_date
, case
when to_char(sale_date, 'MON-DD') in ('JAN-01','JAN-21','FEB-18','MAY-28'
,'JUL-04','SEP-03','OCT-08','NOV-11','NOV-22','DEC-25') then
'Holiday'
when to_char(sale_date, 'DY') in ('MON','TUE','WED','THU','FRI') then
'Weekday'
else
'Weekend'
end as day_type
from (select distinct trunc(sale_date) as sale_date
from sales)