Question

I want to set up two tables in sql command.

I have a Customer table and a User Account table.

A Customer has none or at most 1 User_account (0...1) relationship.

But a USER_ACCOUNT will always have a CUSTOMER.

How can I do it via SQL command?

EDIT Here's what I have tried so far:

ALTER TABLE UserAccount DROP CONSTRAINT FKUserAccountToCustomer
GO

DROP TABLE Customer;
DROP TABLE UserAccount;
GO

CREATE TABLE Customer
(
    CustomerID INT NOT NULL IDENTITY,
    (...)
);
GO

CREATE TABLE UserAccount
(
    UserAccountID INT NOT NULL IDENTITY,
    CustomerID INT NOT NULL,
    (...)
);
GO

ALTER TABLE Customer ADD PRIMARY KEY (CustomerID);
GO

ALTER TABLE UserAccount ADD PRIMARY KEY(UserAccountID);
GO

IF NOT EXISTS (SELECT * FROM sysdiagrams WHERE name = 'FKUserAccountToCustomer')
BEGIN
    ALTER TABLE UserAccount
    ADD CONSTRAINT FKUserAccountToCustomer
    FOREIGN KEY(CustomerID)
    REFERENCES Customer(CustomerID)
END;
Was it helpful?

Solution

If a customer can have 0 or 1 user account, then make the UserAccount Id the same as the Customer Id, enforced with primary key and foreign key constraints like so:

CREATE TABLE Customer
 (
   CustomerId     int  not null identity(1,1)
    constraint PK_Customer
     primary key clustered
   ,(...)
 )

CREATE TABLE UserAccount
 (
   UserAccountId  int  not null
    constraint PK_UserAccount
     primary key clustered
    constraint FK_UserAccount__Customer
     foreign key references Customer (CustomerId)
   ,(...)
 )

This way:

  • you cannot create a user account without first creating a customer
  • you cannot have two or more user accounts assigned to the same CustomerId
  • if "your" CustomerId is not in UserAccount, then you have no user account

OTHER TIPS

You can create a unique constraint to the CustomerId in UserAccount to ensure that Customer cannot have several account..

Should be doable like this

ALTER TABLE UserAccount ADD CONSTRAINT IX_Customer UNIQUE(CustomerId)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top