Oracle uses triggers to avoid repeated data insertion

Source: Internet
Author: User

Sometimes, when inserting a database, we may insert duplicate data, but do not want

Modify existingProgram, We can use triggers to avoid modifying programs and solve problems directly in the database.

Test procedure:

1. First, create a test database table.

 

Create   Table "Gzrdya". "tbtest"
("ID"
Number ( 13 , 0 ),
"Name" nvarchar2 (
200 )
)

 

2. Create a trigger.

Check whether the IDs are repeated. If there are duplicates, an error is thrown and no data is inserted.

 

Code

Create   Or   Replace   Trigger Trig_tbtest
Before
Insert   On Tbtest For Each row
Declare
V_count
Number ( 5 );
Begin
Select   Count ( * ) Into V_count From Tbtest Where ID = : New. ID;
If (V_count > 0 ) Then
Raise_application_error (
- 20000 , ' Data is duplication ' );
End   If ;
End ;

 

 

3. Test

Try to insert duplicate ID data. If you find that the data cannot be inserted, an error is thrown.

 

 

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.