CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7
  1. #1
    Join Date
    May 2012
    Posts
    3

    SQL DB Transaction fails when executing INSERT after DELETE, on duplicated PK

    Hi,

    Your help is very much appreciated.


    When running a DELETE and then INSERT (BULK INSERT) sql commands , I am receiving an error
    “Cannot insert duplicate key”.

    It seems like the DELETE doesn’t actually delete the records, and therefore the INSERT fails.


    [Framework 4.0, SQL Server 2008].

    Heres' the code I'm using:
    Code:
    public static bool RunInTransInternal(List<SqlCommand> cmds, string conn)
            {
                try
                {
                    using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew,
                        new TransactionOptions()
                        {
                            IsolationLevel = System.Transactions.IsolationLevel.Serializable,
                            Timeout = TimeSpan.FromHours(2)
                        }))
                    {
                        using (SqlConnection connection1 = new SqlConnection(conn))
                        {
                            connection1.Open();
                            for (i = 0; i < cmds.Count; i++)
                            {
                                cmds[i].Connection = connection1;
                                cmds[i].CommandTimeout = 36000;
                                cmds[i].ExecuteNonQuery();
                            }
                        }
                        scope.Complete();
    
                    }
                }
    
                catch (Exception ex)
                {
                    return false
                }
    
                return true;
            }
    Cheers
    Roy
    Last edited by BioPhysEngr; May 3rd, 2012 at 12:42 AM. Reason: add code tags

  2. #2
    Join Date
    Feb 2011
    Location
    United States
    Posts
    1,016

    Re: SQL DB Transaction fails when executing INSERT after DELETE, on duplicated PK

    A little out of my expertise here, but perhaps you need to execute two transactions? One to commit the deletes and another to commit the updates?

    Kind of just a guess though. Someone know better?
    Best Regards,

    BioPhysEngr
    http://blog.biophysengr.net
    --
    All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

  3. #3
    Join Date
    May 2012
    Posts
    3

    Re: SQL DB Transaction fails when executing INSERT after DELETE, on duplicated PK

    Yes, if the DELETE and INSERT run separately (not within the same transaction), the INSERT will succeed.

    However, I want to maintain data integrity, hence running both in one transaction

    (i.e. if the INSERT fails, I don't want to DELETE to execute..)

  4. #4
    Join Date
    Feb 2011
    Location
    United States
    Posts
    1,016

    Re: SQL DB Transaction fails when executing INSERT after DELETE, on duplicated PK

    Never hurts to ask! :-)

    Other stupid question: where is cmds assigned? Is every delete at a lower index in the list than every insert?

    Second idea: you can use the INSERT ... ON DUPLICATE KEY ... syntax; see e.g.: https://dev.mysql.com/doc/refman/5.0...duplicate.html
    Best Regards,

    BioPhysEngr
    http://blog.biophysengr.net
    --
    All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

  5. #5
    Join Date
    Jul 2007
    Location
    In the present
    Posts
    80

    Thumbs down Re: SQL DB Transaction fails when executing INSERT after DELETE, on duplicated PK

    Why not just set conditions tests?

    Code:
    private void ExecuteQuery()
    {
    	if(DeleteRecord)
    	{
    		InsertRecord();
    	}
    	else
    	{
    		MessageBox.Shoe("Can Not Complete");
    		
    	}
    
    }
    
    public bool DeleteRecord()
    {
    	try
    	{
    		//Deleting Record
    		return true;
    	}
    	catch
    	{
    		return false;
    	}
    }
    
    private void DeleteRecords()
    {
    	//DeleteRecords here
    }
    
    private void InsertRecords()
    {
    	//Insert the Records Here
    }

  6. #6
    Join Date
    Feb 2011
    Location
    United States
    Posts
    1,016

    Re: SQL DB Transaction fails when executing INSERT after DELETE, on duplicated PK

    Good thought, forgotten, but if the insert should fail, the delete should also fail. Thus, there must be some way of bundling them together in the same transaction...
    Best Regards,

    BioPhysEngr
    http://blog.biophysengr.net
    --
    All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

  7. #7
    Join Date
    May 2012
    Posts
    3

    Re: SQL DB Transaction fails when executing INSERT after DELETE, on duplicated PK

    Thanks guys,

    I can see two options here:


    1. Using a temp table (separate table where you copy rows you are about to delete. Perform copy and delete in transaction so if inserting to copy table fails or deleting from source table fails then you can rollback that transaction and no harm is done)

    2. UPSERT in SQL SERVER 2008
    http://blog.dezfowler.com/2011/05/bu...-from-net.html
    http://www.databasejournal.com/featu...erver-2008.htm
    http://blogs.msdn.com/b/cellfish/arc...rver-2008.aspx

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured