通过ODBC进行事务和多个查询

时间:2012-11-22 13:44:50

标签: c# sql-server-2008 tsql odbc

我有一个接口,通过ODBC连接触发多个SQL查询。

这些查询创建函数,存储过程,执行存储过程等。

如果其中一个失败,我想要完全回滚开始。

begin transaction之后查询commit transactionbegin transaction的简单计划会导致{{1}}之后的运行时错误,因为此时不会触发任何提交。

是否有可能在一堆查询周围放置一个事务块?

1 个答案:

答案 0 :(得分:3)

是的,你可以。 我假设您的意思是进行插入或更新各种sql语句(而不是选择查询)。 在进行此类操作之前,您应该记住,如果它们与您在查询之间设置的新数据没有关系,则只在单个事务中运行查询。这是因为新数据尚未提交,因此您无法在下一个语句中使用is。

这是一个使用事务运行一组命令的代码。

    /// <summary>
    /// Execute commands with an open SQL connection.
    /// Note: To execute a stored procedure send to useTransaction parameter false value
    /// </summary>
    /// <param name="connection">An opened SqlConnection</param>
    /// <param name="commands">A string array of the requested commands to execute</param>
    /// <param name="useTransaction">true if to force transaction, false to execute the commands without transaction</param>
    /// <returns>true for success, otherwise false</returns>
    public static bool ExecuteSqlCommands(SqlConnection connection, string[] commands, bool useTransaction)
    {
        bool bStatus = false;

        string[] lines = commands; // regex.Split(sql);

        SqlTransaction transaction = null;
        if (useTransaction)
            transaction = connection.BeginTransaction();
        using (SqlCommand cmd = connection.CreateCommand())
        {
            cmd.Connection = connection;
            if (useTransaction)
                cmd.Transaction = transaction;

            foreach (string line in lines)
            {
                if (line.Length > 0)
                {
                    cmd.CommandText = line;
                    cmd.CommandType = CommandType.Text;

                    try
                    {
                        cmd.ExecuteNonQuery();
                    }
                    catch (SqlException e)
                    {
                        string msg = e.Message;
                        if (useTransaction)
                            transaction.Rollback();
                        throw;
                    }
                }
            }
            bStatus = true;
        }
        if (bStatus && useTransaction)
            transaction.Commit();

        return bStatus;
    }
相关问题