Allowing null in a foreign key

  • I have added these tables to my database (for example):

    CREATE TABLE dbo.Departments (

    DeptID INT IDENTITY NOT NULL PRIMARY KEY NONCLUSTERED,

    DeptName NVARCHAR(50) NOT NULL,

    DeptDeleted BIT NOT NULL DEFAULT 0

    );

    CREATE TABLE dbo.Employees (

    EmployeeID INT IDENTITY NOT NULL PRIMARY KEY NONCLUSTERED,

    // Other fields

    DeptID INT NULL FOREIGN KEY REFERENCES dbo.Departments

    );

    If I then write:

    INSERT INTO Employees (

    // OtherFields,

    DeptID = null

    );

    I get an error on the foreign key relationship.

    Is there something else I need to do to allow the null to be inserted in the Employees table?

    Doug

  • Can you past INSERT statement you use?

    Error must be there.

    _____________
    Code for TallyGenerator

  • But with exactly the same insert statement except DeptID equal to a valid record in the Departments table, the insert succeeds.

    Doug

  • How do you assighn NULL?

     

    _____________
    Code for TallyGenerator

  • Not quite certain what you mean.

    The insert statement is just as shown in the original example.

    For that field: DeptID = null

    Doug

  • Yes of course, that is the problem.

    The assignment when it's null is incorrect. I can see the error now.

    Thanks so much.

    Doug

Viewing 6 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic. Login to reply