سؤال

I have table calls 'Users' and there is UserID there.

I have also table calls UsersFriends that look like:

create table UsersFriends
(   
UserID int references Users(UserID),
FriendID int references Users(UserID), 
primary key(UserID,FriendID)
)

As you see, UserID and FriendID are references from Users(UserID).

I want to make sure that there is no enrty like: (1,1) because can't be friend of himself. So, I tried to make Check but isn't.. I tried to do like this:

create table UsersFriends
(   
User1ID int references Users(UserID),
FriendID int references Users(UserID) CHECK (FriendID in (select u.UserID from Users u where      
u.UserID!= User1ID)),
primary key(User1ID,FriendID)
)

But I've got error:

Msg 1046, Level 15, State 1, Line 4
Subqueries are not allowed in this context. Only scalar expressions are allowed.

Someone can help me please?

Thanks.

هل كانت مفيدة؟

المحلول

You are defining the check constraint inline and moreover subqueries are not allowed. You need to define the constraint at table level like below

create table UsersFriends
(   
UserID int references Users(UserID),
FriendID int references Users(UserID), 
primary key(UserID,FriendID),
CONSTRAINT CK_nested_friend check(UserID <> FriendID)
);

In case need a demo, see here http://sqlfiddle.com/#!3/1e405

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top