2

我有如下表格:

坦克桌

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) 

现在是这样的,有一个不同种类的鱼缸。我想把鱼放进鱼缸。吃指定哪两个物种互相吃。如果我们在吃像

species1='a' species2='b'

这意味着物种'a'吃'b',所以我们不能把它们都放在同一个缸里。现在我正在尝试创建一个名为 fish 的表,它应该有

name
species
tanknum

在创建表格时,我想在这里添加一个条件,即同一个鱼缸中的任何两条鱼都不应该互相吃掉。我想使用检查约束来实现这一点,并且我正在研究 oracle SQL。需要一些帮助。

4

2 回答 2

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;
于 2013-03-02T16:43:25.923 回答
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;
于 2013-03-04T12:16:28.887 回答