使用默认表空间在循环中创建Oracle用户

时间:2016-11-26 10:16:35

标签: oracle plsql oracle11g

我尝试执行此操作,但它在默认表空间中出错。我想给我创建的用户提供一个默认的表空间,但是如何?

BEGIN
  FOR USERNAME IN (SELECT studentname from students)
  LOOP
    EXECUTE IMMEDIATE 'CREATE USER ' || USERNAME.studentname  || ' IDENTIFIED BY ' || USERNAME.studentname;
    EXECUTE IMMEDIATE 'DEFAULT TABLESPACE "USERS"'; 
    EXECUTE IMMEDIATE 'TEMPORARY TABLESPACE "TEMP"';
    EXECUTE IMMEDIATE 'GRANT STUDENT TO ' || USERNAME.studentname ;                                    
  END LOOP;
END;


Error report - ORA-00900: invalid SQL statement ORA-06512: at line 5 00900. 00000 - "invalid SQL 

1 个答案:

答案 0 :(得分:1)

您需要将前三个语句合并为一个并添加适当的空格。由于您使用的是不区分大小写的标识符,因此不需要在表空间名称周围使用双引号。

BEGIN
  FOR USERNAME IN (SELECT studentname from students)
  LOOP
    EXECUTE IMMEDIATE 'CREATE USER ' || USERNAME.studentname  || ' IDENTIFIED BY ' || USERNAME.studentname ||
                      '  DEFAULT TABLESPACE USERS  
                        TEMPORARY TABLESPACE TEMP';
    EXECUTE IMMEDIATE 'GRANT UNLIMITED TABLESPACE TO ' || USERNAME.studentname;
    EXECUTE IMMEDIATE 'GRANT STUDENT TO ' || USERNAME.studentname ;                                    
  END LOOP;
END;

就个人而言,我总是使用SQL语句生成一个字符串,并将该字符串传递给EXECUTE IMMEDIATE。这样可以很容易地执行诸如记录执行的SQL语句或记录哪个语句失败等操作。这将使调试变得更加容易。