Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find if a sequence exists using PL/SQL

Tags:

oracle

plsql

I need to find using PL/SQL if a specific sequence named e.g. MY_SEQ exits. If the sequence exists then drop it and create a new, or else to just create a new sequence.

E.G. (pseudocode)

IF EXISTS(MY_SEQ) THEN
BEGIN
   DROP SEQUENCE MY_SEQ;
   CREATE SEQUENCE MY_SEQ...
END;
ELSE
BEGIN
  CREATE SEQUENCE MY_SEQ;
END;
like image 904
Nikola Stjelja Avatar asked Aug 26 '10 07:08

Nikola Stjelja


People also ask

How do I query sequence 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.

What is Currval and Nextval?

CURRVAL. returns the current value of a sequence. NEXTVAL. increments the sequence and returns the next value.

What is sequence in Plsql?

An Oracle Sequence is a database object, just like a table or view, that represents a sequence of integers that can be used by any table or view in the global database namespace. A Sequence's values can be accessed using the NEXTVAL, and CURRVAL pseudo-columns. A Sequence can be ascending or descending.

What is seq Nextval in SQL?

The Oracle NEXTVAL function is used to retrieve the next value in a sequence. The Oracle NEXTVAL function must be called before calling the CURRVAL function, or an error will be thrown. No current value exists for the sequence until the Oracle NEXVAL function has been called at least once.


1 Answers

you can check the dictionary view ALL_SEQUENCES (or USER_SEQUENCES if the executing user is the owner), for example:

BEGIN
   FOR cc IN (SELECT sequence_name as sequence_exists
                FROM all_sequences
               WHERE sequence_owner = :seq_owner
                 AND sequence_name = :seq_name) LOOP
      -- sequence exists, drop it (at most there will be *one* sequence)
      EXECUTE IMMEDIATE 'DROP SEQUENCE XXX';
   END LOOP;
   -- create sequence
   EXECUTE IMMEDIATE 'CREATE SEQUENCE XXX';
END;
like image 95
Vincent Malgrat Avatar answered Sep 22 '22 09:09

Vincent Malgrat