Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PLSQL generate random integer

In Oracle Sql developer 11g, how do I generate a random integer and assign it to a variable? This is what I've tried so far:

S_TB := SELECT dbms_random.value(1,10) num FROM dual;

With this code I got error:

S_TB := SELECT dbms_random.value(1,10) num FROM dual
Error report -
Unknown Command

What is the proper way to solve my issue?

like image 942
Justin Avatar asked May 23 '15 21:05

Justin


People also ask

How to generate a random number in Oracle SQL?

For example, generating random numbers can be performed using the random() function.

How do I generate a random character in Oracle?

The DBMS_RANDOM package will generate random data in character, numeric or alphanumeric formats. The size and the range from which to pickup the random values can also be specified. This package is created by the script dbmsrand.


1 Answers

Variables require PL/SQL; it's not clear from your question whether your code is a proper PL/SQL block. In PL/SQL variables are populated from queries using the INTO syntax rather than the assignment syntax you're using.

declare
    txt varchar2(128);
    n pls_integer;
begin
    --  this is how to assign a literal
    txt := 'your message here';

    --  how to assign the output from a query
    SELECT dbms_random.value(1,10) num 
    into n
    FROM dual;

end;

Although, you don't need to use the query syntax. This is valid, and better practice:

declare
    n pls_integer;
begin
    n := dbms_random.value(1,10);
end; 
like image 130
APC Avatar answered Oct 13 '22 20:10

APC