Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6865897
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T03:06:40+00:00 2026-05-27T03:06:40+00:00

I need to delete some records from table and then insert some records to

  • 0

I need to delete some records from table and then insert some records to the same table. This delete and insert process should be in transaction.

Below is what i did.

 using (SqlConnection sqlConn = new SqlConnection(connectionString))
        {
            sqlConn.Open();
            using (SqlTransaction sqlTran = sqlConn.BeginTransaction())
            {
                string deleteQuery = "delete from dbo.MyTable where Col1 =" + colValue;
                SqlCommand sqlComm = new SqlCommand(deleteQuery, sqlConn,sqlTran);
                sqlComm.ExecuteNonQuery();
                using (SqlBulkCopy sqlcopy = new SqlBulkCopy(sqlConn, SqlBulkCopyOptions.Default, sqlTran))
                {
                    sqlcopy.BatchSize = 10;
                    sqlcopy.DestinationTableName = "MyTable";
                    try
                    {
                        sqlcopy.WriteToServer(dsDataSet.Tables[0]);
                        sqlTran.Commit();
                    }
                    catch (Exception ex)
                    {
                        sqlTran.Rollback();
                    }
                }
            }
        }

But, i guess as the delete operation is not getting performed before insert, i get duplicate key errors. Can some one help.?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T03:06:41+00:00Added an answer on May 27, 2026 at 3:06 am

    I tried your sample code, and it seemed to work for me. I created a PK on one of the columns to make sure a duplicate insert would throw an error. Then I run the code twice — the first time through it puts in some dummy data (no errors thrown), the second time through it tries to delete the data and then reinsert within the same transaction. From your question, I was hoping to get an exception the 2nd time through but it worked. Not sure it matters, but I am running SQL Server 2008 R2 SP1.

    Here is the complete test code which I used, perhaps it will help you identify your issue.

    First the SQL to create a sample table:

    CREATE TABLE [dbo].[MyTable](
        [Col1] [nvarchar](20) NOT NULL,
        [Col2] [nvarchar](20) NULL,
        [Col3] [nvarchar](30) NULL,
        CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED 
        (
            [Col1] ASC
        )
    )
    

    And the C#:

    public static void Main()
    {
        DataTable t = new DataTable();
        t.Columns.Add(new DataColumn("Col1"));
        t.Columns.Add(new DataColumn("Col2"));
        t.Columns.Add(new DataColumn("Col3"));
        for (int i = 0; i < 5; i++)
        {
            var r1 = t.NewRow();
            r1["Col1"] = "1" + i.ToString();
            r1["Col2"] = "2" + i.ToString();
            r1["Col3"] = "3" + i.ToString();
            t.Rows.Add(r1);
        }
        t.AcceptChanges();
        var connectionString = new SqlConnectionStringBuilder();
        connectionString.DataSource = "localhost";
        connectionString.InitialCatalog = "testdb";
        connectionString.IntegratedSecurity = true;
    
        using (SqlConnection sqlConn = new SqlConnection(connectionString.ToString()))
        {
            sqlConn.Open();
            using (SqlTransaction sqlTran = sqlConn.BeginTransaction())
            {
                string deleteQuery = "delete from MyTable"; // just delete them all
                SqlCommand sqlComm = new SqlCommand(deleteQuery, sqlConn, sqlTran);
                sqlComm.ExecuteNonQuery();
                using (SqlBulkCopy sqlcopy = new SqlBulkCopy(sqlConn, SqlBulkCopyOptions.Default, sqlTran))
                {
                    sqlcopy.BatchSize = 10;
                    sqlcopy.DestinationTableName = "MyTable"; 
                    try
                    {
                        sqlcopy.WriteToServer(t);
                        sqlTran.Commit();
                    }
                    catch (Exception ex)
                    {
                        sqlTran.Rollback();
                    }
                }
            }
        }
    
    }
    

    Update on your question
    By the way, you didn’t get an error because 11/23/2011 was evaluated as a math expression (‘/’ is division), resulting in the value 0, which was then implicitly cast to a datetime as 1900/01/01. Try running the query “select CONVERT(datetime, 11/23/2011)” and you will see what I mean.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need to delete some Unicode symbols from the string 'بِسْمِ اللَّهِ الرَّحْمَٰنِ الرَّحِيمِ'
I am trying to write some SQL to automatically delete some records from the
I've got a table which has about 5.5 million records. I need to delete
i have one property file which contains some records so i need to delete
Whoops, I need some info from a file I deleted, a while ago. In
I need to delete a temporary file from my C++ windows application (developed in
I need to delete files of a certain type (.zip files, say) from a
I need to delete the latest browser history entry for this reason , but
I need to delete a file. Occasionally, the file may be locked, in this
I need to delete an option from a select in certain circumstances. Basically: if(mystatement

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.