0

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?

a_horse_with_no_name
  • 497,550
  • 91
  • 775
  • 843

2 Answers2

2

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,198,228
  • 53
  • 572
  • 709
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
  • 5,870
  • 9
  • 46
  • 73