How to add primary key for table with existing data?

The table is occupied data already. There was no primary key before, so for every column, there are some duplicate values.
I want to add a new column, which should be of the datatype integer, and can automatically increment, starting from 001. I tried this in Oracle SQL Developer, but it says "ORA-01758: table must be empty to add mandatory (NOT NULL) column". How can I do it? Thanks!

Hello, don't call the column ID, that could be an ID relating to anything. Perhaps be a little more specific like emp_id .
Then to update it:
UPDATE Employee emp
  SET emp_id = (
  SELECT row_num
    FROM (
  SELECT ROWID,
             ROW_NUMBER() OVER (ORDER BY ROWID) row_num
    FROM Employee emp2) emp2
  WHERE emp.ROWID = emp2.ROWID);That will assign a new EMP_ID for each, beginning at 1.
Then:
ALTER TABLE Employee MODIFY emp_id NOT NULL;
ALTER TABLE Employee ADD CONSTRAINT EMP_PK PRIMARY KEY (EMP_ID);Then create a sequence for future population of the Employee table:
CREATE SEQUENCE emp_seq START WITH <maximum value of emp_id + 1>;

Similar Messages

  • How add primary key constraint to already existing table with data

    I want apply primary key constraint to already existing table with data
    is there any command or way to do

    Alternatively, assuming you want to ensure uniqueness in your primary key column you can do this:
    alter table <table name> add constraint <cons name> primary key (col1,col2) exceptions into <exception_table>
    If the altter table statement fails this will populate the EXCEPTIONS table with the rows that contain duplicate values for (col1,col2).
    You will need to run (or get a DBA to run) a script called UTLEXCPT.SQL (which will be in the $ORACLE_HOME/rdbms/admin directory) if you don't already have an EXCEPTIONS table.
    Cheers, APC

  • How to find Primary Key for a particular SAP Databse Table?

    Hi Guys,
                  How to find Primary Key and foreign key  for Particular SAP Databse table ?for Ex : EKKO , EKPO , EKKN , EKBE , EKBEH  , EKET and EKETH.
    Thanks,
    Srinivas.

    Use transaction SE11 to display the table. Put the cursor on the field you want to display the check table and click 'Foreign key' push button (a key with an bottom point arrow), then it will show the check table of the foreign of a field.
    Or by just simple double click on the field, a pop-up window of all the attribute (including the foreign key and the check table if exists) will show too.
    <i><b>Please reward point for helpful answer.</b></i>
    Minami

  • Primary key for table

    I have a table Gr_order which was populated ages ago and now it need to be populated
    with some more look up data.
    "Orderid" is primary key for the table but question is how do I insert "orderid" in insert statement in procedure. I could not find any sequence name. There are 1230
    records which need to be inserted.
    Desc Gr_order
    Orderid  Number Primary key
    Desc     Varchar2
    INSERT INTO gr_order (orderid,desc) 
    VALUES (???, upper(each_pom.desc);Thanks
    sandy

    You find the code that inserts into the table and see if it uses the sequence ;-) . A sequence is not "attached" to a particular table - it is up to the inserting statement to decide if a sequence is to be used.
    You might want to check if the table has a trigger - some developers like to emulate MS-sql server behaviour by having a trigger on the table that selects from a sequence. If it has such a trigger, then you just do your inserts without specifying order_id. But if the table does not have such a trigger, then you cannot know if the table was originally populated using a sequence or not (unless you can find the insert statements somewhere.)

  • How to genarate Primary Key for each record in XI  Mapping

    Hi,
    I need to genarate primary key for each record in the paylod in mapping..
    Eg: if i have a 10 reacords i need to have a primary key for each record..starting with the
    Record      Primary key
    First            001
    Secound      002
    Tenth         010
    If i need to write any user defined funtion... can any one provide the code for it.
    Thanks
    Amaresh

    Hi Bavesh,
    I will explain with the example:
    XML:
    <Record 1>
    <Primary key>
    <value1>
    <value2>
    </Record 1>
    <Record 2>
    <Primary Key>
    </Record 2>
    like above i will be getting n number of recored and in each record i need  to genarate primary key in XI.and the key sould be in sequence...
    like for the first record 1 secound 2 like that primary key should add to the privous Primary key.
    and this is for each payload.
    Thanks
    Amaresh

  • Database Copy can't copy primary key for tables

    When I use Tools->Database Copy Wizard to copy my existing schema (for example: azteca_KSMMS) to a brand new schema (azteca), I find the primary key for some of the tables can't be copied, also the views seem not valid under the new schema (azteca). Please give me your comments about that. Thanks for your help.
    Kevin

    For example I have a table called workorder, it has a primary key with name (CW_PKEY_519, on WORKORDERID column) from the source schema (azteca_KSMMS). After I database copy to new schema azteca, the primary key lost. The data of workorder and other indexes have been copied to azteca schema.
    Kevin

  • How to set primary key for a date column

    hello experts .,
    i need to set primary key for a column consists of the datatype date. how to solve this..?

    1008318 wrote:
    its my personal need..then it is a very bad personal need. DATE is not an appropriate type to be using for a primary key, as it cannot be guaranteed to be unique, especially when inserting multiple rows at once.
    You would be better working to business needs and implementing correct technical solutions to those needs, than to just do things based on your personal needs.

  • How can we export the Primary key values (along with other data) from an Advantage database?

    One of our customers is moving from our application (which uses Advantage Database Server) to another application (which uses other database technology). They have asked us to help export their data, so that they can migrate it to another database system. So far, we have used the Advantage Data Architect (ARC32) "Export Table Structures as Code" functionality to generate SQL. We used the "Include existing data" option. The SQL contains the necessary code to recreate the tables and indexes. The customer's IT staff will alter the SQL statements as necessary for their new system.
    However, there is an issue with the Primary Keys in these table. The resulting INSERT statements use AutoInc as the type for the Primary Key in each Table. These INSERT statements contains "DEFAULT" for the value of each of these AutoInc fields. The customer would like to output an integer value for each of these Primary Key values in order to maintain referential integrity in their new system.
    So far, I have not found any feature of ARC32 that allows us to export the Primary Key values. We had been using an older version of ARC32, since our application does not use the latest version of ADS. I did download the latest version of ARC32 (11.10), but it does not appear to include any new functionality that would facilitate doing this sort of export.
    Can somebody tell me if there is such a feature in ARC32?
    Or, is there is another Advantage tool to facilitate what we are trying to accomplish?
    If there are no Advantage tools to provide such functionality, what else would you suggest?

    George,
      It sounds like the approach you are using is the correct one. This seems to be the cleanest solution to me especially since the customer is able to modify the generated SQL statements for their new system.
      In order to preserve the AutoInc values I would recommend altering the table and changing the field datatype from AutoInc to Integer. Then export the table as code which will export the actual values. After the tables have been created on the new system they can change the field datatype back to an AutoInc type if necessary.
    Regards,
    Chris Franz

  • How to add License Key For Integration Tool kit For SAP in Linux Server

    Dear Experts,
    We are Using BO XI R3.1 SP3 Enterprise Version ,Integration Tool Kit For SAP,Live Office.
    The Server is Linux Server.
    But while generating reports in Infoview it is giving error like ""_check that you are licensed to access SAP Data Source_".
    So we came to know that license Key might Expire for Integraton Tool Kit For SAP in Bo Server.
    So can you tell me how to add the license key For BO XI R3.1 SP3 Integration Tool Kit For SAP in Linux Server.
    Thanks & Regards,
    Venkat

    On Unix / Linux you should be able to leverage the response from Raphael and change:
    Location=%BOBJDIR%/bobje/data/.bobj/registry/software/business objects/suite 11.5/sap/keycode/.registry
    For more information verify the below link
    [How do you update the SAP Integration Kit license?;
    Regrads
    Pardhu

  • Identifying Primary Keys for table(s) which have no natural PK

    Hello,
    At my organization, a person used the loader to bring in 4 tables which have no natural PK's. The user is using BI Studio to demo to upper management. He wants to be able to get down to a single row returned, but the table(s) don't appear to have anything unique, and the data pulled from the warehouse has no timestamps, and only dates. Since there can be multiple occurrences of case names, supervisor names, worker names, case numbers, dates, etc. I have no idea how to get anything for sure down to a unique single row returned and this table has no other table in relation to it:
    Name Null Type
    APPROVAL_PERIOD VARCHAR2(50)
    PAGE_NUMBER VARCHAR2(50)
    SERVICING_AGENCY VARCHAR2(50)
    ELIGIBILITY_OVERRIDES_1 VARCHAR2(50)
    SERVICE_AUTH_OVERRIDES_1 VARCHAR2(50)
    SUPERVISOR VARCHAR2(50)
    ELIGIBILITY_OVERRIDES_2 VARCHAR2(50)
    SERVICE_AUTH_OVERRIDES_2 VARCHAR2(50)
    WORKER VARCHAR2(50)
    ELIGIBILITY_OVERRIDES_3 VARCHAR2(50)
    SERVICE_AUTH_OVERRIDES_3 VARCHAR2(50)
    TYPE_OF_OVERRIDE VARCHAR2(50)
    CASE_NUMBER VARCHAR2(50)
    CASE_NAME VARCHAR2(50)
    CC_PROGRAM VARCHAR2(50)
    PERIOD_BEGIN DATE
    OVERRIDE_REASON VARCHAR2(50)
    OVERRIDE_VERSION VARCHAR2(2)
    APPROVED_DATE DATE
    If anyone has some advice on how to proceed with this data I would appreciate it.

    Data model normalization is usually different for data warehouses.
    Data often is denormalized purposely.
    To get "unique" rows you have to aggregate data one or another way.
    Work with OLAP/BI is oriented rather on aggregations of facts by dimensions, versus looking to individual rows in fact table.
    Aggregations are usually done by BI Studio automatically when user slices and dices, a fact column will be either summarized, or max'ed or aggregated otherwise.
    Getting down "to the row" may make sense when user wants to go (drill through) to original data that came from OLTP database.
    Usually it is required for investigations or like that.
    Normally OLAP/BI applications do no go that deep and manipulate aggregated data on more high level.
    He wants to be able to get down to a single row returnedWhat is a reason for that? What will change if he will see that same worker had multiple interactions for a case for one day?
    Worker  Case       Date
    Joe Doe SC12345 2013-02-07
    Joe Doe SC12345 2013-02-07
    Joe Doe SC12345 2013-02-07
    Joe Doe SC12345 2013-02-07instead of normally aggregated result
    Worker  Case       Date           Count
    Joe Doe SC12345 2013-02-07  4Edited by: Mark Malakanov (user11181920) on Feb 7, 2013 12:22 PM
    If user still want to drill through, a drill through query needs to be specified and send to OLTP database where this data was originated from.
    For above it should be like:
    select w.WorkerName, c.Case#, i.Timestamp, ... other details
    from Workers@OLTP w
    join Cases@OLTP c on c.worker_id=w.worker_id
    join Interactions@OLTP i on i.case#=c.case#
    where w.WorkerName='Joe Doe' and c.Case#='SC12345'
    and TRUNC(i.Timestamp)=TO_DATE('2013-02-07');Edited by: Mark Malakanov (user11181920) on Feb 7, 2013 12:22 PM
    Edited by: Mark Malakanov (user11181920) on Feb 7, 2013 12:35 PM

  • How to create manual key for AES with 256 key size

    we are just finding Different Approch for secure Key Genration and Store.
    For security purpose which way would be secure to store key in database and retrive that key.
    And can u tell me how to create secure maual key.
    Database user has access they should not able to find the what key we are using .
    Anybody has idea.

    1) Use 'keytool' with option -genseckey
    2) Use SecureRandom and store in a Java Keystore.
    3) Use a Secure Random with something like http://www.strongkey.org/
    4) Use hardware encryption such as produced by nCipher and others.
    There are many other approaches and I would suggest that you bring in an expert to advise you.

  • How to add a second database along with existing two node RAC environment

    Hi,
    I was wondering if anyone can help me with this.
    My Environment:
    1. Two node RAC Cluster database (11.2.0.2) with ASM running perfectly (Oracle Sid = test-1)
    2. I have installed a second single instance db on node 2 (Oracle Sid = test-2) with NTFS file system for datafiles
    3. Database is up and running, but I am not able to connect it from any client.
    4. I am getting ORA-12514:  TNS:listener does not currently know of service requested in connect descriptor
    5. Database (test2) is registered with grid LISTENER
    5. TNSPING from client machine response is ok
    Am I missing something here, happy to provide more info if requested.
    Thanks,
    PS

    C:\Users\root.test_prod>lsnrctl
    LSNRCTL for 64-bit Windows: Version 11.2.0.2.0 - Production on 23-FEB-2012 11:58:05
    Copyright (c) 1991, 2010, Oracle. All rights reserved.
    Welcome to LSNRCTL, type "help" for information.
    LSNRCTL> status
    Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=LISTENER)))
    STATUS of the LISTENER
    Alias LISTENER
    Version TNSLSNR for 64-bit Windows: Version 11.2.0.2.0 - Production
    Start Date 18-FEB-2012 19:51:47
    Uptime 4 days 16 hr. 6 min. 24 sec
    Trace Level off
    Security ON: Local OS Authentication
    SNMP OFF
    Listener Parameter File C:\app\11.2.0\grid\network\admin\listener.ora
    Listener Log File C:\app\11.2.0\grid\log\diag\tnslsnr\IRIS11G-DB-2\listener\alert\log.xml
    Listening Endpoints Summary...
    (DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(PIPENAME=\\.\pipe\LISTENERipc)))
    (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=10.30.0.202)(PORT=1520)))
    (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=10.30.0.215)(PORT=1520)))
    Services Summary...
    Service "+ASM" has 1 instance(s).
    Instance "+asm2", status READY, has 1 handler(s) for this service...
    Service "test-11gRAC.test_prod.internal" has 1 instance(s).
    Instance "test-11gr2", status READY, has 1 handler(s) for this service...
    Service "test-11gRXDB.test_prod.internal" has 1 instance(s).
    Instance "test-11gr2", status READY, has 1 handler(s) for this service...
    Service "irisapps.test_prod.internal" has 1 instance(s).
    Instance "test-11gr2", status READY, has 1 handler(s) for this service...
    Service "test-2" has 1 instance(s).
    Instance "test-2", status READY, has 1 handler(s) for this service...
    Service "test-2XDB" has 1 instance(s).
    Instance "test-2", status READY, has 1 handler(s) for this service...
    The command completed successfully
    LSNRCTL> service
    Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=LISTENER)))
    Services Summary...
    Service "+ASM" has 1 instance(s).
    Instance "+asm2", status READY, has 1 handler(s) for this service...
    Handler(s):
    "DEDICATED" established:1322 refused:0 state:ready
    LOCAL SERVER
    Service "test-11gRAC.test_prod.internal" has 1 instance(s).
    Instance "test-11gr2", status READY, has 1 handler(s) for this service...
    Handler(s):
    "DEDICATED" established:1829 refused:0 state:ready
    LOCAL SERVER
    Service "test-11gRXDB.test_prod.internal" has 1 instance(s).
    Instance "test-11gr2", status READY, has 1 handler(s) for this service...
    Handler(s):
    "D000" established:0 refused:0 current:0 max:1022 state:ready
    DISPATCHER <machine: IRIS11G-DB-2, pid: 4496>
    (ADDRESS=(PROTOCOL=tcp)(HOST=IRIS11G-DB-2.test_prod.internal)(PORT=57695))
    Service "irisapps.test_prod.internal" has 1 instance(s).
    Instance "test-11gr2", status READY, has 1 handler(s) for this service...
    Handler(s):
    "DEDICATED" established:1829 refused:0 state:ready
    LOCAL SERVER
    Service "test-2" has 1 instance(s).
    Instance "test-2", status READY, has 1 handler(s) for this service...
    Handler(s):
    "DEDICATED" established:0 refused:0 state:ready
    LOCAL SERVER
    Service "test-2XDB" has 1 instance(s).
    Instance "test-2", status READY, has 1 handler(s) for this service...
    Handler(s):
    "D000" established:0 refused:0 current:0 max:1022 state:ready
    DISPATCHER <machine: IRIS11G-DB-2, pid: 9340>
    (ADDRESS=(PROTOCOL=tcp)(HOST=IRIS11G-DB-2.test_prod.internal)(PORT=58653))
    The command completed successfully
    LSNRCTL>

  • Unique or primary key on timestamp with timezone

    Hi,
    I have been experimenting with a date column in a primary key, or actually I tried using a timestamp with time zone in a primary key.
    While researching whether there was a way to avoid ORA-02329, I found the following:
    K15> create table dumdum
      2    (datum date not null
      3    ,naamp varchar2( 30 ) not null);
    Table created.
    K15>
    K15> alter table dumdum
      2    add constraint d_pk
      3        primary key
      4          (datum, naamp)
      5    using index;
    Table altered.
    K15>
    K15> select ind.index_type
      2  from   user_indexes ind
      3  where  ind.index_name = 'D_PK';
    INDEX_TYPE
    NORMAL
    1 row selected.
    K15>
    K15> insert into dumdum
      2    (datum
      3    ,naamp )
      4  select sysdate - (level/1440)
      5  ,      'nomen nescio'
      6  from   dual
      7  connect by level < 1000
      8  ;
    999 rows created.
    K15>
    K15> analyze index d_pk validate structure;
    Index analyzed.
    K15> analyze table dumdum compute statistics;
    Table analyzed.
    K15>
    K15> select naamp
      2  from   dumdum
      3  where  datum > to_date('16-06-2011 15.46.16', 'dd-mm-yyyy hh24.mi.ss' )
      4 
    K15> For the last select statement I get the following "explain plan":
    SELECT STATEMENT  CHOOSE
              Cost: 2  Bytes: 247  Cardinality: 13       
         1 INDEX RANGE SCAN UNIQUE D_PK
                    Cost: 3  Bytes: 247  Cardinality: 13  This behavior lived up to my expectations.
    Then, I tried this:
    K15> create table dumdum
      2    (datum date not null
      3    ,naamp varchar2( 30 ) not null);
    Table created.
    K15>
    K15> alter table dumdum
      2    add constraint d_pk
      3        primary key
      4          (datum, naamp)
      5    using index;
    Table altered.
    K15>
    K15> alter table dumdum
      2        modify datum timestamp(6) with time zone;
    Table altered.
    K15>
    K15> select ind.index_type
      2  from   user_indexes ind
      3  where  ind.index_name = 'D_PK';
    INDEX_TYPE
    NORMAL
    1 row selected.
    K15>
    K15> insert into dumdum
      2    (datum
      3    ,naamp )
      4  select sysdate - (level/1440)
      5  ,      'nomen nescio'
      6  from   dual
      7  connect by level < 1000
      8  ;
    999 rows created.
    K15>
    K15> analyze index d_pk validate structure;
    Index analyzed.
    K15> analyze table dumdum compute statistics;
    Table analyzed.
    K15>
    K15> select naamp
      2  from   dumdum
      3  where  datum > to_date('16-06-2011 15.46.16', 'dd-mm-yyyy hh24.mi.ss' )
      4
    K15> So, at first glance, the alter table statement to change the datatype from DATE to TIMESTAMP seems like a way of fooling Oracle. But the explain plan reveals a different story:
    SELECT STATEMENT  CHOOSE
              Cost: 4  Bytes: 1,25  Cardinality: 50       
         1 TABLE ACCESS FULL DUMDUM
                    Cost: 4  Bytes: 1,25  Cardinality: 50  I was only fooling myself. :-0
    But I wasn't done with my research:
    K15> create table dumdum
      2    (datum timestamp(6) with time zone not null
      3    ,naamp varchar2( 30 ) not null);
    Table created.
    K15>
    K15> create unique index d_ind
      2      on dumdum
      3           (datum, naamp);
    Index created.
    K15>
    K15>
    K15> select ind.index_type
      2  from   user_indexes ind
      3  where  ind.index_name = 'D_IND';
    INDEX_TYPE
    FUNCTION-BASED NORMAL
    1 row selected.
    K15>
    K15> insert into dumdum
      2    (datum
      3    ,naamp )
      4  select systimestamp - (level/1440)
      5  ,      'nomen nescio'
      6  from   dual
      7  connect by level < 1000
      8  ;
    999 rows created.
    K15>
    K15> analyze index d_ind validate structure;
    Index analyzed.
    K15> analyze table dumdum compute statistics;
    Table analyzed.
    K15>
    K15> select naamp
      2  from   dumdum
      3  where  datum > to_date('16-06-2011 15.56.16', 'dd-mm-yyyy hh24.mi.ss' )
      4
    K15>Now, my explain plan looks fine:
    SELECT STATEMENT  CHOOSE
              Cost: 2  Bytes: 1,25  Cardinality: 50       
         1 INDEX RANGE SCAN UNIQUE D_IND
              Cost: 3  Bytes: 1,25  Cardinality: 50  Why is Oracle so adamant about not allowing a timestamp with time zone in a unique key? And, given their position on the matter, where does their tolerance for a unique index come from?
    By the way, if I had a say in it, I would not allow anything that even remotely looks like a date to be part of a primary key, but that's another discussion.
    Thanks,
    Remco
    P.S. All this is on Oracle9i Enterprise Edition Release 9.2.0.8.0. Is it different on 10g or 11g?

    See if this helps. You can create primary key for TIMESTAMP WITH LOCAL TIME ZONE datatype.
    SQL>CREATE TABLE Mytimezone(Localtimezone TIMESTAMP WITH LOCAL TIME ZONE primary key, Location varchar2(20) );
    Table created.
    http://download.oracle.com/docs/cd/B19306_01/server.102/b14225/ch4datetime.htm#i1006169
    TIMESTAMP WITH LOCAL TIME ZONE Datatype
    TIMESTAMP WITH LOCAL TIME ZONE is another variant of TIMESTAMP. It differs from TIMESTAMP WITH TIME ZONE as follows: data stored in the database is normalized to the database time zone, and the time zone offset is not stored as part of the column data. When users retrieve the data, Oracle returns it in the users' local session time zone. The time zone offset is the difference (in hours and minutes) between local time and UTC (Coordinated Universal Time, formerly Greenwich Mean Time).
    Thanks
    http://swervedba.wordpress.com/

  • How can I use the SQL to create a primary key for a existing table?

    create table a(bm number,mc varchar2(20));
    when the table was created,i want to make the column bm as
    the primary key and my SQL is "alter table a enable primary key bm",the system show
    me error,how can I write the right one?

    create table a(bm number,mc varchar2(20));
    when the table was created,i want to make the column bm as
    the primary key and my SQL is "alter table a enable primary key bm",the system show
    me error,how can I write the right one? You do not have any primary key defined on your table yet, so, it does not make sense to enable it (if at all possible) !
    You need to add PRIMARY KEY using something like this:
    SQL> alter table a add constraint pk_a_bm primary key (bm) ;

  • How to do hibernate mapping for table or view without a primary key

    Hi,
    Anyone knows how to do hibernate mapping for table or view without a primary key?
    thanks.
    cc

    or you can make all column primary key .Anybody seriously considering that as a good idea should understand the implications:
    1. this requires that each row be unique - that's a minor issue normally, but can be a significant problem in some cases
    2. in practically all databases, a primary key constraint creates a unique index - this has many implications:
    a) in most databases, the index stores a copy of the column data that is indexed - this suggestion therefore more than doubles the data storage required for the data
    b) whenever an indexed column is changed, the index has to be maintained - this suggestion then more than doubles the work that each UPDATE statement has to do, since both the table and the index have to be maintained for any UPDATE at all
    This might work OK for toy projects, but it doesn't scale well at all...

Maybe you are looking for

  • HT1926 applied the latest Itunes update and now it crashes when I try yo access the store win 7 64 pc

    has anyone else seen this win pc is totally up to date but I am at IE9 as IE 10 is flakey

  • Right click print option not now available for pdfs

    I have just upgraded from Windows XP to Windows 7 and am running Acrobat 9 Pro.  On a daily basis I get a batch of pdf files that I need to print.  In XP I would have right clicked and chosen Print, however this option is not available now I am on Wi

  • Fingerhut??

    So I applied to their fresh start program. And before accepting it I have been doing some reading. Consumer affairs has hundreds of bad reviews stating they will report late payments even if you are on time and such. Anyone have any experience with t

  • Converting PDF forms

    Can I convert a "flat" PDF form into a form I can complete and print?

  • New In Java.....

    Hi, I'm a Lotus based programmer and just started to learn Java few month ago. After the few month self-study, I found that there are too many classes and interface to remembers. I'm having a hard time to remembers all the classes. I have few questio