I want to design a user/role system:
The users have a name and a password and then the user can have several roles like Admin.
For this I created a schema like this:
Users:
CREATE TABLE [dbo].[Users]
(
[id] [int] NOT NULL,
[name] [nvarchar](50) NULL,
[password] [nvarchar](50) NULL,
CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED ([id] ASC)
)
Roles:
CREATE TABLE [dbo].[Roles]
(
[id] [int] NOT NULL,
[name] [nvarchar](50) NULL,
CONSTRAINT [PK_Roles] PRIMARY KEY CLUSTERED ([id] ASC)
)
user_roles:
CREATE TABLE [dbo].[User_Roles]
(
[id] [int] NOT NULL,
[User_id] [int] NOT NULL,
[Role_id] [int] NOT NULL,
CONSTRAINT [PK_User_Roles] PRIMARY KEY CLUSTERED ([id] ASC)
)
My question is: should I use foreign keys User_Roles.User_id -> User.Id
If yes why?
Not quite sure what you mean, but…
User_Rolesshould have 2 columns onlyUser_idandRole_idBoth of these form the Primary Key
User_RolesUser_idis a foreign key toUsers.idRole_idis a foreign key toRoles.idEdit: Now I understand. Yes, always use foreign keys
Also…
passwordisnvarchar(50), this implies plain text. This is bad.namevalues inUsers, how do you know which user is which?Especially if they have the same password (which will happen because we meatsacks are stupid)
Edit after comment after primary key creation…