Creating an Oracle User if it doesn't already exist

匿名 (未验证) 提交于 2019-12-03 08:36:05

问题:

I am trying to create a script that will create users if they do not already exist.

CREATE USER "Kyle" PROFILE "DEFAULT" IDENTIFIED BY "password" ACCOUNT UNLOCK WHERE NOT IN  //Also tried 'WHERE NOT EXISTS' (     SELECT username FROM all_users WHERE username = 'Kyle' ) 

The following error is given:

SQL Error: ORA-00922: missing or invalid option

I was able to do this in SQL Server 2008 by using:

IF NOT EXISTS (SELECT name FROM master.sys.server_principals WHERE name = 'Kyle') BEGIN     CREATE LOGIN Kyle WITH PASSWORD = 'temppassword' MUST_CHANGE, CHECK_EXPIRATION=ON, CHECK_POLICY=ON END 

Is there a similar way in Oracle to check if a user already exists before attempting to create a new user?

回答1:

The IF NOT EXISTS syntax available in SQL Server, is not available in Oracle.

In general, Oracle scripts simply execute the CREATE statement, and if the object already exist, you'll get an error indicating that, which you can ignore. This is whaat all the standard Oracle deployment scripts do.

However, if you really want to check for existence, and only execute if object doesn't exist, thereby avoiding the error, you can code a PL/SQL block. Write a SQL that checks for user existence, and if it doesn't exist, use EXECUTE IMMEDIATE to do CREATE USER from the PL/SQL block.

An example of such a PL/SQL block might be:

declare userexist integer; begin   select count(*) into userexist from dba_users where username='SMITH';   if (userexist = 0) then     execute immediate 'create user smith identified by smith';   end if; end; / 

Hope that helps.



回答2:

You need to write a pl/sql block. See an example here

You can check if the user exists in the all_users table using some pl/sql code like:

SELECT count(*) INTO v_count_user FROM all_users WHERE username = 'Kyle' 

and then use v_count_user in an IF condition to conditionally execute the create user statement.



回答3:

From the previous answers, it is clear that if not exists is not supported in Oracle. To clarify which error(s) are thrown by Oracle when attempting to create an already existing user (and as a bonus, when attempting to drop a non existing user):

drop user foo; ORA-01918: user 'foo' does not exist  create user existing_user IDENTIFIED BY existing_user; ORA-01920: user name 'existing_user' conflicts with another user or role name 

The statements above were executed on Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!