临时表如何在事务之前创建然后使用内部事务

时间:2010-09-03 10:33:05

标签: c# sql temp-tables

我在c#中编写代码。

我想在事务开始之前创建临时表,然后在事务中使用它,但是当我尝试这样做时,我在事务中得到错误,它表示“表不存在”。这样做的正确方法是什么?

SqlConnection sqlConnection = new SqlConnection( "connstring" );
sqlConnection.Open();

string temp = string.Format( "CREATE TABLE dbo.#temp (id INT);" );
DbCommand command = database.GetSqlStringCommand( temp );
database.ExecuteNonQuery( command ); //here is the problem when I add argument , transaction it works
//fill data in temporary table
//...
// open transaction
SqlTransaction transaction = sqlConnection.BeginTransaction();

//Here I try to read from temp table I have some DbCommand readCommand
database.ExecuteNonQuery( readCommand, transaction ); 

2 个答案:

答案 0 :(得分:2)

如何只是重新排序语句,以便在事务中创建表:

SqlConnection sqlConnection = new SqlConnection( "connstring" );
sqlConnection.Open();

// open transaction
SqlTransaction transaction = sqlConnection.BeginTransaction();

string temp = string.Format( "CREATE TABLE dbo.#temp (id INT);" );
DbCommand command = database.GetSqlStringCommand( temp );
database.ExecuteNonQuery( command, transaction  ); //here is the problem when I add argument , transaction it works

//Here I try to read from temp table I have some DbCommand readCommand
database.ExecuteNonQuery( readCommand, transaction ); 

答案 1 :(得分:2)

以下代码完美无缺。

    static void Main(string[] args)
    {
        string conStr = "Integrated Security=true;Initial Catalog=sushma;server=(local)";

        SqlConnection sqlConnection = new SqlConnection(conStr);
        sqlConnection.Open();

        SqlCommand DbCommand = new SqlCommand("CREATE TABLE dbo.#temp (id INT);", sqlConnection);
        DbCommand.ExecuteNonQuery();

        SqlTransaction transaction = sqlConnection.BeginTransaction();
        DbCommand.CommandText = "SELECT * FROM dbo.#temp";
        DbCommand.Transaction = transaction;
        SqlDataReader dr = DbCommand.ExecuteReader();
        dr.Close();            

        transaction.Commit();
        Console.WriteLine("what is the issue");
        Console.ReadKey();
    }