Reputation: 4682
Does anyone know how to create a one-to-one relationship from a SQL Server database diagram?
Upvotes: 24
Views: 26034
Reputation: 1250
It's very pretty straight forward when you use the following:
ALTER TABLE [Salary]
ADD CONSTRAINT FK_Salary_Employee FOREIGN KEY([EmployeeID])
REFERENCES [Employee]([ID]);
That should do the trick!!!
Upvotes: 0
Reputation: 5783
I believe the question was specifically around how to create a one-to-one relation in SQL Server Management Studios Diagram window. I have a procedure where you can create a one-to-one relation in SQL Server Management Studio database diagram.
You're done!
Upvotes: 0
Reputation: 4843
You can easily use MSSQL Management Studio.
ie
table_user
uid(pk) username email
table_profile
pid(pk) f_name l_name user_id (fk)
then follow this,
4 Choose "Add" (From Indexes / Keys window, it will add a new name )
5 In "General section" select "Columns" and then select "user_id"
6 In "General section" set "Is Unique" as a true
7 In "Identity section" give a name for (Name) section. in this case I ll give UK_user_id_profile
8 after all those above steps, close Indexes / Keys window
9 Drag and Drop "uid" (from user table) into "user_id" (from profile table)
That is it.
The theory behind that, foreign key should be a unique .
You need to put a unique key constraint on top of the foreign key, so its restricted to one-one relationship.
That is what Azam said in his post.
[In-case, I am using MSSQL 2012]
Cheers.
Upvotes: 2
Reputation: 171
if your table is created like this,
CREATE TABLE tableName ( id INT NOT NULL IDENTITY(1,1) CONSTRAINT[PK:tableName] PRIMARY KEY(id) , fkId INT NOT NULL CONSTRAINT[FK:tableName:tableFk] FOREIGN KEY(fkId) REFERENCES tableFk(id) ) CREATE TABLE tableFk ( id INT NOT NULL IDENTITY(1,1) CONSTRAINT[PK:tableFk] PRIMARY KEY(id) )
you can alter the tableName with this code to set tableName.fkId as unique
ALTER TABLE tableName ADD UNIQUE (fkId)
Upvotes: 2
Reputation: 4393
Assuming you are using Sql Server 2008 onwards and SSMS.
Once you click O.K again for the second time, SSMS Designer will show a key to key relationship between the tables involved. This is a one-one relationship. Read as, one record in one table directly relates to another record in another table.
i.e A ResolutionsTable - 1 : 1 - Resolution Types Read as one resolution has one resolution type applied to it, i.e, case closed or case ongoing, case pending law change, case denied? Of course people have different DB design skills so what works for one may not work for another db developer. Never the less the example is clear enough to understand.
Hopefully this will help any non sql syntax savvy noobies out there like me who prefer to do build an entire database via the SQL Database Diagram feature.
Upvotes: 8
Reputation: 20670
You need to put a unique key constraint on top of the foreign key
, so its restricted to one-one relationship.
Upvotes: 43