Need to create a primary key by using sequence in a table with records.

Hello
I want to create a primary key for a table that is already having a huge number of records. Am thinking to create the primary key by using a sequence generator. Could someone tell how can I do this using SQL or PL - SQL.

Kind regards
SK

Hello

Try this...

SQL> select * from emp;

     EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
---------- ---------- --------- ---------- --------- ---------- ---------- ----------
      7369 SMITH      CLERK           7902 17-DEC-80        800                    20
      7499 ALLEN      SALESMAN        7698 20-FEB-81       1600        300         30
      7521 WARD       SALESMAN        7698 22-FEB-81       1250        500         30
      7566 JONES      MANAGER         7839 02-APR-81       2975                    20
      7654 MARTIN     SALESMAN        7698 28-SEP-81       1250       1400         30
      7698 BLAKE      MANAGER         7839 01-MAY-81       2850                    30
      7782 CLARK      MANAGER         7839 09-JUN-81       2450                    10
      7788 SCOTT      ANALYST         7566 19-APR-87       3000                    20
      7839 KING       PRESIDENT            17-NOV-81       5000                    10
      7844 TURNER     SALESMAN        7698 08-SEP-81       1500          0         30
      7876 ADAMS      CLERK           7788 23-MAY-87       1100                    20
      7900 JAMES      CLERK           7698 03-DEC-81        950                    30
      7902 FORD       ANALYST         7566 03-DEC-81       3000                    20
      7934 MILLER     CLERK           7782 23-JAN-82       1300                    10

14 rows selected.

SQL> create sequence emp_empno_seq
  2  start with 1
  3  minvalue 1
  4  maxvalue 999999999999999999999
  5  increment by 1
  6  nocache
  7  noorder
  8  nocycle;

Sequence created.

SQL>
SQL> ed
Wrote file afiedt.buf

  1  update emp
  2* set empno=emp_empno_seq.nextval
  3  /

14 rows updated.

SQL> commit;

Commit complete.

SQL> select * from emp;

     EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
---------- ---------- --------- ---------- --------- ---------- ---------- ----------
         1 SMITH      CLERK           7902 17-DEC-80        800                    20
         2 ALLEN      SALESMAN        7698 20-FEB-81       1600        300         30
         3 WARD       SALESMAN        7698 22-FEB-81       1250        500         30
         4 JONES      MANAGER         7839 02-APR-81       2975                    20
         5 MARTIN     SALESMAN        7698 28-SEP-81       1250       1400         30
         6 BLAKE      MANAGER         7839 01-MAY-81       2850                    30
         7 CLARK      MANAGER         7839 09-JUN-81       2450                    10
         8 SCOTT      ANALYST         7566 19-APR-87       3000                    20
         9 KING       PRESIDENT            17-NOV-81       5000                    10
        10 TURNER     SALESMAN        7698 08-SEP-81       1500          0         30
        11 ADAMS      CLERK           7788 23-MAY-87       1100                    20
        12 JAMES      CLERK           7698 03-DEC-81        950                    30
        13 FORD       ANALYST         7566 03-DEC-81       3000                    20
        14 MILLER     CLERK           7782 23-JAN-82       1300                    10

14 rows selected.

Thank you
Prakash P

Tags: Database

Similar Questions

  • Create the primary key on the target

    Y at - it no IKM which would create the primary key on target after having read the instructions for the source?

    Thank you
    Dinesh.

    Hi Dinesh,

    You can customize a KM to create a primary key on the target
    The target table will be created with the mention of the primary key constraint in the data target store.

    Steps: -.

    Customiuse creating target step of the table and I create $ step table.

    for example: -.

    original train target table KM walk (IKM Oracle Simple incremental update): -.

    create table< %="snpRef.getTable" ("l",="" "a",="" "targ_name")="" %="">
    (
         <%=snpRef.getTargetColList("", "[COL_NAME]\t[DEST_CRE_DT] NULL", ",\n\t", "")%>
    )

    custom STAGE: -.

    create table< %="snpRef.getTable" ("l",="" "a",="" "targ_name")="" %="">
    (
         <%=snpRef.getTargetColList("", "[COL_NAME]\t[DEST_CRE_DT] NULL", ",\n\t", "")%>

    CONSTRAINT constraint_name PRIMARY KEY (< %="snpRef.getColList" ("",="" "[column]",="" ",",="" "",="" "pk")="" %="">)
    )

    Note:- The code above described here is just a sample of reference. I did not test the syntax.

    Kind regards
    Its

  • primary key in the sequence

    Hi all

    I need to create the primary key sequence for the id of the column in the table tab1, how do I do it?

    http://www.Oracle-base.com/articles/Misc/AutoNumber.php

  • Can we create a foreign key by using built in functions?

    Hi all

    I'm in the need to create a foreign key referring to an expression of a column in another table.

    For example, I try below and I got some errors.

    CREATE TABLE TABLE_A

    (

    student_id VARCHAR2 (30),

    student_name VARCHAR2 (100),

    CONSTRAINT fk_A FOREIGN KEY (student_id) REFERENCES TABLE_B (UPPER (column_name))

    );

    Please suggest if it is possible that a foreign key could be made in an expression or not?

    2761969 wrote:

    Hi all

    I'm in the need to create a foreign key referring to an expression of a column in another table.

    For example, I try below and I got some errors.

    CREATE TABLE TABLE_A

    (

    student_id VARCHAR2 (30),

    student_name VARCHAR2 (100),

    CONSTRAINT fk_A FOREIGN KEY (student_id) REFERENCES TABLE_B (UPPER (column_name))

    );

    Please suggest if it is possible that a foreign key could be made in an expression or not?

    No - it isn't.

    You can, however, create a VIRTUAL column in the parent table, and then create a foreign key that references.

  • Problem by setting the primary key: relaxation Assigned primary key in the sequence.

    I have a table and a trigger for insert/update on the table. Trigger I get the game of the primary key of a sequence. I tested unit by inserting records in the table. It works very well. Kets primary key the next sequence number.

    I use this table as an entity in my adf application. The primary key attribute is set to "DBSequence". But when inserted I do not receive the following sequence for the primary key. Instead it is inserting the temporary number - ve that assigns the adf.

    I use JDeveloper 11 g.


    Can someone tell me what could be the problem?

    Your trigger should be something like:

    create or replace TRIGGER "SID_ASSIGN"
     before INSERT
     ON MY_TABLE
     FOR EACH ROW
    
    BEGIN
    
    if :new.SID is null or :new.SID < 0 then
       SELECT MASTER_SID_SEQUENCE.nextval into :new.SID from dual ;
    end if;
    END;
    

    You can refer to the guide of Dev of 11g for more details on this...

    Julian

  • Call a page after you have created a primary key?

    Hello

    I have a form on a table with a button create on this subject. When I click on the button CREATE and brings back me to this report which shows my new record, the primary key is created. Here, everything's fine.

    Now, I want to create a branch to a new page (after treatment), passing the value of my new primary key to this page. But it seems that this value is zero (if I look in the URL there is no value)

    For example, I need to create a new customer, then pass the primary key of my client to a new page. But it does not work... someone can help me?

    Thank you

    Mathieu

    You should take a look in your SRM process and he'll say

    Return key in point

    You must put the name of the key (primary) here like this:

    P1_PRIMARY_KEY

    If you create a new record, the process will get the primary key and set the item with this value. You can refer to this element in your conditional branch and it'll pass this value to your target page. That's essentially what Scott said in his first response.

    Denes Kubicek
    -------------------------------------------------------------------
    http://deneskubicek.blogspot.com/
    http://www.Opal-consulting.de/training
    http://Apex.Oracle.com/pls/OTN/f?p=31517:1
    -------------------------------------------------------------------

  • SQL Data Model 3.0 EA1 trying to create the primary key on OT

    Hello

    I am trying to change a primary key of a table of the object that has been reversed (imported) from an Oracle 11.2.x RDBMS and get the error message "the incomplete Index Definition. It is displayed in the window "columns transfer Index." I get to the window"properties of primary key 'by pressing the 'Properties' button on the 'table properties'-> 'Primary key'. If I try to change the expression, and then press Ok or apply buttons I get the error. With this be corrected in the production version? That we will be able to create a model in the SQL Developer Data Modeler, which generates a SQL statement similar to the following:

    ALTER TABLE x_flags
    ADD (CONSTRAINT x_flags_pk PRIMARY KEY (flags.id))

    ?

    Thank you
    Scott K

    Hi Scott,.

    I am trying to change a primary key of a table of the object that has been reversed (imported) from an Oracle 11.2.x RDBMS and get the error message "the incomplete Index Definition"... With this be corrected in the production version?

    Yes

    That we will be able to create a model in the SQL Developer Data Modeler, which generates a SQL statement similar to the following:

    ALTER TABLE x_flags
    ADD (CONSTRAINT x_flags_pk PRIMARY KEY (flags.id))

    I guess that 'flags' is the type of the object column and 'id' attribute of this type. I logged for this bug, there are however not for 3.0.

    Philippe

  • Why create a primary key on a VIEW?

    One of our developers found that you can define a primary key on a VIEW. What are the circumstances which justify the something like that?

    -= Chuck

    http://asktom.Oracle.com/pls/asktom/f?p=100:11:0:P11_QUESTION_ID:636499119911

    "
    Tom,

    I'm a little confused on the constraints on views. According to the documentation, they are not applied. Then
    What is the use for the constraints on views?

    According to the "SQL Reference": documents

    Constraints of view (the view and the column level or attribute) are declarative. It's
    Oracle does not apply to them. However, the operations on views are subject to constraints of integrity
    defined on the underlying base tables, then you can apply constraints on views through constraints
    on the base tables.

    Thanks for your time.

    Follow-up February 5, 2002-11:00 Central time zone:

    They are used for rewriting complex query with other materialized views. It's more "metadata".
    -It gives additional information from the optimizer, allows a wider range of the rewrite of the query to
    place.
    "

  • Need to create a trigger that generates multiple rows in another table

    {size: 12} Hello

    I use Oracle9i (9.2.0.4.0)

    My problem is:
    I need to create a trigger that create different in the other table lines when someone will introduce a new line in the first table.

    For this, I use the table 4:

    1. first one where you want the trigger.
    2. a second just to take information.
    3. a third to make a trip meter.
    4. the fourth is the table where I want to create new lines. {size}

    Here is a summary of these 4 tables:

    {color: blue} Table 1
    STOJOU
    Number ¿Nulo? Tipo
    STOFCY_0 NOT NULL VARCHAR2 (9)
    ITMREF_0 NOT NULL VARCHAR2 (60)
    LOT_0 NOT NULL VARCHAR2 (45)
    VCRTYP_0 NOT NULL NUMBER (3)
    VCRNUM_0 NOT NULL VARCHAR2 (45)
    VCRLIN_0 NOT NULL NUMBER (10)
    QTYSTU_0 NOT NULL NUMBER
    NUMVCR_0 NOT NULL VARCHAR2 (45) {color}

    {color: blue} Table 2
    ITMMASTER
    Number ¿Nulo? Tipo
    ITMREF_0 NOT NULL VARCHAR2 (60)
    ZCOEFI_0 NOT NULL NUMBER {color}

    {color: blue} Table 3
    ZCTUART;
    Number ¿Nulo? Tipo
    CTUART_0 NOT NULL NUMBER (10)
    CTUDATE_0 NON NULL DATE {color}

    {color: blue} Table 4
    ZUART
    Number ¿Nulo? Tipo
    ZUARTDM_0 NOT NULL VARCHAR2 (102)
    STOFCY_0 NOT NULL VARCHAR2 (9)
    STOCOU_0 NOT NULL NUMBER
    ITMREF_0 NOT NULL VARCHAR2 (60)
    LOT_0 NOT NULL VARCHAR2 (45)
    CREDAT_0 NOT NULL DATE
    QTYSTU_0 NOT NULL NUMBER
    STA_0 NOT NULL VARCHAR2 (3)
    VCRLIN_0 NOT NULL NUMBER (10)
    VCRNUM_0 NOT NULL VARCHAR2 (45)
    VCRTYP_0 NOT NULL NUMBER (3) {color}

    I do this trigger:
    CREATE OR REPLACE TRIGGER CREA_REGISTROS_TRAZA
    AFTER INSERT ON STOJOU
    FOR EACH ROW
    DECLARE
       n INTEGER;
       ct NUMBER;
       fecha_actual VARCHAR2;
       fecha_old VARCHAR2;
       codigo_dm VARCHAR2;
    BEGIN
       fecha_actual := TO_CHAR(SYSDATE, 'DD/MM/YYYY');
       -- SELECT TO_CHAR(sysdate, 'DD/MM/YYYY') INTO fecha_actual FROM DUAL;
       SELECT TRUNC((STOJOU.QTYSTU_0/ITMMASTER.ZCOEFI_0),0) INTO n FROM STOJOU INNER JOIN ITMMASTER ON STOJOU.ITMREF = ITMMASTER.ITMREF;
          FOR i IN 1 .. n
       LOOP
          SELECT CTUART_0,TO_CHAR(CTUDAT_0, 'DD/MM/YYYY') INTO ct,fecha_old FROM ZCTUART;
          IF fecha_old <> fecha_actual THEN
            ct := 0;
          END IF;
          ct := ct + 1;
          INSERT INTO ZCTUART
            (CTUART_0,CTUDAT_0)
          VALUES
            (ct,SYSDATE);
          codigo_dm := SUBSTR('000000000000000000000',1,20 - LENGHT(NEW.ITMREF_0)) || NEW.ITMREF_0 || SUBSTR('0000000000',1,10 - LENGHT(NEW.LOT)) || NEW.LOT || SUBSTR('0000',1,4 - LENGHT(ct)) || ct;
          INSERT INTO ZUART
            (ZUARTDM_0,ITMREF_0,CREDAT_0,STA_0,QTYSTU_0,LOT_0,STOFCY_0,VCRLIN_0,VCRNUM_0,VCRTYP_0)
          VALUES
            (codigo_dm,NEW.ITMREF_0,SYSDATE,0,NEW.QTYSTU_0,NEW.LOT_0,NEW.STOFCY_0,NEW.VCRLIN_0,NEW.VCRNUM_0,NEW.VCRTYP_0);
       END LOOP;
    END CREA_REGISTROS_TRAZA;
    /
    {size: 12} And the error message I get States is just:
    "The trigger was created with compilation errors."
    Thanks for the help {size}

    You must prefix your NEW "columns" with a colon, as in: NEW.

  • The masks need images to match the size of the sequence or they work with a different scale.

    Now, it is normal to film 4 k for 1080 chronologies, speedgrade will be able to use masks, not taking into account the difference between chronology and images of size?

    I guess, you take a 4K and using the first Panel, applying the motion effect in the position and scale to fit in a sequence of 1080 and then directly link Speedgrade, apply a mask and missing his target.

    Work is about to lower the motion effect in the first Panel. But you can't reduce the motion effect, you must apply the effect of transformation.

    I mean by this is:

    -do not apply the motion effect

    -apply the transformation effect (it has the same position and scale under the effect of movement and can be rearranged because of first z-order)

    This effect is found in the effects of first under Video Effects Panel-deformation-transform

    and apply your Speedgrade Lumetri above the kind your masks are lining up for target.

  • Another syntax for creating primary key


    Hello


    I have a question about the right way to create primary keys.
    Earlier, we were on Oracle 9i and we have upgraded to Oracle 10 g. The question is when creating primary key is allowed to create the unique index and then to create the primary key constraint? or directly create the first key is better? or are there ways to both the same?


    for example:
    one way:


    SQL & gt; CONN u2/u2@db1
    Connected.
    SQL & gt; create table a (a1, b1 varchar2 number (2), the date c1);


    Table created.


    SQL & gt; create an index on a (a1) tablespace unique pk_a t1;


    The index is created.



    SQL & gt; ALTER table a Add (constraint primary key (a1) using index pk_a);


    Modified table.
    Another way:
    SQL & gt; CONN u1/u1@db1
    Connected.
    SQL & gt; create table a (a1, b1 varchar2 number (2), the date c1)
    2.


    Table created.


    SQL & gt;
    SQL & gt; ALTER table a Add (constraint primary key (a1) using index tablespace t1 pk_a)
    2.


    Modified table.
    Which of the two approach is better? or are they the same?


    Thank you
    Cedric

    Oracle will attempt to create the index to apply the constraint. Of course, it is certainly possible that the creation of the index will fail, but you would be just to move the point of failure of the CREATE INDEX statement to the ALTER TABLE statement, assuming that everything else is equal (that is, you create the index in the same tablespace, quotas and tablespace sizes are the same, permissions are not changed, etc.)

    It may be preferable in some contexts to create a non-unique index before the creation of the constraint and instruct Oracle to use the non-unique index to apply the constraint. If you decide in the future to make the primary key constraint can be delayed, for example, have a non-unique index allows you to make this change without having to (implicitly), drop and re-create the index. A separate CREATE INDEX statement also influences when you go to remove a constraint / index. If the index was created before the constraint, you can remove the constraint without affecting the index. If the index was created after the constraint, deleting the constraint implicitly removes the index. Normally, particularly with OLTP applications, this doesn't buy you much. Sometimes, however, there are ETL process benefiting from such things.

    Justin

  • Automatically fill the primary key

    We have Oracle database 10g. I've added a primary key column to my deo_language_resources_t of table with the following logic:

    -- 1. create sequences
    create sequences eod_lr_seq
    Start increment by 10 by 5
    MinValue 10 nomaxvalue
    NoCache;

    -- 2. Create the primary key column
    ALTER table deo_language_resources_t
    ADD NUMBER RESOURCE_ID;

    -- 3. Fill the pk
    Update deo_language_resources_t
    Set id_ressource = eod_lr_seq.nextval
    where id_ressource is null;

    -- 3. Create the primary key constraint
    ALTER table deo_language_resources_t
    Add constraint resource_id_pk key (resource_id) primary;

    insert into deo_language_resources_t
    (first_name, last_name, id_ressource)
    values ('John', 'Doe', eod_lr_seq.nextval);

    The last INSERT statement successfully a line inserted into the table and populated by id_ressource with the next number in the sequence eod_lr_seq. Ok.

    Is it possible to set a constraint on deo_language_resource_t so that when I INSERT a line the id_ressource is automatically set to eod_lr_seq.nextval? It is possible to define a trigger and resembling the logic of the trigger? The insert statement would be like:

    INSERT INTO deo_language_resources_t (first_name, last_name) VALUES ('John', 'Doe');
    create trigger deo_language_resources_trigger
    before insert on deo_language_resources_t
    for each row
    begin
    select eod_lr_seq.nextval into :resource_id from dual;
    end;
    
  • creating a unique index of instaed of using the primary key index

    Hello

    I heard in a debate sometimes it is better to create a unique index on a column and use it instead of using the primary key index in oracle. I did not understand what that the reason propely.

    Can someone please help me in this topic if it is valid.

    Thanks in advance

    On the surface, which does not seem reasonable... Volume of the DML is irrelevent to determine which column is the primary key for a table.

    My wild speculation a bit at a reasonable time could someone do...

    If you use synthetic primary keys (i.e. the keys generated by sequence) and that your tables are subject to large volumes of inserts such as there is a danger that the block "to the right" will be the source of contention block and worry not about analysis of beach on the column, you can create a reverse on this column (unique or non-unique) key index before creating the primary key constraint and to indicate Oracle to use this existing index to respect the primary key constraint.

    Obviously, however, this involves a lot of assumptions to arrive at a reasonable point. There may well be another set of assumptions that could also lead to a valid argument. Or it could be a myth that someone has heard and just repeats.

    Justin

  • need to based on the primary key of different table 2 foreign key constraint

    I'm using Oracle 11.2.0.3.

    I have 2 table invl with invl_pk as primary key and org with org_pk as the primary key.

    In the third table entity_list, I have entity_pk that can be indvl_pk or org_pk.   How can I create this constraint?

    Thanks for your time.

    Hello

    Assuming that your model is correct, then what you describe is a normal type of ER modeling construction known as a relationship of the CRA. It is characterized by an entity with two or more links that are mutually exclusive to each other (XOR). A typical example may be where a person entity and an entity of the Organization relate both to a bank account entity, but a bank account can only be used by a person or an organization in a mutually exclusive way. In order to serve this on a diagram, an arc is drawn between effective relationships on the side of the child, where the name of a relationship of the CRA.

    Google will be of multiple examples and explanations.

    In a perspective of physical databases, this can be implemented in general in two different ways.

    1. assuming that all parents in the relationship of the CRA have identical PK, that is to say, a number that is generated, the child may have a FK of the same type and an entity of type column that defines what entity the FK is. The advantage of this is that it is a bit more compact and is expandable without schema changes if you want to add more relationships. The downside of this is that the CF cannot be defined at the database level and will build on the code to be executed or both in the application and the database as a trigger.

    2. regardless of types PK for parent entities, the child has a separate optional FK appropriate for each relationship in the arc. Each FK is defined at the database level while maintaining the exclusivity of relationships, a constraint is defined on the table that prevents several FK being filled for a given instance. This can be a little messier that there must be a (column/s) FK for each relationship in the arc, but the relationship may be limited to the level of the object database with the help of FK constraints and a check constraint. This could also be considered to be more technically correct implementation.

    Hope this helps

    André

  • How to specify the tablespace for a India primary key in create table statement

    How to specify the storage space for a primary key index in a create table statement?
    Does the following statement is true?
    CREATE TABLE 'GPS'||TO_CHAR(SYSDATE+1,'YYYYMMDD')
                ("ID" NUMBER(10,0) NOT NULL ENABLE, 
                "IP_ADDRESS" VARCHAR2(32 BYTE), 
                "EQUIPMENT_ID" VARCHAR2(32 BYTE), 
                "PACKET_DT" DATE, 
                "PACKET" VARCHAR2(255 BYTE), 
                "PACKET_FORMAT" VARCHAR2(32 BYTE), 
                "SAVED_TIME" DATE DEFAULT CURRENT_TIMESTAMP, 
                 CONSTRAINT "UDP_LOG_PK" PRIMARY KEY ("ID") TABLESPACE "INDEX_DATA"
                 )            
                 TABLESPACE "SBM_DATA";   
    Thank you

    Published by: qkc November 9, 2009 13:42

    As orafad noted, you can use the documentation using ESCALATION clause, i.e.

    SQL> ed
    Wrote file afiedt.buf
    
      1  CREATE TABLE GPS
      2              ("ID" NUMBER(10,0) NOT NULL ENABLE,
      3              "IP_ADDRESS" VARCHAR2(32 BYTE),
      4              "EQUIPMENT_ID" VARCHAR2(32 BYTE),
      5              "PACKET_DT" DATE,
      6              "PACKET" VARCHAR2(255 BYTE),
      7              "PACKET_FORMAT" VARCHAR2(32 BYTE),
      8              "SAVED_TIME" DATE DEFAULT CURRENT_TIMESTAMP,
      9               CONSTRAINT "UDP_LOG_PK" PRIMARY KEY ("ID") USING INDEX TABLESP
    ACE "USERS"
     10               )
     11*              TABLESPACE "USERS"
    SQL> /
    
    Table created.
    

    Justin

Maybe you are looking for

  • quick response of iOS for whatsapp works not when the alphanumeric password has been on iPhones

    Hello My question was, I was getting keyboard white with no key, just by doing a quick response to whatsapp messages, while the phone is locked and if the phone has been unlocked, it works fine. After a quick search, I found that in this case, on all

  • How do you create a pulse train finished using a FP-CTR-502?

    Recently, I replaced my FP-PG-522 module with a module FP-CTR-502, to achieve higher output frequencies (FP-PG-522 freq to maximum output is 5 kHz, while the FP-CTR-502 output max freq is 16 kHz). I need to be able to generate a pulse train finished.

  • Explorer crashes when I access an .avi file and must be restarted

    When I try to access an .avi file, Explorer Windows stops working and "dumprep.exe" begins, using 50% of the capacity of the processor. Then, I need to delete the instance of dumprep with undesirable effects. I can open the .avi files to read by VLC,

  • X 60 digitizer pen is stuck in x 230 slot tablet

    I can not get my digitaliseur pen of its notch.  I know that I need to push to get him out.  Its done this before, but I was able to get a precision screwdriver bit small but he can't get out.  I have to send it back to the factory?  I also noticed t

  • WebEx call for the stand-alone device SX20

    My client got an autonomous telepresence SX20 system. It communicates with other systems of telepresence on the internet using the public IP address. They ask to have WebEx users dial in their system. Is this possible with the current configuration?