i have a "main table", call it Customers
:
CREATE TABLE Customers (
CustomerID int PRIMARY KEY NOT NULL,
FirstName nvarchar(50),
LastName nvarchar(50)
)
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)
)
Now, what i want is a foreign key constraint from the Illegal
table back to the main Customers
table:
In other words:
Customer
without an Illegal
entryIllegal
entry without a Customer
My instinct was to, in the SQL Server database diagram, drag
Illegal
table TO the Customers
tableIndicating 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:
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:
But that wasn't my question.
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, '', '');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With