次のようなストアドプロシージャがあります。
delimiter //
create procedure UserRole_IsUserAdmin(userID int)
begin
if userID is null then
select 'User ID is required.';
else
if (
select
count(UserRoleCode)
from
UserRole
where
UserID = userID
and RoleCode = 1
and VendorCode is null
and NPOCode is null
) > 0 then
select true;
else
select false;
end if;
end if;
end;
//
if ステートメントのサブクエリは、場合によっては 0 を返し (たとえば、userID が 5 の場合)、場合によっては 1 を返します (たとえば、userID が 1 の場合)。問題は、ストアド プロシージャが常に true を選択することです。原因がわからず、頭がおかしくなりそうです。if ステートメントで何か間違ったことをしているのか、それとも何なのかわかりません。
プロシージャを呼び出すコード:
call UserRole_IsUserAdmin(5);
/*Should return false*/
call UserRole_IsUserAdmin(1);
/*Should return true*/
要求どおり、テーブルのデータは次のとおりです
UserID はユーザーの FK ID、RoleCode はユーザーが属するロールの FK ID です。UserRoleCode は、自動インクリメントされた PK です。ncode と vcode が null で、rolecode が 1 のレコードがある場合、プロシージャは true を返す必要があります。