TransWikia.com

constraint em uma primary key - SQL

Stack Overflow em Português Asked by J.Rodrigues on February 5, 2021

Estou com um problema para intender qual a intenção nesse código abaixo ao colocar uma constraint para criar uma chave primaria de uma chave estrangeira.

CREATE TABLE Customer(
    IdCustomer integer PRIMARY KEY NOT NULL IDENTITY(1,1),
    NmCustomer varchar(255) NOT NULL,
    CpfCnpj numeric NOT NULL
);

CREATE TABLE AddressType(
    CdAddressType char(1) PRIMARY KEY NOT NULL,
    AddressType varchar(50) NOT NULL
);

CREATE TABLE CustomerAddress(
    IdCustomer integer,
    CdAddressType char(1),
    Street varchar(255) NOT NULL,
    Lot integer NOT NULL,
    Reference varchar(255) NULL,
    ZipCode varchar(50) NOT NULL
    CONSTRAINT FK_IdCustomer FOREIGN KEY (IdCustomer) REFERENCES Customer(IdCustomer),
    CONSTRAINT FK_CdAddressType FOREIGN KEY (CdAddressType) REFERENCES AddressType(CdAddressType),
    CONSTRAINT PK_CustomerAddress PRIMARY KEY (IdCustomer, CdAddressType)
);

One Answer

Criação da chave primária da tabela CustomerAddress:

CONSTRAINT PK_CustomerAddress PRIMARY KEY (IdCustomer, CdAddressType)

Criação de 2 chaves estrangeiras:

CONSTRAINT FK_IdCustomer FOREIGN KEY (IdCustomer) REFERENCES Customer(IdCustomer),
CONSTRAINT FK_CdAddressType FOREIGN KEY (CdAddressType) REFERENCES AddressType(CdAddressType),

Na coluna IdCustomer da tabela CustomerAddress só é possível adicionar valores que existam na coluna com o mesmo nome da tabela Customer.

Na coluna CdAddressType da tabela CustomerAddress só é possível adicionar valores que existam na coluna com o mesmo nome da tabela AddressType.

Answered by Marta B on February 5, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP