SQL Server 2005: Nullable Foreign Key Constraint

后端 未结 1 446
深忆病人
深忆病人 2021-02-07 11:18

I have a foreign key constraint between tables Sessions and Users. Specifically, Sessions.UID = Users.ID. Sometimes, I want Sessions.UID to be null. Can this be allowed? Any tim

1条回答
  •  被撕碎了的回忆
    2021-02-07 11:53

    I seemed to remember creating a nullable FK before, so I whipped up a quick test. As you can see below, it is definitely doable (tested on MSSQL 2005).

    Script the relevant parts of your tables and constraints and post them so we can troubleshoot further.

    CREATE DATABASE [NullableFKTest]
    GO
    USE [NullableFKTest]
    GO
    CREATE TABLE OneTable 
    (
        OneId  [int] NOT NULL,
        CONSTRAINT [PK_OneTable] PRIMARY KEY CLUSTERED 
        (
            [OneId] ASC
        )
    )
    CREATE TABLE ManyTable (ManyId  [int] IDENTITY(1,1) NOT NULL, OneId [int] NULL)
    GO
    IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_ManyTable_OneTable]') AND parent_object_id = OBJECT_ID(N'[dbo].[ManyTable]') )
    ALTER TABLE [dbo].[ManyTable]  WITH CHECK ADD CONSTRAINT [FK_ManyTable_OneTable] FOREIGN KEY([OneId])
        REFERENCES [dbo].[OneTable] ([OneId])   
    GO
    
    --let's get a value in here
    insert into OneTable(OneId) values(1)
    select* from OneTable
    
    --let's try creating a valid relationship to the FK table OneTable
    insert into ManyTable(OneId) values (1) --fine
    --now, let's try NULL
    insert into ManyTable(OneId) values (NULL) --also fine
    --how about a non-existent OneTable entry?
    insert into ManyTable(OneId) values (5) --BOOM! - FK violation
    
    select* from ManyTable
    --1, 1
    --2, NULL
    
    --cleanup
    ALTER TABLE ManyTable DROP CONSTRAINT FK_ManyTable_OneTable
    GO
    drop TABLE OneTable
    GO
    drop TABLE ManyTable
    GO
    USE [Master]
    GO
    DROP DATABASE NullableFKTest
    

    0 讨论(0)
提交回复
热议问题