Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   Varios (https://www.clubdelphi.com/foros/forumdisplay.php?f=11)
-   -   Foreign key referenciando 2 tablas (https://www.clubdelphi.com/foros/showthread.php?t=87504)

JAI_ME 15-01-2015 19:14:19

Foreign key referenciando 2 tablas
 
Buenas tardes, tengo las siguientes tablas

Código:

create table table1 (
  idTable1 integer not null primary key,
  nombre varchar(20)
);

create table table2 (
  idTable2 integer not null primary key,
  nombre varchar(20)
);

create table table3 (
  idTable3 integer not null primary key,
  idReferencia integer,
  nombre varchar(20),
  tipo integer
);


El campo idReferencia de la table3 debe tener los Id de las tablas 1 o 2 y el campo tipo indica si debe buscar en la tabla1 o tabla2 al momento de hacer una consulta.

En otras palabras quiero saber si idRefencia puedo crearle dos foreing key a las Tablas 1 y 2 y busque segun el valor del campo Tipo, o necesariamente tengo que crear 2 campos con sus repectivas referencias y dejar un de los dos null cuando se cree un registro en la tabla3.

duilioisola 16-01-2015 00:28:03

No mencionas la base de datos que deseas utilizar. Supondré por tanto que utilizas Firebird o MySQL. En ese caso no puedes controlar la restricción que mencionas mediante FKs. Deberías hacerlo mediant triggers.
Código SQL [-]
CREATE TRIGGER TABLE3_BI0
as
begin
   if (tipo = 1) then
   begin
      if (not exists(select id_Table1 from table1 where id_Table1 = new.idReferencia)) then
         exception ERR_NO_EXISTE_REF;
   end

   if (tipo = 2) then
   begin
      if (not exists(select id_Table2 from table2 where id_Table2 = new.idReferencia)) then
         exception ERR_NO_EXISTE_REF;
   end
end

CREATE TRIGGER TABLE3_BU0
as
begin
   if ((new.idReferencia <> old.idReferencia) or (new.tipo <> old.tipo)) then
   begin 
      if (tipo = 1) then
      begin
         if (not exists(select id_Table1 from table1 where id_Table1 = new.idReferencia)) then
            exception ERR_NO_EXISTE_REF;
      end

      if (tipo = 2) then
      begin
         if (not exists(select id_Table2 from table2 where id_Table2 = new.idReferencia)) then
            exception ERR_NO_EXISTE_REF;
      end
   end
end


La franja horaria es GMT +2. Ahora son las 04:07:43.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi