Orcle creating a self-increment column

Source: Internet
Author: User

Just with Orcle, the team leader let me design a table, the results of the design after the Plsql design the primary key ID, because if not self-increment column, you have to use composite primary key, so you want to use the ID of the self-increment column to represent. But he was a little bit different from SQL Server, and he didn't add it up again. So I looked it up online, two ways.

Method 1: Trigger

First create a test table T_demo

CREATE TABLE T_demo (     ID number  primary key,     username varchar2 (20))

First step: Create Squence

Create sequence Demo_seq increment by 1   -Increase to 1start with 1      -starting from 1 MinValue 1     maxvalue 9999999999999-Maximum Noca Che        --no need to cache order;      Sort

Step Two: Create a before insert trigger that is based on the table and use the trigger to create the sequence that loves you.

Create or replace trigger Userlogin_trigger before insert on usertestfor each row begin       Select   test_seq.nextval< C11/>into:new.id from Sys.dual; End

Step three: Test

Test, insert a record to see if there is any self-increment.

Method Two

Implemented directly with SQL statements and dequence.

The first step: Create sequence ' as aboveStep Two: SQL statements

Insert into T_demo (id,username) VALUES (Test_seq.nextval, Menghaibin)

Summary

Personally think the second method is good, note if in the future to maintain, or the second kind of modification of the convenience, and if the use of triggers, then the database changes will be bound by the application of triggers.


Orcle creating a self-increment column

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.