简体   繁体   中英

Programmatically using c# drop a SQL Server 2016 table

A part of my program I am writing runs a some T-SQL code. The program will keep running in a loop until I stop it. When it runs through the first time there are no problems. When it runs through a second time I get an error when it tries to run the T-SQL code. It says that one of the temp tables the code creates already exists in the database. The code, before it tries to insert records into the temp table, drops the temp table. I don't know if I have it configured correctly in the T-SQL code or if its just not possible to run T-SQL code that drops a table if it exists. I also tried to drop the table within the c# code, here's what I tried:

cn.Open();
string cmdText = @"BEGIN TRANSACTION; DROP TABLE IF EXISTS #temp850; COMMIT TRANSACTION;";                
SqlCommand command = new SqlCommand(cmdText, cn);
command.CommandType = CommandType.Text;
command.ExecuteNonQuery();
cn.Close();

and here's the error message I get:

There is already an object named '#temp850' in the database.

Can someone help?

If you want to use transactions in C# for your SQL, then you can use the following example.

private static void ExecuteSqlTransaction(string connectionString)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();

        SqlCommand command = connection.CreateCommand();
        SqlTransaction transaction;

        // Start a local transaction.
        transaction = connection.BeginTransaction("SampleTransaction");

        // Must assign both transaction object and connection
        // to Command object for a pending local transaction
        command.Connection = connection;
        command.Transaction = transaction;

        try
        {
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
            command.ExecuteNonQuery();
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
            command.ExecuteNonQuery();

            // Attempt to commit the transaction.
            transaction.Commit();
            Console.WriteLine("Both records are written to database.");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
            Console.WriteLine("  Message: {0}", ex.Message);

            // Attempt to roll back the transaction.
            try
            {
                transaction.Rollback();
            }
            catch (Exception ex2)
            {
                // This catch block will handle any errors that may have occurred
                // on the server that would cause the rollback to fail, such as
                // a closed connection.
                Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
                Console.WriteLine("  Message: {0}", ex2.Message);
            }
        }
    }
}

Just place the following SQL statement before you create a temp table

IF OBJECT_ID('tempdb..#temp850') IS NOT NULL DROP TABLE #temp850
GO

SELECT 1 col1 INTO #temp850

On sql you can not create the same temp table more than once in the same query.

You could delete the #temp85 table every time before create it:

Change this line:

string cmdText = @"BEGIN TRANSACTION; DROP TABLE IF EXISTS #temp850; COMMIT TRANSACTION;";       

**I think thats is not the way for delete temporary tables

For this:

string cmdText = @"BEGIN TRANSACTION; if (OBJECT_ID('tempdb..#temp850')>0) drop table #temp850; COMMIT TRANSACTION;";        

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM