Jump to content

Recommended Posts

Posted

Muito boa tarde,

Ando com algumas dúvidas como ligo as minhas tabelas da minha BD, eu penso estar a fazer direito mas provavelmente não estou pois não daria erro,

Será que alguém me poderia rever este código a ver o que eu fiz mal ?

Desde já muito Obrigado.

CREATE TABLE Clientes
(
ID_Cliente int PRIMARY KEY,
Nome VARCHAR2(50) not null,
Morada VARCHAR2(100) not null,
NIF int not null,
BI int not null,
Telemovel int not null,
Data_Registo date not null,
FOREIGN KEY(ID_Cliente) REFERENCES Cartao(ID_Cliente)
);
CREATE TABLE Cartao
(
ID_Cartao int Primary key,
Data_Emissao Date not null,
ID_Cliente int not null,
Pontos int not null,
FOREIGN KEY(ID_Cartao) REFERENCES Encomenda(ID_Cartao)
);
CREATE TABLE Encomendas
(
ID_Encomenda int Primary key,
ID_Cartao int not null,
Dama_Emissao date not null,
Data_Entrega date not null,
Hora_Entrega date not null,
ID_Produto int not null
);

  • 3 weeks later...
Posted (edited)

simples..

"FOREIGN KEY(ID_Cliente) REFERENCES Cartao(ID_Cliente)"

quando este código é executado a tabela cartao ainda não existe 😄

Best practice:

primeiro cria as tabelas todas (CREATE TABLE), depois cria as PKs e UKs (ALTER TABLE .. ADD CONSTRAINT..) e só depois as FKs (ALTER TABLE .. ADD CONSTRAINT..)..

assim nunca tens estes problemas.

inté!

Edited by jsWizard
Posted

Parece-me é que de facto as chaves estão todas trocadas...

A tabela cliente não tem nenhuma foreignkey, a tabela cartão tem de ter para a tabela cliente, e tabela encomendas para a tabela cartão:

CREATE TABLE Clientes
(
 ID_Cliente INT PRIMARY KEY,
 Nome VARCHAR2(50) NOT NULL,
 Morada VARCHAR2(100) NOT NULL,
 NIF INT NOT NULL,
 BI INT NOT NULL,
 Telemovel INT NOT NULL,
 Data_Registo DATE NOT NULL
);
CREATE TABLE Cartao
(
 ID_Cartao INT PRIMARY KEY,
 Data_Emissao DATE NOT NULL,
 ID_Cliente INT FOREIGN KEY REFERENCES Clientes(ID_Cliente),
 Pontos INT NOT NULL
);
CREATE TABLE Encomendas
(
 ID_Encomenda INT PRIMARY KEY,
 ID_Cartao INT FOREIGN KEY REFRENCES Cartao(ID_Cartao),
 Dama_Emissao DATE NOT NULL,
 Data_Entrega DATE NOT NULL,
 Hora_Entrega DATE NOT NULL,
 ID_Produto INT NOT NULL
);
Posted

Uma outra solucao seria a criacao das tabelas a serem referenciadas antes e

depois criar as tabelas que referenciam as outras, assim evitas ter que usar o script

ALTER TABLE visto que numa situacao em que tens muitas tabelas poderias perder o controlo

das tabelas por alterar.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.