Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you assign a sequence value to a variable?

Tags:

sql

oracle

I need to assign a sequence value to a variable for use later after the sequence value has been incremented. I've tried this but it gives an error:

variable imageID number;
select SEQ_IMAGE_ID.CURRVAL into :imageID from dual;

select * from IMAGES where IMAGE_ID = :imageID;


Error starting at line 2 in command:
select SEQ_IMAGE_ID.CURRVAL into :imageID from dual
Error report:
SQL Error: ORA-01006: bind variable does not exist
01006. 00000 -  "bind variable does not exist"

I have triple checked that the sequence name is correct, any ideas?

like image 337
Nick Brunt Avatar asked Aug 23 '12 13:08

Nick Brunt


People also ask

How do I change the sequence value in SQL Developer?

You can change the increment by clicking on the edit button right under the 'details' tab, but would then have to call nextval somewhere else before changing back. And you could drop the sequence from the 'actions' drop-down, but then you'd need to recreate it as a separate action.

What is Currval in sequence?

CURRVAL. returns the current value of a sequence. NEXTVAL. increments the sequence and returns the next value. You must qualify CURRVAL and NEXTVAL with the name of the sequence: sequence.CURRVAL sequence.NEXTVAL.


1 Answers

You seem to be doing this in SQL*Plus or SQL Developer, from the variable declaration. You need to do the assignment in a PL/SQL block, either with an explicit begin/end or with the exec call that hides that:

variable imageID number;
exec select SEQ_IMAGE_ID.CURRVAL into :imageID from dual;
select * from IMAGES where IMAGE_ID = :imageID;

If you're using 11g you don't need to select, you can just assign:

variable imageID number;
exec :image_id := SEQ_IMAGE_ID.CURRVAL;
select * from IMAGES where IMAGE_ID = :imageID;

You could also use a substitution variable:

column tmp_imageid new_value image_id;
select SEQ_IMAGE_ID.CURRVAL as tmp_imageID from dual;
select * from IMAGES where IMAGE_ID = &imageID;

Note the change from : to indicate a bind variable, to & to indicate a substitution variable.

like image 63
Alex Poole Avatar answered Sep 28 '22 08:09

Alex Poole