Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a One-to-Optional-One constraint in SQL Server

i have a "main table", call it Customers:

 CREATE TABLE Customers (
     CustomerID int PRIMARY KEY NOT NULL,
     FirstName nvarchar(50),
     LastName nvarchar(50)
 )

enter image description here

And i have a "satellite table", call it Customer_IllegallyObtainedInformation:

CREATE TABLE Customer_IllegallyObtainedInformation (
    CustomerID int PRIMARY KEY NOT NULL,
    CellPhonePin int,
    SexualOrientation varchar(20),
    EmailPassword varchar(50)
)

enter image description here

Now, what i want is a foreign key constraint from the Illegal table back to the main Customers table:

enter image description here

In other words:

  • there can be a Customer without an Illegal entry
  • but there can never be an Illegal entry without a Customer

My instinct was to, in the SQL Server database diagram, drag

  • FROM the Illegal table TO the Customers table

Indicating to SQL Server that Customers_IllegallyObtainedInformation is the "child" in the relationship. Instead what happens in that SQL Server makes it a one-to-one relationship:

enter image description here

Meaning that if you try to insert a Customer, it will fail because there is no existing Illegal information.

How can i create a "Parent-Child", or "One-to-Optional-One" relationship in SQL Server?


Note: Don't confuse the example with the question. i could create an sacrificial primary surrogate key in the Illegal table:

enter image description here

But that wasn't my question.

like image 942
Ian Boyd Avatar asked Oct 31 '12 21:10

Ian Boyd


Video Answer


1 Answers

It seems the designer is creating the foreign key in the opposite direction.

Just code it yourself:

 CREATE TABLE Customers (
         CustomerID int PRIMARY KEY NOT NULL,
         FirstName nvarchar(50),
         LastName nvarchar(50)
     )

    CREATE TABLE Customer_IllegallyObtainedInformation (
        CustomerID int PRIMARY KEY NOT NULL,
        CellPhonePin int,
        SexualOrientation varchar(20),
        EmailPassword varchar(50),

        constraint fk_Customers foreign key (CustomerId) references dbo.Customers
    )

    -- succeeds:
    insert into dbo.Customers
        values(1, 'One', 'One'), (2, 'Two', 'Two')

    --fails:
    insert into dbo.Customer_IllegallyObtainedInformation
        values(3, 1, '', '');

    --succeeds:
    insert into dbo.Customer_IllegallyObtainedInformation
        values(1, 1, '', '');
like image 151
nathan_jr Avatar answered Sep 21 '22 21:09

nathan_jr