Skip to content
Advertisement

Syntax errors while trying to use a select statement as the condition for a while loop in SQL

I have a simple loop I wrote to check if a random id is already in the table, else regenerate it:

Running the code above gives the error:

and

As far as I can tell, no error in the editor.

Advertisement

Answer

The better approach is to collect all the id’s into a PL/SQL collection, so that you only make one context switch from PL/SQL to SQL (and back). Something like this; note that I use empno from table emp in schema scott for testing, since I don’t have your table. The employee numbers are all between 7350 and 7950; I will pretend that I am looking for a number in that range that is not already assigned to an existing employee. (Similar to your attempt, if I got it right.)

The code begins by defining a local collection type, as a table of numbers (to hold the id’s), and an instance of this local collection type. Then a single select using the bulk collect into clause collects the existing id’s (employee numbers) into this collection instance, so the rest of the code is pure PL/SQL.

Also, please pay attention to what I told you in a comment: without rounding or truncating, dbms_random.value() produces non-integers in general, and that is very unlikely to be what you intended.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement