Foreign Key Sql Server

Asked

Viewed 3,398 times

1

I have a question about Foreign key in the following situation:

Tehno table UF, with 3 columns:

ID_UF (PK), Cod_uf (int) and Descuf (nvarchar(50))

I have another table called IDE, with 3 columns:

ID_IDE (PK), Cod_uf(int) and Descide (nvarchar(50))

When I try to create a FK between the two tables with the Cod_uf column Sql gives a unique identifier error.

I understand the reason for the mistake, but what is the best solution to create a FK in a situation like this?

EDIT:

Answering questions about Cod_uf:

The ID_UF column is the internal code of the application for a given FU. The Cod_uf column is the code that the IBGE determines.

The IDE table receives information from a third party document that I receive via web service.

As I have no control of this webservice nor have to validate the information filled by the citizen on the other side of the webservice I thought of creating this FK between the UF table and the IDE table to avoid saving in this table an IBGE code that does not exist.

  • Wouldn’t it be better if you renamed Cod_UF of UF for CodIBGE?

  • It would even be changed after posting the question to Cod_ibge, because I read the comments and realized that the name of the column could cause confusion in the future.

  • Okay, but the answer, is there anything missing? You need me to complement something else?

  • I already thought about the solution of the question but I have not found a way to avoid inserting IBGE codes that do not exist in the UF table

  • I edited the answer, with the tip from UNIQUE for your column CodIBGE.

1 answer

4


..., what is the best solution to create an FK in such a situation?

Pointing foreign keys only to primary keys. For example:

CREATE TABLE UF (
    ID_UF INT PRIMARY KEY IDENTITY, 
    Cod_UF INT NOT NULL,
    DescUF nvarchar(50) NOT NULL
);

CREATE TABLE IDE (
    ID_IDE INT PRIMARY KEY IDENTITY, 
    Cod_UF INT NOT NULL
    DescIDE nvarchar(50) NOT NULL
);

ALTER TABLE IDE
ADD CONSTRAINT IDE_UF_FK FOREIGN KEY (Cod_UF) REFERENCES UF (ID_UF);

In fact, I don’t understand why there are two Cod_UF in both tables.


EDIT

To prevent CodIBGE cannot accept duplicate values, use:

ALTER TABLE UF
ADD UNIQUE (CodIBGE);

Or:

ALTER TABLE UF
ADD CONSTRAINT UQ_UF_CodIBGE UNIQUE (CodIBGE);
  • I think the relationship between UF and IDE is 1->N, so he needs cod_uf as FK in the IDE table. At least that’s what I understood.

  • Yes, but it’s still strange. It would be justified if it were a field Sigla, or if it has internal and external code. But internal and external code is a problematic practice.

  • 1

    Yes, truth analyzing better became strange even, because the PK of UF is ID_UF.

  • I made an Edit in the question explaining why to have Cod_uf in two tables.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.