Can I have a primary key as a non-unique column

Hi all,
I have a table with 35 columns and only one column in a not null column. But this column data is not unique. I want to create a primary key with non-unique index, can I don it, if it is not possible is there any other way to it. Please help me with this.
Thanks for your help.vinaykotha

1) Do the 'Unique Column combination' check first, using this example. (Pl. Change the column name and number of columns you consider as candidate key.) The SQL as follows:-
;WITH CTE (ProductKey, CustomerKey, SalesTerritoryKey, DupRec)
 AS
  (SELECT ProductKey, CustomerKey, SalesTerritoryKey, ROW_NUMBER() OVER
     (PARTITION BY ProductKey, CustomerKey, SalesTerritoryKey
      ORDER BY ProductKey, CustomerKey, SalesTerritoryKey) AS DupRec
   FROM dbo.FactSales 
SELECT *
FROM CTE
WHERE DupRec > 1
2) if CTE Table returns no records, you are good to create a Composite CLUSTERED PRIMARY KEY, like:
ALTER TABLE dbo.FactSales
ADD CONSTRAINT PK_ProductKey_CustomerKey_SalesTerritoryKey 
PRIMARY KEY CLUSTERED (ProductKey, CustomerKey, SalesTerritoryKey);
If no error..bingo! if NOT, Don't worry, create a Composite Index like this:-
3)
CREATE NONCLUSTERED INDEX [IX_ProductKey_CustomerKey_SalesTerritoryKey] 
ON dbo.FactSales(ProductKey, CustomerKey, SalesTerritoryKey);
This will work still efficiently. Usually all transaction table are like that like Daily_Order table, Ship_Details table etc.
-NC

Similar Messages

  • How can I replicate a source table that doesn't have any primary keys?

    We have transactional replication setup in our workplace.
    In the source database, there are some tables that do not have any primary key.
    1) How can I get these tables to replicate in the current scenario?
    2) Is it possible to introduce foreign elements in a replicated instance of the database?
    Example, additional records in a table that don't exist in the source or additional tables in the database?

    1) You need to add a primary key to this table. There must be a criteria that the app uses to identify which row it wants to up date or delete. If not you might be able to add an identity column to the table and then add a primary key to it. If this is not
    possible you might want to use snapshot replication or CDC to do change tracking and then something like SSIS or service broker to move the change to the destination server.
    2) yes, but be careful. They should not modify the schema or the data of tables which are being replicated.
    looking for a book on SQL Server 2008 Administration?
    http://www.amazon.com/Microsoft-Server-2008-Management-Administration/dp/067233044X looking for a book on SQL Server 2008 Full-Text Search?
    http://www.amazon.com/Pro-Full-Text-Search-Server-2008/dp/1430215941

  • Can EJB 3.0 beans be used with tables that do not have a primary key?

    Can a EJB 3.0 persistence bean be used with tables that do not have a primary key defined? I am building a test application based on the HowTo - Building EJB 3.0 Faces App paper posted after Openworld (schalk). The issue I am running into when trying to run the application is: Exception Description: Entity class [class com.persistence.Rpthead] has no primary key specified. Note: I get a simular error when using toplink directly.
    The tables I am binding to do not have primary keys defined. They use unique constraints to manage the table integrity.
    Is it possible to use EJB 3.0 on tables without a primary key? If not, are there plans to support this in the future?

    The spec requires a primary key Id annotation. I will take your suggestion to EJB 3.0 expert group.
    Can you also send an email to [email protected] with your requirement?
    -Debu

  • Source tables for forms and tabular forms must have a primary key.

    Why does HTML DB 2.0 return the message
    "Source tables for forms and tabular forms must have a primary key."
    when trying to generate a "Report and Form" page based on a view defined like "create view <applicationschema>.a as select * from <sourceschema>.b" ?
    It should be possible for HTML DB to "see" that the table "<sourceschema>.b" already has a primary key.
    bw - Christian

    Christian,
    In the create application wizard, when creating form or tabular form pages, you can only use tables with primary keys, and not views, because that wizard is automatically deriving the primary key from the table definition. If you want to build forms on views or tables without a primary key, you need to use one of the create form wizards while working on an existing application. Those wizards allow you to pick your own column as a primary key column.
    Regards,
    Marc

  • How many primary keys for one table?can we add more primary keys

    In general Table have one  primary key.is it possible to more than one primary key in a table?(ie is it possible to add more than one pirmary key in a table). Help me out.

    pls do check this link
    [http://help.sap.com/saphelp_nw04/helpdata/en/cf/21ea0b446011d189700000e8322d00/frameset.htm|http://help.sap.com/saphelp_nw04/helpdata/en/cf/21ea0b446011d189700000e8322d00/frameset.htm]
    All the key fields of a table must be stored together at the beginning of the table. A non-key field may not occur between two key fields.
    A maximum of 16 key fields per table is permitted. The maximum length of the table key is 255.
    If the key length is greater than 120, there are restrictions when transporting table entries. The key can only be specified up to a maximum of 120 places in a transport. If the key is larger than 120, table entries must be transported generically.

  • Getting ADFv: Rowkey does not have any primary key attributes

    Hi
    I am using 11.1.1.5.0 version of JDeveloper.
    The ViewObject has DistaccountId,OperatingUnit,PricingCategoryId,PartyId as Primary Key and
    the EntityObject also has DistaccountId,OperatingUnit,PricingCategoryId,PartyId as Primary Key
    and my Table also has the same set of attributes(DistaccountId,OperatingUnit,PricingCategoryId,PartyId) as Primary Key .
    I am getting the following error on Create,Update Operation -
    "<CurrencyRowKeySet> <_computeCurrentRowKey> ADFv: Rowkey does not have any primary key attributes. Rowkey: oracle.jbo.Key[], table: oracle.jbo.server.ViewObjectImpl@6c41af."
    Also,when i choose a row for Update operation,the pop-up that opens up holds the values for some other record.
    Please suggest.

    I'm not too sure but can you check if you have the following text in your page source ?
    selectedRowKeys="#{bindings.<TreeBindingName>.collectionModel.selectedRow}"
    selectionListener="#{bindings.<TreeBindingName>.collectionModel.makeCurrent}"

  • Error : Rowkey does not have any primary key attributes

    Hello All,
    I'm developing an ADF application which has a few ADF forms. The forms have VO's and some tables.
    On running, I seem to be getting this error
    <Error> <oracle.adfinternal.view.faces.model.binding.CurrencyRowKeySet> <BEA-000000> <ADFv: Rowkey does not have any primary key attributes. Rowkey: oracle.jbo.Key[], table: oracle.jbo.server.ViewObjectImpl@2ecf4f19.>
    Where does the Rowkey have to be set? Is it in the VO?
    Regards,
    PP

    Make sure that the VO's you use have at least one attribute selected as a key attribute. GO to View Object overview editor and select attributes tab, see whether there is at least one attribute marked as a key. If not select the most appropriate attribute from the list of fields and go to edit attribute dialog, tick the key attribute property.

  • Can I create constraints "Primary key - Foreign key" on materialized views?

    Hello!
    Can I create constraints "Primary key - Foreign key" on materialized views like on tables?
    My purpose - is to make DB schema "COPY" with set of materialized views or tables, which take data from time to time from other tables situated.into another schema "ORIGINAL".
    Also - I want to use reporting tool, like Crystal Reports, to make nice reports from schema "COPY". To make nice reports, I need primary-foreign relationships between materialized views or tables in schema "COPY".
    Is it possible to use materialized views?
    Or I should use only tables to get such result?
    Thank you in advance.
    Edited by: kogotok1 on Dec 3, 2010 5:01 PM

    What happens when you try it? Or search the manuals.
    http://download.oracle.com/docs/cd/E11882_01/server.112/e17118/statements_6002.htm#i2105365
    http://download.oracle.com/docs/cd/E11882_01/server.112/e10706/repmview.htm#REPLN360

  • Can I have a developer Key?

    Hello,
    I activated the SAP HANA Insurance, but I need one developer Key. How can I have a developer Key?
    Is possible create the CDS or view table inside Hana database with this istance?
    Thank in advance.
    Best Regards,
    Marino

    Hello Marino,
    in case you would like to use the systems for a Proof of concept and actually use your own data, you would have to purchase the SAP Cloud Appliance Library Subscription license first and then you can use the systems with the software with your own licenses.
    Trial systems can not be used for a PoC or a prototype or with your own data. These are explicitly excluded from trials in the Terms and Conditions already.
    for further details see the FAQ
    http://scn.sap.com/docs/DOC-58120
    regards
    Ingo Hilgefort

  • Setting a Primary Key for a newly added Column

    Is it possible for setting a primary key for a newly added column in a table having records?

    Hi,
    km**** wrote:
    oh if the table has records then it is not possible ah...No, the table can have rows at the time you add the Primary Key constraint. Solomon was just saying that the column(s) that you are making into the Primary Key must already have unique values. A Primary Key can not be NULL, so you must do the steps in this order:
    (1) ALTER TABLE to add the column(s) (if this hasn't been done already)
    (2) UPDATE the table, to put unique values in all rows for the Primary Key column(s)
    (3) Add the PRIMARY KEY constraint
    You need to do step (2) before you do step (3)

  • OWB Dataprofiling - Unique Key Analysis on non-number columns

    Does anyone know an easy way to enable unique key analysis on non-Number columns (OWB 10.2.0.3).
    It seems that the profiler by default disables the
    'Use in relationsship discovery' when the documented datatype is non-Number.
    Is this a setting which can be configured for OWB, or is there a smart way to set this property for all columns?
    thks in advance

    Hi don't think there is a way to to automatically switch this on/off, a small script can be created to set the option on/off for all columns in the table.
    Cheers
    David

  • 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 can I obtain the primary key of a table for an entity relation?

    hello everybody
    I am doing a consultation to a table in my data base, good this table has alone two fields, the first one is the code or pk and the second one is the description, to be presisos they are names of city and code.
    From the beginning!!: This method this one in another class that is a Dialog that is going to call to the class SelecPlace ();
      SelecPlace sl = new SelecPlace();
    public void capturarLugar(){  //  Simple void method in the mentioned class
            String place = txtProcedencia.getText() ;  //  a JTextField
            sl.executeStatement(place) ;                  
        }ok, now we see part of the code of the class SelectPlace
    public class SelecPlace extends AbstractTableModel{
        Connection con = null;
        Statement sentencia = null ;
        ResultSet rs = null;
        ResultSetMetaData rsmd = null ;
        String[] nameColum = {} ;
        Vector datos = new Vector() ;
        public SelecPlace() { }
        public void executeStatement(String query){
          try{
             con = DBManager.getConnection() ;
             sentencia = con.createStatement(rs.TYPE_SCROLL_INSENSITIVE,
                                                                          rs.CONCUR_UPDATABLE) ;
             String sql = "select * from Place where descripcion like %"+query+"%'";
              rs = sentencia.executeQuery(sql) ;
              rsmd = rs.getMetaData();
              int nroColumnas = rsmd.getColumnCount() ;
              nameColum = new String[nroColumnas] ;
              //obtengo los nombres de columnas en cache
               for(int colum = 0; colum < nroColumnas; columna++){
                    nameColum[colum] = rsmd.getColumnLabel(columna + 1) ;
               datos = new Vector();
                while(rs.next()){
                    Vector newRow = new Vector();
                    for(int i = 0; i < getColumnCount(); i++){
                    newRow.addElement(rs.getObject("place_ID"));
                    newRow.addElement(rs.getObject("description"));
                    datos.addElement(nuevaFila);
                fireTableChanged(null);
            }catch(SQLException e){
                System.err.println(e);
                e.printStackTrace(System.err);
                System.out.println("error in statement");
            }catch(ClassNotFoundException cnfe){
                System.err.println(cnfe);
        }Ok, this code me works and I obtain in this case the field description of the table Place
    Now my question is, how can I obtain the primary field of my table?
    I need this value of this field that in the base of information in a bigint, and to take it to the first class before mentioned, for that I am working with a data base related

    Certain duffymo and everyone!!, good I give you my scheme:
    And generalizing my question, I want to obtain the value of the primary key of a table in the database, I obtain more values of the same row, but I need the primary key, and you see one with the primary key I want to turn a Long and it to insert with code java in foreign clave in another table of the database
    Good of this form I believe that it would not be breaking the integrity relacional of the tables

  • How can I avoid displaying Primary key fields in BC4J .......

    Hi,
    I am using auto-sequencing in the create method to assign values
    to primary keys - therefore I do not need to display these
    primary key columns to the user, etc. How can I do that.
    Thanks in advance.
    KI

    I will try to help you
    1. go to your bc4j
    2. Double click the entity object
    3. Select attributes setting tab
    4. Select your key attribute and unchecked 'mandatory'
    5. Select apply and close this windows
    6. Double click the view object and select the attributes
    setting tab
    7. Select your key attribute and on updatable option
    select 'Never'
    8. Good luck

  • Matching Primary key from Excel to DB Column before import

    Hello Experts, 
    I am trying to achieve the task related with updates into my destination table via store procedure using dynamic sql. Basically I am importing the
    excel file into sql server.
    For further step, I want to update only the records that do not exist already in the table with reference to primary key. For this the user will provide
    as an input for procedure the column (or columns) that compose the primary key in excel.
    Example of EXEC command to run the store Procedure
    EXEC
    [ImportExcelFile_Error_Handling]
    'D:\test\test.xlsx','sheet1','testDB',
    'create','[Test Column1]’
    So in this case the [Test Column1] from excel contains now my Primary Key and if I execute my procedure then code should check the values of the
    [Test Column1] in the existing table in database, against the
    [Test Column1]
    in database.  
    If [Test Column1]
    value match with db
    [Test Column1]
    then skip rows and if not match then insert row entry.
    Below is my code, which needs to be update.
    if
    @TypeOfUpdate='Update'
    Begin
    declare
    @PrimaryLeyColumn NVARCHAR(max)
    set
    @PrimaryLeyColumn=''
    exec('Insert into ['
    + @DestinationTable
    + '] select * from openrowset(''Microsoft.ACE.OLEDB.12.0'', ''Excel 12.0;HDR=YES;IMEX=1;Database='
    + @TABLENAME
    + ''', ' +
    ''' select * from '+@SourceSheet
    + ''')')
    end
     thanks in advance.
    Looking for support.
    SharePoint_Consultant_EMEA

    Hello,
    Here is my complete code:
    --------------------Declaring variables------------------------------
    CREATE
    PROCEDURE [dbo].[ImportExcelFile_Update_Error_Handling]     
    (@TABLENAME
    varchar(1000)
    ,@SourceSheet
    varchar (100)
    ,@DestinationTable
    varchar (100)
    ,@TypeOfUpdate
    varchar (100)
    ,@PrimaryLeyColumn
    VARCHAR(255))
    as
    declare
    @retval int
    --Remaing Value
    EXEC
    master..xp_fileexist
    @TABLENAME,
    @retval output
    -- check if file exists
    if
    @retval = 0
    begin
    print 'file does not exists.'
    return
    end
    if
    @SourceSheet is
    null or @SourceSheet
    = ''
    set @SourceSheet
    = '[Sheet1$]' -- assume that the Sheet name on excel file is the default name
    else
    set @SourceSheet
    = '[' +
    ltrim(rtrim(@SourceSheet))
    + '$]'
    if
    @DestinationTable is
    null or
    @DestinationTable =
    set @DestinationTable
    = substring(@SourceSheet, 2,
    len(@SourceSheet)
    - 3)
    + convert(varchar,
    getdate(), 126)
    if
    @TypeOfUpdate='Update'
    Begin
    Begin
    try
    --if @PrimaryLeyColumn =''
    set
    @PrimaryLeyColumn =
    '[]'--here i think need to add the value or updates
    exec('Insert into ['
    + @DestinationTable
    + '] select * from openrowset(''Microsoft.ACE.OLEDB.12.0'', ''Excel 12.0;HDR=YES;IMEX=1;Database='
    + @TABLENAME
    + ''', ' +
    ''' select * from '+@SourceSheet
    + ''')t WHERE NOT EXISTS (SELECT 1 FROM ['
    + @DestinationTable
    + '] WHERE ['
    + @PrimaryLeyColumn
    + '] = t.[' +
    @PrimaryLeyColumn +
    declare
    @Appendcount INT
    declare
    @SQLStringCount nvarchar(500);
    declare
    @ParamDef nvarchar(500);
    declare
    @TabName nvarchar(500);
    SET
    @SQLStringCount =
    N'SELECT @COUNT=COUNT(1) FROM '+
    @DestinationTable;
    SET
    @ParamDef =
    N'@TABLE varchar(30),@COUNT BIGINT OUTPUT';
    EXECUTE
    sp_executesql @SQLStringCount,
    @ParamDef ,@Table=@TabName,
    @COUNT=@Appendcount
    OUTPUT;
    --Getting the rowcount as a output parameter from the sp_executesql.
    if
    @Appendcount != 0
    PRINT
    'Database is "Updated" with total number of Records= '
    + Cast(@Appendcount
    AS VARCHAR(200))
    end
    try
    Begin
    Catch
    if @DestinationTable is null or @DestinationTable = ''
    DECLARE
    @ErrorNumberUT INT
    = ERROR_NUMBER();
    DECLARE
    @ErrorMessageofUpdateTable
    NVARCHAR(max)
    = ERROR_MESSAGE();
    PRINT
    'Error, Table not exists in the database'
    PRINT
    'Actual error number: ' +
    CAST(@ErrorNumberUT
    AS VARCHAR(10));
    PRINT
    'Actual Error Message: '
    + CAST(@ErrorMessageofUpdateTable
    AS VARCHAR(max));
    end
    Catch
    end
    To execute this code I am using this script
    EXEC
    [ImportExcelFile_Update_Error_Handling]
    'D:\TestFiles\Test_Updates.xlsx','sheet1','Error_Handing','update','[SUPLR_DUNS_NBR]';
    [SUPLR_DUNS_NBR] is the column where I have "ID to match" with new and old content in my excel and if this content same in my sql table then skip else insert the row.
    Any support in this would ge really helpful to achive my tasks goal. 
    thanks
    SharePoint_Consultant_EMEA

Maybe you are looking for

  • Help with icloud and multiple users in iTunes

    Our family music is under my iTunes/apple id.  My mother, husband and I all synch to iTunes on one computer.  Can we set up multiple icloud accounts for synching our contacts separately?

  • BEx Web Analyzer send buttion

    Dear all, We are on NetWeaver 2004s BI SP11.  I have activated the web templates starting with 0ADHOC from BI content.  From BEx Web Analyzer, if I click on send buttion, I see screen consisting four tabs and buttons like save view, export to excel,

  • Missing files from creative cloud

    Numerous files have gone missing. The folders are there, but there is nothing in them. Also, I've checked the archive folder, and it is also empty.

  • Same URL Pattern error

    A colleague of mine has generated a web service stub (is that the correct term) using netbeans and he has it deployed on his local host using Glassfish. I have tried to to the same by taking his source code and building it. I successfully buld the se

  • LABEL.ASC Error on System Copy

    Dear gurus, I'm executing standard system copy (migration/r3load) on HP-UX, DB2 database. When providing a RDBMS source file, it came up with error: Found the label DB2/LUW:V9.7 FP4:RDBMS:DB2/LUW:D51041317 but need the label DB2/LUW:V9:RDBMS:DB2/LUW: