CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7

Threaded View

  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

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