Select Into Explanation / Temporary Tables

15.5k views Asked by At

Based on the tutorial on SQL Temporary Tables, it should be OK to create a temp table by using SELECT * INTO #tempTable FROM tableA but it's throwing me SQLException when I trying to SELECT * FROM #tempTable saying that Invalid object name '#tempTable'. May I know what's the proper way of using a temp table in C#?

string sql = "SELECT * INTO ##tempTable FROM (SELECT * FROM tableA)";
using (var command = new SqlCommand(sql, connection))
{
    string sqlNew = "SELECT * FROM ##tempTable";
    using (var command2 = new SqlCommand(sqlNew, connection))
    {
        using (var reader = command2.ExecuteReader())
        {
            while (reader.Read())
            {
                Console.WriteLine(reader["column1"].ToString());

            }
            Console.ReadLine();
        }
    }
}

My Objective is tryint to using the data retrieved from sqlVar and insert them into a tempTable and perform some operation on it. Very much appreciated if there is some sample code on how to fit the code into the above code. Thank You.

5

There are 5 answers

2
Dhaval On BEST ANSWER

But why you need temp table at SQL server side..

1) if you wish to perform operation on C# side just take data in DATASET instead of DATAREADER .. and

 DataSet dataset = new DataSet();
 using (SqlConnection conn = new SqlConnection(connString))
 {
     SqlDataAdapter adapter = new SqlDataAdapter();                
     adapter.SelectCommand = new SqlCommand("select * from tableA", conn);
     conn.Open(); 
     adapter.Fill(dataset);
     conn.Close(); 
     foreach (DataRow row in dataset.Tables[0]) // Loop over the rows.
    {
        // perform your operation
    }
 }  

2) if you need to perform operation on SQL side then create a stored procedure at SQL server .. in the stored procedure create #table and use it ..

3) and you do not want to create DATASET then you can take data LIST and perform your operation on C# side

0
Thorsten Dittmar On

You are not executing the first command at all, so the SELECT INTO isn't executed, so the temporary table is not created, so you get an error about the table not existing.

The code should read:

string sql = "SELECT * INTO ##tempTable FROM (SELECT * FROM tableA)";
using (var command = new SqlCommand(sql, connection))
{
    command.ExecuteNonQuery(); // <-- THIS

    string sqlNew = "SELECT * FROM ##tempTable";
    using (var command2 = new SqlCommand(sqlNew, connection))
    {
        using (var reader = command2.ExecuteReader())
        {
            while (reader.Read())
            {
                Console.WriteLine(reader["column1"].ToString());

            }
            Console.ReadLine();
        }
    }
}
3
Nadeem_MK On

Change your temp table from #tempTable to ##tempTable.

Using ## means a global temp table that stays around. You'll need to Drop it after you have completed your task.

If Exists(Select * from tempdb..sysobjects Where id = object_id('tempdb.dbo.#tempTable'))

DROP TABLE #tempTable 
3
Yosi Dahari On

I think your answer is in the comment:

Temporary tables available during the session that creates them.

If you want to actualy get the data you have to perform a SELECT statement from this temporary table within the same scope.

One more thing:

I don't see you are executing the var command, you are missing this line:

string sql = "SELECT * INTO ##tempTable FROM (SELECT * FROM tableA)";
using (var command = new SqlCommand(sql, connection))
{
    command.ExecuteNonQuery();// This line is missing..
    string sqlNew = "SELECT * FROM ##tempTable";
    using (var command2 = new SqlCommand(sqlNew, connection))
    {
        using (var reader = command2.ExecuteReader())
        {
            while (reader.Read())
            {
                Console.WriteLine(reader["column1"].ToString());

            }
            Console.ReadLine();
        }
    }
}

But missing the line isn't the reason why your implementation is wrong..

0
Yousri Mousa On

1-SELECT * INTO # tempTable FROM tableA (local temp)or 2-SELECT * INTO ## tempTable FROM tableA (global temp)then

Local temp tables are only available to the current connection for the user; and they are automatically deleted when the user disconnects from instances. Local temporary table name is stared with hash ("#") sign.

Global Temp Table

Global Temporary tables name starts with a double hash ("##"). Once this table has been created by a connection, like a permanent table it is then available to any user by any connection. It can only be deleted once all connections have been closed.

Both, Temporary tables are stored inside the Temporary Folder of tempdb. Whenever we create a temporary table, it goes to Temporary folder of tempdb database.

temp table in SQL DB