SqlTransaction transaction = cnnGlobal.BeginTransaction(IsolationLevel.Serializable);//cnnGlobal is connection
try
{
SqlCommand cmdMaster = new SqlCommand(sql, cnnGlobal);//sql is sql command
cmdMaster.Transaction = transaction;
cmdMaster.ExecuteNonQuery();
SqlCommand cmdDetails;
for (int i = 0; i <>
{
cmdDetails = new SqlCommand(sql, cnnGlobal);
cmdDetails.Transaction = transaction;
cmdDetails.ExecuteNonQuery();
}
transaction.Commit();
transaction = null;
cmdMaster.Dispose();
cmdDetails.Dispose();
}
catch
{
if (transaction != null)
{
transaction.Rollback();
transaction = null;
}
}
other example :
static void Main(string[] args)
{
string insertQuery =
@"INSERT TESTTABLE (COLUMN1, COLUMN2) " +
"VALUES(@ParamCol1, @ParamCol2)";
using (SqlConnection connection =
new SqlConnection(connectionString))
{
using (SqlCommand command =
connection.CreateCommand())
{
SqlTransaction transaction = null;
try
{
// BeginTransaction() Requires Open Connection
connection.Open();
transaction = connection.BeginTransaction();
// Assign Transaction to Command
command.Transaction = transaction;
for (int i = 0; i < 100; i++)
CommandExecNonQuery(command, insertQuery,
new SqlParameter[] {
new SqlParameter("@ParamCol1", i),
new SqlParameter("@ParamCol2", i.ToString()) });
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
finally
{
connection.Close();
}
}
}
}
No comments:
Post a Comment