Search code examples
asp.netsqluniquerecord

Unique record in Asp.Net SQL


I asked this question previously but the answers weren't what I was looking for.

I created a table in Asp.net without using code. It contains two columns.

YourUserId and FriendUserId

This is a many to many relationship.

Heres what I want:

There can be multiple records with your name as the UserId, there can also be multiple records with FriendUserId being the same...but there cannot be multiple records with both being the same. For example:

Dave : Greg

Dave : Chris

Greg : Chris

Chris : Greg

is good

Dave : Greg

Dave : Greg

is not good.

I right clicked on the table and chose Indexes/Keys. I then put both columns in the columns section and chose to make the unique. I thought this would make them unique as a whole but individually not unique.

If you go to the Dataset, it show keys next to both columns and says that there is a constraint with both columns being checked.

Is there a way of just making sure that you are not inserting a duplicate copy of a record into the table without individual columns being unique?

I tried controling it with my sql insert statement but that did not work. This is what I tried.

INSERT INTO [FriendRequests] ([UserId], [FriendUserId]) VALUES ('"+UserId+"', '"+PossibleFriend+"') WHERE NOT EXIST (SELECT [UserId], [FriendUserId] FROM [FriendRequests])

That didn't work for some reason. Thank you for your help!


Solution

  • You should create a compound primary key to prevent duplicate rows.

    ALTER TABLE FriendRequests
    ADD CONSTRAINT pk_FriendRequests PRIMARY KEY (UserID, FriendUserID)
    

    Or select both columns in table designer and right click to set it as a key.

    To prevent self-friendship, you'd create a CHECK constraint:

    ALTER TABLE FriendRequests
    ADD CONSTRAINT ck_FriendRequests_NoSelfFriends CHECK (UserID <> FriendUserID)
    

    You can add the check constraint in the designer by right clicking anywhere in the table designer, clicking "Check constraints", clicking "add", and setting expression to UserID <> FriendUserID

    You might want to look at this question