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

Similar Messages

  • Too many objects matching primary key

    Hi.,
    I am using jdev 11.1.5
    I ha created a read only VO and FinyrEO,FinyrVO
    I had created a button which will update the status as "p"
    I had used this code in AMImpl Method
        public void post (List selectedindexs){
            ViewObjectImpl GlJrnlHd = this.getgljrnlhdln2();
                 Row row = GlJrnlHd.getCurrentRow();
            RowSetIterator iter = getGlJrnlHd1().createRowSetIterator(null);
            iter.reset();
                while (iter.hasNext()){
                                Row current1 = iter.next();
                    if (row.getAttribute("GjhBu").equals(current1.getAttribute("GjhBu"))){
                        if (row.getAttribute("GjhJrnlNo").equals(current1.getAttribute("GjhJrnlNo"))){
                            if (row.getAttribute("GjhJrnlSfx").equals(current1.getAttribute("GjhJrnlSfx"))){
                                if (row.getAttribute("GjhJrnlType").equals(current1.getAttribute("GjhJrnlType"))){
                                    if (row.getAttribute("GjhPeriod").equals(current1.getAttribute("GjhPeriod"))){
                                        current1.setAttribute("GjhStatus", "P");
                                        this.getTransaction().commit();
        }while i click this button an exception occurs as too many objects
    This link gives u added information
    http://www.4shared.com/photo/E3P28f2s/E015.html

    USER,
    Too many objects match primary key null
    from ur subjects says u r facing the problem with pk. ok . if this ur problem. ur table the particular column has pk.
    by nature u know that pk should not duplicate values. and null values.
    y adding null in subject. i don about it.
    in the post your says about create button operation.. i cant understud.
    where u r facing primayy key problem. r u speaking create button operation or else create insert operation?.
    what is exact needed. where are u facing the problem. make it some more clear for me.

  • 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)

  • 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

  • Populating primary key from My SQL

    I have a table called MEMBERS in MY SQL with BEFORE INSERT trigger on it to create the primary key. Trigger works when I use the MYSQL prompt to insert. By Using BC in 10.1.3 , I want to populate the primary key (memberid) when insert any record in to this table. In the model, 'primary key','& TRansient' are the only properties selected for the entity.
    When I insert using BC the record in not being created. How do I make it work.
    Following is the trigger on the table.
    CREATE OR REPLACE TRIGGER ASSIGN_MEM_ID
    BEFORE INSERT ON MEMBERS FOR EACH ROW
    BEGIN
    IF :NEW.MEMBERID IS NULL OR :NEW.MEMBERID < 0 THEN
    SELECT memid
    INTO :NEW.MEMBERID
    FROM MemberSequence;
    UPDATE MemberSequence
    SET memid= memid+1;
    END IF;
    END;
    Any help is appreciated.
    Thanks
    nk

    Try using the DBSequence data type for the column.
    see "6.6.3.8 Trigger-Assigned Primary Key Values from a Database Sequence" in the ADF Developer Guide.
    http://download.oracle.com/docs/html/B25947_01/bcentities006.htm#sm0147

  • Retrieving auto inc primary key from entity bean (MySQL DB)

    Hello,
    I searched the forum intensively, but did not find an answer for the following problem.
    I've set up an MySQL database "Location" with two fields (ID, Description), ID is my primary key and I've added the AUTO_INCREMENT flag to this field. This works fine, i can add a row in the table with my entity bean "Location" from my session bean :
    Location l = new Location();
    l.setDescription("at home");
    em.persist(l);
    and even when I ask this location back from the DB, there is no problem :
    Location l = em.find(Location.class,1);
    return l.getDescription();
    The rows in the table increment nicely. The problem however is, that you don't allways know the ID. So I would like to do the following from my session bean:
    Location l = new Location();
    l.setDescription("at home");
    em.persist(l);
    int id = l.getId();
    the getID method allways returns a null object. The row is added in the DB, but the auto incremented ID is not returned to the entity bean!
    I know I could solve this by generating the ID's myself, but one of the strengths of autoincrement should be not to have to do this, no?
    If anyone has a clue how to solve this issue, I would very much appreciate it !
    Michiel
    Edited by: Michiel82 on Dec 6, 2007 6:01 AM

    No reactions so far ... this is a work-around for the issue :
    I've created an additional table sequence with two fields: gen_key and gen_value. Then, in my Location entity bean I can add the following:
    @TableGenerator(
    name="locationGen",
    table="sequence",
    pkColumnName="gen_key",
    valueColumnName="gen_value",
    pkColumnValue="location",
    allocationSize=1
    @Id
    @GeneratedValue(strategy=GenerationType.TABLE,generator="locationGen")
    @Column(name = "id", nullable=false)
    private Short id;
    This generates the primary key in the bussiness logic, but I would like to get the autogenerated key from my MySQL database (see previous post). Is this perhaps not supported by EJB3.0?
    Michiel

  • Upload data from excel where one column has text of 3000 characters

    Guyz,
    I have a query. One of my requirments is to upload data from excel sheet & create a material. In the excel sheet one of the columns has text for BASIC DATA TEXT under ADDITIONAL DATA of a Material. This is a text of running length.
    the selection screen has feature of file upload & the users will upload excel files from their respective presentation servers.
    Now my problem is that I need a function module which can convert this column in excel sheet into an internal table & later call the BAPI for MM creation.
    I have used TEXT_CONVERT_XLS_TO_SAP & when i read my internal table to check this column length, it shows only 255 characters where as data in the excel sheet has 3000 characters (say for eg.)
    Can anybody throw some light on this.
    Thanks in advance
    GPK

    Hi,
    You can try using this function module and see that whether all your data is coming into the internal table properly.
    MS_EXCEL_OLE_STANDARD_DAT
    For the other part you needed to convert the internal table data into the structure as need by the BAPI and then call the create BAPI to create the materials in the SAP System.
    Hope this helps.
    Thanks,
    Samantak.

  • How to pass the primary key from a report to multiple forms

    I am trying to build an application that tracks a person's training records. I have a report and 3 forms (all tabbed). From the report I can click the edit link to modify a person. Is there a way I can pass the primary key of the person (from the report) to the other forms? Hope what I'm trying to do is clear.
    Thanks.

    Hi,
    You can specify items from other pages also.
    Did you use that popup to pick item ?
    Did you noticed that it filter by page where your link point. You can remove filter from popup and then select other items.
    Or just manually type your item names
    Br, Jari
    Edited by: jarola on Nov 11, 2009 1:08 AM

  • Primary Key from Database Sequence

    Hi,
    I have a form that has a master block(single_record) and a child block(multi-record). I am using Database Sequence for primary key. And I am not using any toolbar, instead using the default from FORMS. I want to keep this primary key field invisible and non-navigable.
    Which triggers should I write the sequence.nextval code in the form ??
    Thanks!!
    Shalu

    Thanks so much!! I'll try that!!
    I hope I won't get this error: it doesn't let me come out from the field unless i enter a value, because being primary it is mandatory, though i want the field to be non-navigable and i'll turn the display to false.
    Thanks Again!!
    Shalu

  • Primary Key from foreign keys

    I have a table which has 3 foreign keys, two of which form the primary key.
    I have: ID_Product, ID_Sale, ID_Buy, and also an attribute which tells if its a buy or a sale.
    So, if a sale is made, the primary key should consist of ID_Product && ID_Sale, otherwise, it's ID_Product && ID_Buy.
    Is there a way to do this in Oracle, and if there is, can you point me to where I can read about this?
    thank you in advance

    tashe,
    This is the wrong forum for you question. Try posting here:
    PL/SQL
    I will say, however, that there are advantages to keeping your primary keys apart from your data - just populating them from a sequence. Also, you may be temped to enforce this via triggers, but read the following first:
    http://tkyte.blogspot.com/2008/05/another-of-day.html
    Not that you would have a mutating table problem, but the two table solution may help you. Really think the design through.
    Regards,
    Dan

  • Getting the primary key from order form

    Does anyone know how to get the primary key (DocEntry) off of the order form for an existing order?  I don't really want to use the DocNum field since it is not the primary key and theoretically two different orders could have the same DocNum.  Thanks in advance for your help.

    Hi Joe,
    DocEntry and DocNum values are unique, so you cannot have in db 2 orders with the same DocNum. It's possible, that DocEntry and DocNum values can vary.
    If you know the DocNum value (f.e. from Order's Form), you can simple use RecordSet object:
    Dim sQuery as String
    Dim oOrder as SAPbobsCOM.Documents
    Dim oRecordSet As SAPbobsCOM.Recordset
    Set oOrder = oCompany.GetBusinessObject(oOrders)
    Set oRecordSet = oCompany.GetBusinessObject(BoRecordset)
    sQuery = "Select DocEntry From ORDR Where DocNum = '" & DocNumber & "'"
    oRecordSet.doQuery sQuery
    If oRecordSet.RecordCount > 0 Then
      oOrder.GetByKey(oRecordSet.Fields(0).Value)
    End If
    And this should work.
    Regards
    Libor.

  • Dynamically fill primary key from a second table

    Hi,
    IDOC-JDBC
    during runtime, the primary_key of the table must be filled dynamically.
    something like,
    it should go to a table dyn_key and get the hightest value of the field there and add one to it and pass it to dyn_key
    any idea how do i do it?
    regards,
    nikhil.

    Hello Nikhil,
    You can use JDBC look up for retrieving the current Primary key value.....
    Regards
    Ashwin M

  • Primary key from Synonmn

    Hi ,
    I want to get the Primary Keys for my tables . I used
    java.sql.DatabaseMetaData databasemetadata = connection.getMetaData();
        ResultSet rs = databasemetadata.getTables(null, null, "%", null);
    rs.next();
        System.out.println(" TABLE_CAT "+ rs.getString(1));
        System.out.println(" TABLE_SCHEM  "+rs.getString(2));
        System.out.println(" TABLE_NAME "+rs.getString(3));
        System.out.println(" TABLE_TYPE  "+rs.getString(4));
        System.out.println(" REMARKS "+rs.getString(5)); gives :
    TABLE_CAT null
    TABLE_SCHEM PROGRESS
    TABLE_NAME ApplicConv
    TABLE_TYPE SYNONYM
    REMARKS null
    Now if I use :
      rs = databasemetadata.getPrimaryKeys(null,"PROGRESS","Applicconv");
      System.out.println("Is result set Non empty "+rs.next());gives :
    Is ResultSet non empty false .
    Can you tell me why this result is empty? Is it because of my table is a Synonym?
    If it is Synonym how to get the[b] primary key ?

    does your database documentation provide any hints?
    or your jdbc driver?

  • How to get the Primary key from  Synonym

    Hi ,
    I want to get the Primary Keys for my tables . I used
    java.sql.DatabaseMetaData databasemetadata = connection.getMetaData();
        ResultSet rs = databasemetadata.getTables(null, null, "%", null);
    rs.next();
        System.out.println(" TABLE_CAT "+ rs.getString(1));
        System.out.println(" TABLE_SCHEM  "+rs.getString(2));
        System.out.println(" TABLE_NAME "+rs.getString(3));
        System.out.println(" TABLE_TYPE  "+rs.getString(4));
        System.out.println(" REMARKS "+rs.getString(5)); gives :
    TABLE_CAT null
    TABLE_SCHEM PROGRESS
    TABLE_NAME ApplicConv
    TABLE_TYPE SYNONYM
    REMARKS null
    Now if I use :
      rs = databasemetadata.getPrimaryKeys(null,"PROGRESS","Applicconv");
      System.out.println("Is result set Non empty "+rs.next()); gives :
    Is ResultSet non empty false .
    Can you tell me why this result is empty? Is it because of my table is a Synonym?
    If it is Synonym how to get the primary key ?

    You can use DatabaseMetaData#getPrimaryKeys.

  • How to import decimal values from Excel to nvarchar column correctly?

    I have SQL Server 2012 Integration Services. I have Excel Source and OLE DB Destination.
    I have 2 Excels, both having exactly same columns and their destination table is same.
    I have MarketShare column in Excel. I have also MarketShare column nvarchar(100) in Database. I should not make any change in Excel file or DB table.
    MarketShare value can be numerical like "0.50" or "25.4" or text like "Not Available" or text like "Not Available Yet" 
    My problem is that numerical values are stored to DB like 0.500000000000003, 25.399999999999999. Text as stored correctly.
    What should I do so that digits of numerical values are stored corretly to nvarchar(100) column?
    Kenny_I

    Hi Kenny_I,
    I am unable to reproduce the issue in my test environment no matter it is a XLS file or a XLSX file. After adding extended property “IMEX=1” to the ConnectionString of the Excel Connection Manager, the connection string should be as follows:
    For XLS file:
    Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Temp\Test.xls;Extended Properties="EXCEL 8.0;HDR=YES;IMEX=1";
    For XLSX file:
    Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Temp\Test.xlsx;Extended Properties="EXCEL 12.0 XML;HDR=YES;IMEX=1";
    If we open the Advanced Editor for the Excel Source, and expand the Output Columns node,  the data type of the MarketShare column should be to DT_WSTR with 255 length. Because the length of the destination column in SQL Server table is 100,
    we need to change the length of the output column from 255 to 100. There may be a warning about data truncation thrown by the Excel Source but we can ignore this warning.
    If the above steps doesn’t work, please post more information about this package for further investigation. Please post the data type of the Output Column MarketShare of the Excel Source as well as the Input Column MarketShare of the OLE DB Destination.
    Besides, click the path between the Excel Source and OLE DB Destination and click “Enable Data Viewer”. Then, run the package to check whether the data displayed in the Data Viewer are the same as the source data (like 0.50) or the same as the data inserted
    to the SQL Server table (like 0.500000000000003).
    Regards,
    Mike Yin
    If you have any feedback on our support, please click
    here
    Mike Yin
    TechNet Community Support

Maybe you are looking for