简体   繁体   中英

How can I a foreign key to NULL in SQL Server database?

I'd like to get your advice about how i can add foreign key constraint with set null.

I wrote this SQL:

ALTER TABLE DEPARTMENT
ADD CONSTRAINT DEPARTMENT_HIDEPTID_FK 
    FOREIGN KEY (HIDEPTID) REFERENCES DEPARTMENT(DEPTID) 
    SET NULL

but, at the end of the above statement, set null causes an error.

I can add just foreign key, but with set null, I cannot.

Thank you.

Thank you for your hint.

ALTER TABLE DEPARTMENT
    ADD CONSTRAINT DEPARTMENT_HIDEPTID_FK 
        FOREIGN KEY(HIDEPTID) REFERENCES DEPARTMENT(DEPTID) 
            ON DELETE CASCADE

This works.

The reason I'd like to set null at foreign key is that the table references itself.

Thank you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM