Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Shaun E on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

UNIQUE CONSTRAINT 1

Status
Not open for further replies.

Luzian

Programmer
Nov 27, 2005
103
US
Code:
CREATE TABLE [UsersRoles_MAP]
(
[tab][user_id] int NOT NULL FOREIGN KEY REFERENCES [Users]([id]),
[tab][role_id] int NOT NULL FOREIGN KEY REFERENCES [Roles]([id]),
[tab][red]CONSTRAINT UNIQUE ([user_id], [role_id])[/red]
)

What is the syntax to make sure a combination of role_id and user_id is unique?

I never tried this before, and the code in red, does not work.
 
Code:
ALTER TABLE [dbo].[UsersRoles_MAP] ADD 
	CONSTRAINT [IX_SomeName] UNIQUE  NONCLUSTERED 
	(
		[user_id],
		[role_id]
	)  ON [PRIMARY] 
GO
 
Thanks. Can you explain what [tt]NONCLUSTERED[/tt] and [tt]ON [PRIMARY][/tt] does?
 
And I don't want to specify a name for the index. I'd rather use SQL Server's way of assigning names to keys than my memory.
 
To answer my own question, you just leave out "CONSTRAINT [IX_SomeName]" if you don't want to name it.
Code:
ALTER TABLE [dbo].[UsersRoles_MAP]
ADD UNIQUE
(
[tab][user_id],
[tab][role_id]
)
GO
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top