有一個控制檯應用程序,我有一個sql select語句和一些內部連接。我希望此語句的每個結果都能更新這些表中的某一列與使用C#的新值。如何遍歷SQL select語句結果並更新特定表
這裏我已經嘗試過:
using System;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
namespace MyProgram
{
class Program
{
private static SqlConnection _connection;
private static SqlTransaction _transaction;
static void Main(string[] args)
{
using (var connection = new SqlConnection())
{
try
{
connection.ConnectionString = ConfigurationManager.ConnectionStrings["myConfig"].ConnectionString;
connection.Open();
_connection = connection;
using (var command = connection.CreateCommand())
{
command.CommandText =
"My Select sql stament with inner joins";
using (var reader = command.ExecuteReader())
{
var indexOfColumn3 = reader.GetOrdinal("IDExtObject");
while (reader.Read())
{
_transaction = _connection.BeginTransaction("UpdateTransaction");
command.Transaction = _transaction;
var extId = reader.GetValue(indexOfColumn3).ToString();
string finalId = "Something new...";
try
{
UpdateIdSqlTransaction(extId, finalId);
_transaction.Commit();
}
catch (Exception)
{
_transaction.Rollback();
}
}
}
}
}
catch (Exception)
{
if (_transaction != null)
_transaction.Rollback();
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
}
Console.ReadLine();
}
private static void UpdateIdSqlTransaction(string objectId, string newId)
{
using (_connection)
{
SqlCommand command = _connection.CreateCommand();
command.Connection = _connection;
var commandText = "The update SQL statement...";
command.CommandText = commandText;
command.Parameters.AddWithValue("@ID", objectId);
command.Parameters.AddWithValue("@newId", newId);
command.ExecuteNonQuery();
}
}
}
}
的問題是,我得到這個異常:
{「新的事物是不允許的,因爲有在運行的其他線程會議。「}
什麼問題,我該如何實現這一目標?
你可以把這個「command.Transaction = _transaction;」 ExecuteReader語句之前? – FakeisMe
爲什麼你需要在這裏進行交易?如果您的更新語句是單個語句,則它失敗或通過。您期望處理多少條記錄?您可以讀取所有的ID然後運行更新循環。你能計算出服務器上的新值嗎?在這種情況下,您可以將更新作爲單個語句運行。 –
Look @SergeyL我想啓動進程,如果有任何記錄失敗,我希望整個事務回滾。 –