Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there something like "if not exist create sequence ..." in Oracle SQL?

Tags:

For my application that uses an Oracle 8 DB, I am providing an SQL script to setup stuff like triggers, sequences etc., which can be copied and pasted into SQL*Plus. I would like the script to not stop with an error if a sequence that I am trying to create already exists. For a Trigger this can easily be done using "create or replace trigger ...", but for a sequence this does not work. I also tried ""if not exists mysequence then create sequence ..." but it did not too. Is there some alternative?

Alternatively, if this is not possible, is there a way to do a "drop sequence mysequence" without SQL*Plus aborting the script if mysequence does not exist?

like image 715
Timo Avatar asked Apr 11 '10 18:04

Timo


People also ask

How do you check if a sequence exists in Oracle?

Best Answer Although you could find the sequences in a schema using the query :" select sequence_name from user_sequences;", You should use the query "select sequence_name from all_sequences;" to find out all sequences accessible to the schema user.

How can you tell if a sequence is created in SQL?

The syntax to a view the properties of a sequence in SQL Server (Transact-SQL) is: SELECT * FROM sys. sequences WHERE name = 'sequence_name'; sequence_name.

Can we create sequence in Oracle?

However, if you want to set it to 0, you can just delete and recreate it. If you want to set it to a specific value, you can set the INCREMENT to a negative value and get the next value.

Where we Cannot use sequence in SQL?

Restrictions on Sequence Values You cannot use CURRVAL and NEXTVAL in the following constructs: A subquery in a DELETE , SELECT , or UPDATE statement. A query of a view or of a materialized view. A SELECT statement with the DISTINCT operator.


2 Answers

DECLARE
  v_dummy NUMBER;
BEGIN
  -- try to find sequence in data dictionary
  SELECT 1
  INTO v_dummy
  FROM user_sequences
  WHERE sequence_name = 'MY_SEQUENCE_NAME';

  -- if sequence found, do nothing
EXCEPTION
  WHEN no_data_found THEN
    -- sequence not found, create it
    EXECUTE IMMEDIATE 'create sequence my_sequence_name';
END;
like image 55
jva Avatar answered Sep 28 '22 03:09

jva


If you're sure the script will always run under SQL*Plus, you can bracket the CREATE SEQUENCE statements with a directive to continue on error:

WHENEVER SQLERROR CONTINUE
-- create sequences here, ignoring errors
WHENEVER SQLERROR EXIT SQL.SQLCODE

Be aware if there are other errors (permission problems, syntax failures, etc.) in the create sequence statements they will be ignored

like image 33
dpbradley Avatar answered Sep 28 '22 02:09

dpbradley