Wow, I donโt know what to say, please go read and learn sql a bit, do not be offended, but this is one of the worst SQL I have ever seen.
SQL is a set-based language, cursors are generally bad, there are situations when they are useful, but they are quite rare. Your use of cursors is completely inappropriate here.
Your logic in the second cursor is also erroneous, as it will select any entry that includes a friend, and not just the necessary friendship.
If you want to fix this, you can try giving the second cursor a different name, but it is preferable to start over.
Set a composite PK or a unique constraint for users_friends, then you donโt have to worry about checking relationships, and then try something like this.
INSERT INTO users_friends SELECT @inUserId, users.user_id FROM users WHERE email = @inFriendEmail
Paul creasey
source share