Check for duplicate record in SQL database before doing INSERT

Hey guys,
       This is part powershell app doing a SQL insert. BUt my question really relates to the SQL insert. I need to do a check of the database PRIOR to doing the insert to check for duplicate records and if it exists then that record needs
to be overwritten. I'm not sure how to accomplish this task. My back end is a SQL 2000 Server. I'm piping the data into my insert statement from a powershell FileSystemWatcher app. In my scenario here if the file dumped into a directory starts with I it gets
written to a SQL database otherwise it gets written to an Access Table. I know silly, but thats the environment im in. haha.
Any help is appreciated.
Thanks in Advance
Rich T.
#### DEFINE WATCH FOLDERS AND DEFAULT FILE EXTENSION TO WATCH FOR ####
            $cofa_folder = '\\cpsfs001\Data_pvs\TestCofA'
            $bulk_folder = '\\cpsfs001\PVS\Subsidiary\Nolwood\McWood\POD'
            $filter = '*.tif'
            $cofa = New-Object IO.FileSystemWatcher $cofa_folder, $filter -Property @{ IncludeSubdirectories = $false; EnableRaisingEvents= $true; NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite' }
            $bulk = New-Object IO.FileSystemWatcher $bulk_folder, $filter -Property @{ IncludeSubdirectories = $false; EnableRaisingEvents= $true; NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite' }
#### CERTIFICATE OF ANALYSIS AND PACKAGE SHIPPER PROCESSING ####
            Register-ObjectEvent $cofa Created -SourceIdentifier COFA/PACKAGE -Action {
       $name = $Event.SourceEventArgs.Name
       $changeType = $Event.SourceEventArgs.ChangeType
       $timeStamp = $Event.TimeGenerated
#### CERTIFICATE OF ANALYSIS PROCESS BEGINS ####
            $test=$name.StartsWith("I")
     if ($test -eq $true) {
            $pos = $name.IndexOf(".")
       $left=$name.substring(0,$pos)
       $pos = $left.IndexOf("L")
       $tempItem=$left.substring(0,$pos)
       $lot = $left.Substring($pos + 1)
       $item=$tempItem.Substring(1)
            Write-Host "in_item_key $item in_lot_key $lot imgfilename $name in_cofa_crtdt $timestamp"  -fore green
            Out-File -FilePath c:\OutputLogs\CofA.csv -Append -InputObject "in_item_key $item in_lot_key $lot imgfilename $name in_cofa_crtdt $timestamp"
            start-sleep -s 5
            $conn = New-Object System.Data.SqlClient.SqlConnection("Data Source=PVSNTDB33; Initial Catalog=adagecopy_daily; Integrated Security=TRUE")
            $conn.Open()
            $insert_stmt = "INSERT INTO in_cofa_pvs (in_item_key, in_lot_key, imgfileName, in_cofa_crtdt) VALUES ('$item','$lot','$name','$timestamp')"
            $cmd = $conn.CreateCommand()
            $cmd.CommandText = $insert_stmt
            $cmd.ExecuteNonQuery()
            $conn.Close()
#### PACKAGE SHIPPER PROCESS BEGINS ####
          elseif ($test -eq $false) {
            $pos = $name.IndexOf(".")
       $left=$name.substring(0,$pos)
       $pos = $left.IndexOf("O")
       $tempItem=$left.substring(0,$pos)
       $order = $left.Substring($pos + 1)
       $shipid=$tempItem.Substring(1)
            Write-Host "so_hdr_key $order so_ship_key $shipid imgfilename $name in_cofa_crtdt $timestamp"  -fore green
            Out-File -FilePath c:\OutputLogs\PackageShipper.csv -Append -InputObject "so_hdr_key $order so_ship_key $shipid imgfilename $name in_cofa_crtdt $timestamp"
Rich Thompson

Hi
Since SQL Server 2000 has been out of support, I recommend you to upgrade the SQL Server 2000 to a higher version, such as SQL Server 2005 or SQL Server 2008.
According to your description, you can try the following methods to check duplicate record in SQL Server.
1. You can use
RAISERROR to check the duplicate record, if exists then RAISERROR unless insert accordingly, code block is given below:
IF EXISTS (SELECT 1 FROM TableName AS t
WHERE t.Column1 = @ Column1
AND t.Column2 = @ Column2)
BEGIN
RAISERROR(‘Duplicate records’,18,1)
END
ELSE
BEGIN
INSERT INTO TableName (Column1, Column2, Column3)
SELECT @ Column1, @ Column2, @ Column3
END
2. Also you can create UNIQUE INDEX or UNIQUE CONSTRAINT on the column of a table, when you try to INSERT a value that conflicts with the INDEX/CONSTRAINT, an exception will be thrown. 
Add the unique index:
CREATE UNIQUE INDEX Unique_Index_name ON TableName(ColumnName)
Add the unique constraint:
ALTER TABLE TableName
ADD CONSTRAINT Unique_Contraint_Name
UNIQUE (ColumnName)
Thanks
Lydia Zhang

Similar Messages

  • How do i check ensure that SAP checks for duplicate vendor invoice numbers?

    Hi Experts -
    How do I verify that SAP checks for duplicate vendor invoice numbers and blocks duplicate invoices from being paid?
    Thanks!

    Hi
    Pls chek the settigs by following the path
    IMG>Materials Management>Logistics Invoice Verification>Incoming Invoice>Set Check for Duplicate Invoice.
    Here you make the settings for creating a duplicate invoice check.
    Moreever, in the vendor master, you need to tick the check box for duplicate invoice check.
    I suggest you search the Forums before posting a query. There are lots of postings on this issue.
    Thanks & regards
    Sanil K Bhandari

  • Problem in Set Check for Duplicate Invoices

    Hi,
    I have did all the required setting s for check duplicate invoice , but when i do miro , its not giving any error or warning msge.. i did all the config  as per blw link..
    FYI-  in migo, i have entered the 3434 as a invoice ref # in delveriy note column and while doing miro , i have entered 3434 in ref column and give the 3434 as a dlvery note # in item tab .. but its not giving any error?
    Pls guide, where the mistake has gone wrongly??
    Problem in Set Check for Duplicate Invoices
    Edited by: UJ on May 15, 2009 1:45 PM

    Hello,
    Hope you have done all the required configurations for the checking of double invoice and ticked the vendor for the double invoice checking in vendor master record.
    You have to understand the way the system does the double invoice check.
    As per the configuration, if the system identifies an invoice for a vendor whose double invoice check is activated, at the time of MIRO, system will update a separate table.
    So system will check for the double invoice entry among the invoices entered after making the tick in the vendor master.
    i meant to say that, if you are introducing this double invoice check in between the transactions, the check will be valid only for the invoices entered after the activation of double invoice check.
    Regards

  • Set Check for Duplicate Invoices.

    Hi,
    what is the difference if is set "<b>Set Check for Duplicate Invoices</b>"
    in MIRO?
    Best regards

    HI,
    This check will prevent incoming invoices being accidentally entered and paid more than once.
    You can choose whether to activate or deactivate the check criteria of company code, reference document number and invoice date for each company code. The more criteria that you activate, the lower the probability of the system finding a duplicate invoice.
    The company code check makes sense if you work with more than one company code.
    Depending on the reference document number entry, the system checks as follows:
    1. If you have entered a reference document number, the system checks whether the invoice matches in the following attributes:
    Company code
    Vendor
    Currency
    Invoice date
    Reference document number
    2. If you have not entered a reference document number, the system
    3. checks whether the invoice matches in the following attributes:
    Company code
    Vendor
    Currency
    Invoice date
    Amount in
    document currency
    Depending on the system settings, a warning message or an error message appears if the system finds an invoice that matches all attributes.
    Requirements
    The field Chk double inv. (Check for duplicate invoice) must be flagged on the Accounting view in the vendor master record.
    Regards
    Aasif

  • Does itunes check for duplicate purchases?

    I got a new version of itunes and I cannot have my purchased next to my new purchases.  Does itunes check for duplicates? Or are they happy to take your money?

    Maybe they will in a future update. Im not sure but I think they use to do this. IF they did Id say they stopped to make the record companys happy (And alittle richer)

  • Check for duplicate invoices and trigger a workflow

    Hello All,
        I have a requirement to check for duplicate invoices in AP(Accounts payable) and trigger a workflow when duplicate invoices are found. I a not sure how to do any of the above. Please  let me know if you have any information on:
    1) Checking for duplicate invoices in AP
    2) Trigger a workflow
    Are there any standard workflows that checks duplicate invoices?
    Thanks.
    --Mithun

    Hi MD,
    I doubt if system gives an error on FI side when a duplicate invoice is posted.
    I feel you would require a BAdi for it, where you can call your WF using FM SAP_WAPI_START_WORKFLOW.
    Hope it helps.
    Aditya
    P.S also ask your Func Consultants, if there are any settings in the Customization, where you could capture Inv Dt, Inv Amt, Vendor, Company code.
    Edited by: Aditya Varrier on Oct 15, 2008 9:38 AM

  • How can I check for duplicates in Apple Photos?

    Can't use my existing apps to check for duplicates in Apple Photos as they only work with iPhoto folders. Any ideas how I can get around this gap?
    OS X 10.10.3

    Duplicate Annihilator for Photos:  http://brattoo.com/propaganda/#photos
    PowerPhotos: http://www.fatcatsoftware.com/powerphotos/

  • GOS - check for duplicate Attachments

    Hi guys!
    Fianlly i managed it to add a URL to GOS in my abap program
    i used the following FMs
    CALL FUNCTION 'SO_FOLDER_ROOT_ID_GET'
    CALL FUNCTION 'SO_OBJECT_INSERT'
    CALL FUNCTION 'BINARY_RELATION_CREATE'
    So what i do is running an abap report in a batch job which adds me the necessary urls.
    Now i need to now how i can check for duplicates in the gos. In particular check if this link is already there or not?
    who knows?
    thanks!!

    thank you, that helps me alot.
    Just one last thing,
    How can i find the URL value (the link actually) now?
    thanks!

  • Checking for duplicate primary keys on row inserts

    Checking for duplicate primary keys on row inserts
    I have a situation where I will be making bulk table inserts knowing that the primary key value will in some cases already exist. In this is the case I simply want to ignore the duplicate inserts.
    Should I be performing a sub-query on the table and using a statement like:
    where not exist in
    Or is there a cleaner way of discarding or checking for duplicates on insert.
    My concerns were mainly one of performance, as my routine will be inserting a few thousand rows in its operation.

    The MERGE commnad is a good option when a large percentage of the data will exist in the target because it is much more efficient to attempt to update then insert when the update affects zero rows than capture an error and convert it to an update.
    However, since in this case it would appear that only a few rows will alreadys exist and we want to ignore the duplicates when they exist then
    begin
    insert
    exception
    when dup_value_in_index then null;
    end
    would be the way to code this one. The bulk insert version has in 9.2 the ability to store the errors so that they can all be handled at once which means the rest of the array insert can work.
    HTH -- Mark D Powell --

  • How to check for duplicates - with a twist?

    As I'm importing music from my CD collection, is there a way to automatically check for duplicates - with an unusual twist?
    I already imported about 70 CDs using AAC format.
    I just bought a huge external drive specifically for storing my entire collection of CDs and LPs. Now that I have lots of space, I want to import everything in Apple Lossless format.
    Is there an automatic (or at least painless) way to check for duplicates as I'm importing CDs, and to have the old AAC music files over written by the new Apple Lossless files?

    Hi Clinto,
    Do you see the column headers above in itunes? They say Title, Album, Artist, etc. I don't know if it's the same for MAC but in Windows, Right Click on the column headers and click "Kind". This will display the format each song is in. If your column headers already take up all of your screen, you're gonna have to uncheck one to make room for "kind".
    Oh! and to overwrite existing files, make sure the ID3 tags are filled exactly to the old ones prior to ripping, though you don't need to fill all of them. I think you just fill the Artist, Album Artist, Album, and Title. A window will appear as you start to rip. It will ask if you want to overwrite the existing files, click "Yes". Again, don't know about Mac but it works this way in Windows.
    Message was edited by: fullcream

  • Authorization level check for Condition records.

    Hi,
    Hi Gurus,
    Pls help me out in the the following scenario.
    I want to activate Authorization level check for Condition records.
    For example, Product price PR00 is being entered by first level.
    After verification done by second level only, that condition record to be used for sales order processing.
    I have gone through Process status & Release Status. But once it is Blocked  i am not able to release it...
    Rgds,
    Amol

    Amol,
    Please confirm transaction code you are using in this scenario to release. I can help with this, just a little more detail.
    Thanks,
    Jay

  • How can I sync my contacts from the iPhone to google contacts while checking for duplicates?

    I have been using Outlook to sync contacts and it works well.  Now I would like to get rid of Outlook and put the contacts that I have into my gmail and Yahoo contact accounts and keep all 3 in sync.  When I do it the first time, I'd like to be able to check for duplicates.  Is there a way to do this?

    If you want your contacts to remain in sync across iOS devices, then you can use any Exchange-type of account.  For example, once you have a "clean" set of contacts with no duplicates, you could upload that into iCloud so that any change you make from your iPad would be reflected on your iPhone.  You don't have to use iCloud for e-mail since your devices can pull a contact from iCloud for use with GMail or Yahoo.
    But you can also set GMail up as an Exchange account if you don't want to use iCloud.  The GMail account type in iOS is not Exchange, but you can set it up that way:
    http://support.google.com/mobile/bin/answer.py?l=en&topic=14252&answer=138740
    The benefit of doing this is (a) your Google contacts remain in sync across all your devices, and (b) your GMail will then support Push notification.  Just one caveat, when you do this then the default behavior when you delete an e-mail is such that it is archived to your "All Mail" folder in GMail.  The only way to change this behavior is to use your device's Safari to navigate to m.google.com/sync and change the setting on Google's server for each of your devices.  This is a one-time thing, but important if you want trashed e-mails to really go to Trash.
    As far as Contact Management Software options to clean things up, Google search is the only recommendation I have

  • Form does not show "new" records from SQL Database

    I have a PDF form that pulls data from a SQL Server.  The fields in
    the PDF are populated from the database after selecting a specific
    record from a drop down and then clicking on a button labeled "Fill".
    The problem is that the dropdown does not display new records that
    have been recently added to the database.  I have to open the form up
    in designer then save it, (*note - I change nothing at this point.)
    Then when the form is opened back up in Adobe the dropdown show all
    the records including the new ones.  I even put a manual refresh on
    form to try and fix this an it did not help. Seriously stumped.
    Any help is greatly appreciated.
    Here is my code for the dropdown.
    ++++++++++++++++++++++++++++
    topmostSubform.Page1.JobSelect::initialize - (JavaScript, client)
    var sDataConnectionName = "BBCC"; // example - var sDataConnectionName
    = "Test";
    var sColHiddenValue = "ContractAdmin_Key"; // example - var
    sColHiddenValue = "Dept_ID";
    var sColDisplayText = "JobDescription"; // example - var
    sColDisplayText = "Dept_ID"
    // Search for sourceSet node which matchs the DataConnection name
    var nIndex = 0;
    while(xfa.sourceSet.nodes.item(nIndex).name != sDataConnectionName)
    nIndex++;
    var oDB = xfa.sourceSet.nodes.item(nIndex);
    oDB.open();
    oDB.first();
    // Search node with the class name "command"
    var nDBIndex = 0;
    while(oDB.nodes.item(nDBIndex).className != "command")
    nDBIndex++;
    // Backup the original settings before assigning BOF and EOF to stay
    var sBOFBackup =
    oDB.nodes.item(nDBIndex).query.recordSet.getAttribute("bofAction");
    var sEOFBackup =
    oDB.nodes.item(nDBIndex).query.recordSet.getAttribute("eofAction");
    oDB.nodes.item(nDBIndex).query.recordSet.setAttribute("stayBOF",
    "bofAction");
    oDB.nodes.item(nDBIndex).query.recordSet.setAttribute("stayEOF",
    "eofAction");
    // Clear the list
    this.clearItems();
    // Search for the record node with the matching Data Connection name
    nIndex = 0;
    while(xfa.record.nodes.item(nIndex).name != sDataConnectionName)
    nIndex++;
    var oRecord = xfa.record.nodes.item(nIndex);
    // Find the value node
    var oValueNode = null;
    var oTextNode = null;
    for(var nColIndex = 0; nColIndex < oRecord.nodes.length; nColIndex++)
    { if(oRecord.nodes.item(nColIndex).name == sColHiddenValue)
    { oValueNode = oRecord.nodes.item(nColIndex); } else
    if(oRecord.nodes.item(nColIndex).name == sColDisplayText) { oTextNode
    = oRecord.nodes.item(nColIndex); } }
    while(!oDB.isEOF())
      this.addItem(oTextNode.value, oValueNode.value);
       oDB.next();
    // Restore the original settings
    oDB.nodes.item(nDBIndex).query.recordSet.setAttribute(sBOFBackup,
    "bofAction");
    oDB.nodes.item(nDBIndex).query.recordSet.setAttribute(sEOFBackup,
    "eofAction");
    // Close connection
    oDB.close();
    ++++++++++++++++++++++
    Here is code for the refresh button
    +++++++++++++++++++++
    topmostSubform.Page1.Button27::click - (JavaScript, client)
    sourceSet.BBCC.requery();
    +++++++++++++++++++++

    pguerett wrote:
    The other thing that might be happening is a refresh issue on the DropDownList. Try adding the command xfa.layout.relayout() after the database connection has been closed.
    Paul
    Good catch Paul!  Would you believe that I have been trying to get this resolved for almost two years! Works perfect now.
    Thank you,
      - Eric

  • Button for next recording in the database

    Hello,
    I currently testing Adobe LiveCycle to create a PDF form with data link to a database (Access).
    The goal of my form is for the manager of each of our site to write variable about the paycheck of each employe. So first I create my AccessDatabase with a simple structure :
    N : Auto Number
    Matricule : Employe ID
    Nom : Name
    Prenom : First Name
    Service : Service (Accounting...)
    HeureMensuelBase : Contract hour information for the mouth
    HeureSemBase : Contract hour information for the week
    Mois : Mouth
    Annee : Year
    NbrHeureMensuelW : Write the number of hour the employe work this mouth
    NbrHeureSupp25pc : Extra hour paid 25% more
    NbrHeureSupp50pc : Extra hour paid 50% more
    NbrHeureSupp100pc : Extra hour paid 100% more
    NomPrime : Name of a special gratification
    MontantPrime : Amount of a special gratification
    So after, I create my ODBC connexion and insite AdobeLiveCycle, Data View, Create a connexion > Next > ODBC String connexion > SQL Request > SELECT * FROM Table_Access; > Next > Finish. Great I retreive all my fields. If I preview the PDF I can correctly see the first record of my database.
    My goal is to create two differents buttons to navigate inside :
    NEXT with the follow code :
    formulaire1.#subform[0].Next::click - (JavaScript, client)
    xfa.sourceSet.DataConnection.next();
    PREV with the follow code :
    formulaire1.#subform[0].Prev::click - (JavaScript, client)
    xfa.sourceSet.DataConnection.previous();
    If i try to preview it, unfortunatly no button works.
    I follow this video : http://www.youtube.com/watch?v=C56_Cz-aE0c
    I  see the Adobe FAQ too : http://help.adobe.com/en_US/livecycle/11.0/DesignerHelp/WS107c29ade9134a2c-1f4d3e3c12a7df3 f73e-8000.2.html
    Could help me ? Adobe Support don't want help me because I use a trial version for the moment (logical because my CTO wan't valide LiveCycle do the job before paid for it). Sorry for my english it's not my mother tongue.

    I'm not alone in the same situation : http://forums.adobe.com/thread/793214
    Please support help us

  • Checking of duplicate record

    am wondering how to write code that will check the new item if it is already existing in the table before it can be inserted...am just new in forms. thanks.

    According to online help, CHECK_RECORD_UNIQUENESS is only valid from the On-Check-Unique trigger and only performs what Forms does by default -- checks if the record has already been inserted into the table. Just set the Enforce Primary Key property to Yes for the block, and this happens automatically.
    If you want to check right after the user enters the primary key for a new record, you can do it in the When-Validate-Item trigger:
    declare
       record_count number := 0;
    begin
       select count(*) into record_count from <tablename>
       where <primary_key_column> = :<block.primary_key>;
       if record_count > 0 then
          message('This record is already in the database.');
          raise form_trigger_failure;
       end if;
    end;

Maybe you are looking for

  • HP Color Laserjet 4700 and HP Designjet 5000PS

    I've been working for 4 days trying to get these 2 printers to work in Snow Leopard to no avail. I've Reset, Reinstalled several times. The 4700 will never install and Designjet installs, but will never communicate and print. I also have a HP Laserje

  • Live! Drive II and X-Fi Music Extr

    Similiar to the Audigy Li've Dri've post... I have connected my old SB Li've! Dri've II to my new SB X-Fi Music Extreme sound card. I connect headphones to the headphone jack but do not get any sound, nor can i hear anything inpit via microphone. (So

  • Hierarchy VIewer - Card only on Leaf nodes

    I am using version 11.1.2.3.0. Is there a way to show a Card only on the leaf nodes of the Hierarchy VIewer? I have information that only applies to the nodes on the very bottom of the tree. Thanks in advance.

  • GAL and Generational Qualifier Attribute

    Hi, I have added a generational qualifier to Active Directory using set-ADObject -identity 'CN=Sean Kelly,OU=Calgary,OU=RJC Users,DC=rjc,DC=local' -Replace @{generationQualifier='A+'} Checking to make sure it is in there I used: Get-ADUser skelly -Pr

  • Photoshop Elements Help | Convert a trial version into a full version

    This question was posted in response to the following article: http://helpx.adobe.com/photoshop-elements/getting-started/convert-trial-version.html