1

次のようなストアドプロシージャがあります。

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 を返す必要があります。

4

1 に答える 1

2

私はあなたの単純なデータを持っていませんが、私にとってはうまくいきました。そのように。

BEGIN
IF userID IS NULL THEN
    SELECT 'User ID is required.';
ELSE
        SELECT IF(COUNT(*)>0,TRUE,FALSE) AS if_stmt 
            from 
                UserRole 
            where 
                UserID = userID
                and RoleCode = 1 
                and VendorCode is null 
                and NPOCode is null;

END IF;
END$$
于 2013-08-11T18:53:03.207 に答える