Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 One to One Relationship

Author  Topic 

shapper
Constraint Violating Yak Guru

450 Posts

Posted - 2011-07-07 : 12:24:24
Hello,

I need to create a One to One relationship.
The two tables are Users and Profiles:

create table dbo.Users
(
Id int identity not null
constraint Users_Id_PK primary key clustered (Id),
Username nvarchar (40) not null
);
create table dbo.Profiles
(
Id int not null
constraint Profiles_UserId_PK primary key clustered (UserId),
[Name] nvarchar (80) not null
);

alter table dbo.Profiles
add constraint Profiles_UserId_FK foreign key (Id) references Users (Id) on delete cascade on update cascade;


If I am not wrong this is a One to Many relationship ...

I am trying to split Users into 2 tables: Users and Profiles.

What is the correct way to have a One to One relationship?

Thank You,

Miguel

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2011-07-07 : 12:39:14
The combination of the primary key on Profiles table (which enforces a uniqueness constraint) together with the foreign key constraint will ensure that it is a (one)->(zero-one) relationship.

If I had to implement this, I would do it the way you have done it, although, I am paranoid when it comes to deleting stuff, so I would not use the cascade delete. But that is my personal idiosyncrasy.
Go to Top of Page
   

- Advertisement -