我正在编写的程序的一部分运行一些T-SQL代码。程序将继续循环运行,直到我停止它。当它第一次运行时没有问题。当它第二次运行时,我在尝试运行T-SQL代码时遇到错误。它表示代码创建的临时表之一已存在于数据库中。代码在尝试将记录插入临时表之前,会删除临时表。我不知道我是否在T-SQL代码中正确配置了它,或者它是否无法运行丢弃表的T-SQL代码(如果存在)。我还尝试将表格放在c#代码中,这是我尝试的内容:
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();
这是我收到的错误消息:
There is already an object named '#temp850' in the database.
有人可以帮忙吗?
答案 0 :(得分:0)
如果要在SQL中使用C#中的事务,则可以使用以下示例。
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);
}
}
}
}
答案 1 :(得分:0)
在创建临时表之前,只需放置以下SQL语句
CountVectorizer
答案 2 :(得分:0)
在sql上,您无法在同一查询中多次创建相同的临时表。
您可以在创建它之前每次删除#temp85表:
更改此行:
string cmdText = @"BEGIN TRANSACTION; DROP TABLE IF EXISTS #temp850; COMMIT TRANSACTION;";
**我认为这不是删除临时表的方法
为此:
string cmdText = @"BEGIN TRANSACTION; if (OBJECT_ID('tempdb..#temp850')>0) drop table #temp850; COMMIT TRANSACTION;";