Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an Oracle User if it doesn't already exist

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?

like image 720
Kyle Williamson Avatar asked Jun 08 '15 13:06

Kyle Williamson


People also ask

How do you create a table only if it does not exist in Oracle?

You can do it using PL/SQL Block. Check for table name in user_tables and if table does not exists then create it using Dynamic Query.

How do you check if a user exists in Oracle?

You can find all users created in Oracle by running a query from a command prompt. The user information is stored in various system tables - ALL_USERS and DBA_USERS, depending on what user information you wish to retrieve.


1 Answers

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 what 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;
/
like image 180
Mark J. Bobak Avatar answered Nov 08 '22 23:11

Mark J. Bobak