1

I'm trying to create a sql table in net frame work in VS that has room and user id ,but I want that only one of each combination can exist in the table:

Want:
room --- user id
1           2
1           3
3           2
2           1
1           1
3           1
 
Dont want:
room --- user id
1           2
1           2

how can I make it so that only unique combination can be entered?

RatLord122
  • 11
  • 2

2 Answers2

3

You can enforce uniqueness using a unique constraint or index:

create unique index unq_t_room_userid on t(room, user_id);

or:

alter table t add constraint unq_t_room_userid
    unique (room, user_id);
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
1

Looks like you want Room, UserId to be the PRIMARY KEY on that table.

CREATE TABLE Occupancy
(
    RoomId INT NOT NULL
    ,UserId INT NOT NULL
    ,CONSTRAINT PK_Occupancy PRIMARY KEY CLUSTERED (RoomId,UserId)
)

When you try to insert a duplicate value:

INSERT dbo.Occupancy (RoomId,UserId)
VALUES
(1,1)
,(1,2)
,(1,1)
GO

You will get a message like this:

Violation of PRIMARY KEY constraint 'PK_Occupancy'. Cannot insert duplicate key in object 'dbo.Occupancy'. The duplicate key value is (1, 1).

Metaphor
  • 6,157
  • 10
  • 54
  • 77