add a foreing key to an existing table

Asked

Viewed 653 times

0

I have to create a column in an existing table and at the same time create a foreing key with another table using this column that was created, and this foreing key by default has to be null. The way I’m doing it and this

 IF NOT EXISTS (SELECT * FROM SYSCOLUMNS C INNER JOIN SYSOBJECTS T ON C.id = T.id WHERE C.name = ('IdSetorPreparo') AND T.name = 'Produto')

    BEGIN
    ALTER TABLE Produto  
            ADD IdSetorPreparo int     
    END 

    ALTER TABLE Produto 
        ADD CONSTRAINT FK_Produto_IdSetorPreparo FOREIGN KEY(IdSetorPreparo) REFERENCES OrgSetor(id)  

Well, I was wondering if it’s possible at the same time to create the column to already create the foreing key.

  • Your table Produto already has data?

1 answer

2

In SQL Server you can do so:

ALTER TABLE Produto
    ADD IdSetorPreparo INTEGER,
    FOREIGN KEY(IdSetorPreparo) REFERENCES OrgSetor(id);

If you want the column to admit NULLS you just have to set it to NULL.

ADD IdSetorPreparo INTEGER NULL

In this particular case the Constraint will not be verified.

  • Thanks for helping Bruno, managed to overcome my doubt, if it was possible to create the column and already set a foreing key, thank you.

  • No problem, I’m glad I could help!

Browser other questions tagged

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