How Does Oracle Randomly Read values from a specific combination?

Source: Internet
Author: User

How Does Oracle Randomly Read values from a specific combination?

Here, we will use the DBMS_RANDOM package and the case when statement as follows:

1. Use the DBMS_RANDOM.RANDOM function to randomly generate a value and then modulo the value. If we want to randomly read 10 elements, we need to modulo 10.

2. Associate the modulo value with the element using the case when statement.

For example, I have a combination of five elements: "Beijing", "Shanghai", "Guangzhou", "Shenzhen", and "Wuhan, you want to randomly read values from these five elements to fill a field in the table.

First, create a test table.

SQL> create table test (loc varchar2 (2 char ));

Table created.

Construct an SQL statement that can randomly read Elements

 

Select case mod (abs (dbms_random.random), 5)
When 1 then 'beijing'
When 2 then 'shanghai'
When 3 then 'guangzhou'
When 4 then 'shenzhen'
Else 'wuhan 'end "LOC"
From dual;

 

Fill in the loc field of the test table in large batches

 

Begin
For I in 1 .. 10 loop
Insert into test values (case mod (abs (dbms_random.random), 5)
When 1 then 'beijing'
When 2 then 'shanghai'
When 3 then 'guangzhou'
When 4 then 'shenzhen'
Else 'wuhan 'end );
End loop;
End;

 

The final result is as follows:

 

SQL> select * from test;

LOC
--------
Wuhan
Guangzhou
Shanghai
Beijing
Shanghai
Wuhan
Beijing
Shanghai
Wuhan
Shenzhen

10 rows selected.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.