I'm having an issue with this bit of SQL. For some reason, the value being inserted into wCount is always 1. I've tested it using values I know should evaluate to 0, but it still comes out of the procedure as 1. I've also tested the SELECT on it's own outside of the procedure, and the result is 0, using the same values. What is going wrong here?
-- Add user role to table if user does not already have that role assigned to them
CREATE PROCEDURE `new_user_role`(IN userID INT(11), IN roleID INT(11))
BEGIN
DECLARE wCount INT DEFAULT 0;
SELECT COUNT(*)
INTO wCount
FROM userrole
WHERE RoleID = roleID
AND UserID = userID;
IF wCount = 0 THEN
INSERT INTO userrole(UserID, RoleID) VALUES(userID, roleID);
END IF;
END
Here is the create table statement
CREATE TABLE `userrole` (
`URKey` bigint(20) NOT NULL AUTO_INCREMENT,
`UserID` int(11) NOT NULL,
`RoleID` int(11) NOT NULL,
PRIMARY KEY (`URKey`),
KEY `FK_UserRole_User_idx` (`UserID`),
KEY `FK_UserRole_Role_idx` (`RoleID`),
CONSTRAINT `FK_UserRole_Role` FOREIGN KEY (`RoleID`) REFERENCES `role` (`RoleID`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `FK_UserRole_User` FOREIGN KEY (`UserID`) REFERENCES `user` (`UserID`) ON DELETE CASCADE ON UPDATE CASCADE
);