1

我对 PL/SQL 游戏还很陌生,我正在尝试编写一个简短的脚本来创建登录名并授予只读/读写权限(根据需要进行必要的授予)。但是,我遇到了变量范围问题。有人可以帮助我可能做错了什么吗?

截图如下:

DECLARE CNT INTEGER; 

BEGIN

  SELECT COUNT(*) 
    INTO CNT 
    FROM dba_users 
   WHERE username = :ParamUserName

  IF (CNT > 0) THEN
    IF (INSTR(:ParamSelectedRole, 'WRITE') = 0) THEN 
      REVOKE UNLIMITED TABLESPACE FROM :ParamUserName; 
      REVOKE READ_WRITE FROM :ParamUserName; 

      GRANT READ_ONLY TO :ParamUserName; 
    ELSE 
      GRANT UNLIMITED TABLESPACE TO :ParamUserName; 
    END IF; 
  ELSE 
    CREATE USER :ParamUserName DEFAULT TABLESPACE USERS TEMPORARY TABLESPACE TEMP IDENTIFIED BY ":ParamUserPassword" PROFILE ELEV_USER; 
    ALTER USER :ParamUserName PASSWORD EXPIRE;

    GRANT :ParamSelectedRole TO :ParamUserName; 
    GRANT CREATE SESSION TO :ParamUserName; 

    IF (INSTR(:ParamSelectedRole, 'WRITE') > 0 ) THEN
      GRANT UNLIMITED TABLESPACE TO :ParamUserName; 
    END IF; 
  END IF;
END;

我正在使用 ODP.NET 进行变量分配并使用OracleCommand.Parameters.Add()

4

1 回答 1

2

所有 DDL 语句(GRANT、REVOKE、CREATE 和 ALTER)都需要在 EXECUTE IMMEDIATE 中,例如

EXECUTE IMMEDIATE 'REVOKE UNLIMITED TABLESPACE FROM '||:ParamUserName; 

EXECUTE IMMEDIATE 'ALTER USER '||:ParamUserName||' PASSWORD EXPIRE';

实际上,我会稍微简化一下,一开始就把所有外部变量放在一个地方。

DECLARE 
   V_CNT INTEGER; 
   V_USER VARCHAR2(30);
   V_ROLE VARCHAR2(30);
BEGIN
  --
  V_USER := :ParamUserName;
  V_ROLE := :ParamSelectedRole;
  V_PWD  := :ParamUserPassword;
  --
  SELECT COUNT(*) 
    INTO V_CNT 
    FROM dba_users 
   WHERE username = v_user

  IF (CNT > 0) THEN
    IF (INSTR(v_role, 'WRITE') = 0) THEN 
      EXECUTE IMMEDIATE 'REVOKE UNLIMITED TABLESPACE FROM '||v_user; 
      EXECUTE IMMEDIATE 'REVOKE READ_WRITE FROM '||v_user; 
      EXECUTE IMMEDIATE 'GRANT READ_ONLY TO '||v_user; 
    ELSE 
      EXECUTE IMMEDIATE 'GRANT UNLIMITED TABLESPACE TO '||v_user;
    END IF; 
  ELSE 
    EXECUTE IMMEDIATE 'CREATE USER '||v_user||
                      'DEFAULT TABLESPACE USERS TEMPORARY TABLESPACE TEMP '||
                      'IDENTIFIED BY '||v_pwd||' PROFILE ELEV_USER'; 
    EXECUTE IMMEDIATE 'ALTER USER '||v_user||' PASSWORD EXPIRE;

    EXECUTE IMMEDIATE 'GRANT '||v_role||' TO '||v_user; 
    EXECUTE IMMEDIATE 'GRANT CREATE SESSION TO '||v_user; 

    IF (INSTR(v_role, 'WRITE') > 0 ) THEN
      EXECUTE IMMEDIATE 'GRANT UNLIMITED TABLESPACE TO '||v_user; 
    END IF; 
  END IF;
END;
于 2011-03-17T03:39:22.357 回答