我有如下表格:
CREATE TABLE fishtank(
tanknum number(8),
temperature number(6,2),
capacity number(10),
primary key(tanknum));
Name Null Type
----------- -------- -----------
TANKNUM NOT NULL NUMBER(8)
TEMPERATURE NUMBER(6,2)
CAPACITY NUMBER(10)
CREATE TABLE type(
species varchar2(20),
mintemp number(6,2),
maxtemp number(6,2),
primary key(species));
Name Null Type
------- -------- ------------
SPECIES NOT NULL VARCHAR2(20)
MINTEMP NUMBER(6,2)
MAXTEMP NUMBER(6,2)
CREATE TABLE eats(
species1 varchar2(20),
species2 varchar2(20),
primary key(species1, species 2),
foreign key(species1) references type,
foreign key(species2) references type);
Name Null Type
-------- -------- ------------
SPECIES1 NOT NULL VARCHAR2(20)
SPECIES2 NOT NULL VARCHAR2(20)
现在就像这样有一个不同种类的鱼缸。我想把鱼插入水箱。 Eats指定哪两个物种互相吃。如果我们有像
这样的食物中的值species1='a' species2='b'
这意味着物种'a'吃'b',因此我们不能将它们放在同一个罐中。现在我正在尝试创建一个名为fish的表,它应该有
name
species
tanknum
在创建桌子时我想在这里添加一个条件,即同一个坦克中的任何两条鱼都不应该互相吃掉。我想使用检查约束来实现它,我正在研究oracle SQL。需要一些帮助。
答案 0 :(得分:1)
触发器将是一个很好的解决方案
create trigger prevent
on fish
for insert
as
begin
if ( CASE when inserted.species IN (SELECT DISTINCT (species2) FROM fish f JOIN eats e ON f.species= e.species1) THEN 1 ELSE 0 END)
/* Cancel the insert and print a message.*/
rollback transaction;
print "No fish eating allowed!." ;
/* Otherwise, allow it. */
else
print "Added!";
end if;
end;
答案 1 :(得分:0)
你好老兄刚检查一下!!!!有任何澄清让我知道!!!!
create or replace
TRIGGER check_fish before
INSERT ON fish_in_tank FOR EACH row DECLARE
Type rec_2 IS TABLE OF fish_in_tank%rowtype;
fish_dup rec_2;
no_insert EXCEPTION;
BEGIN
SELECT name,
SPECIES,
tanknum bulk collect
INTO fish_dup
FROM fish_in_tank
WHERE SPECIES IN
(SELECT case when species1=:new.species then species2 when species2=:new.species then species1 end FROM Eats );
dbms_output.put_line(fish_dup(1).name);
FOR i IN fish_dup.first..fish_dup.last
LOOP
IF (:new.tanknum=fish_dup(i).tanknum) THEN
raise no_insert;
END IF;
END LOOP;
EXCEPTION
WHEN no_insert THEN
raise_application_error(-20000,'Cannot insert');
WHEN NO_DATA_FOUND THEN
dbms_output.put_line('Successful');
END;