12

I'm creating a temporary table, #ua_temp, which is a subset of regular table. I don't get an error, but when I try to SELECT from #ua_temp in the second step, it's not found. If I remove the #, a table named ua_temp is created.

I've used the exact same technique from created the table with SELECT INTO elsewhere. It runs fine, so I don't think it has anything to do with database settings. Can anyone see the problem?

        // Create temporary table 
        q = new StringBuilder(200);
        q.Append("select policy_no, name, amt_due, due_date, hic, grp, eff_dt, lis_prem, lis_grp, lis_co_pay_lvl, ");
        q.Append("lep_prem, lapsed, dn_code, [filename], created_dt, created_by ");
        q.Append("into #ua_temp from elig_ua_response ");
        q.Append("where [filename] = @fn1 or [filename] = @fn2 ");
        sc = new SqlCommand(q.ToString(), db);
        sc.Parameters.Add(new SqlParameter("@fn1", sFn));
        sc.Parameters.Add(new SqlParameter("@fn2", sFn2));
        int r = sc.ExecuteNonQuery();
        MessageBox.Show(r.ToString() + " rows");

        // Rosters
        q = new StringBuilder(200);
        q.Append("select policy_no,name,amt_due,due_date,hic,grp,eff_dt,");
        q.Append("lis_prem,lis_grp,lis_co_pay_lvl,lep_prem,lapsed,dn_code,[filename] ");
        q.Append("from #ua_temp where (lis_prem > 0.00 or lep_prem > 0.00) ");
        q.Append("and [filename] = @fn order by name");
        sc.CommandText = q.ToString();
        sc.Parameters.Clear();
        sc.Parameters.Add(new SqlParameter("@fn", sFn));
        sda = new SqlDataAdapter(sc);
        sda.Fill(ds, "LIS LEP Roster");

To answer some of the obvious questions: This program was running fine using the source table, elig_ua_response. The reason for introducing the temp table was that I want to delete some of the rows for this particular report. I put brackets around the column [filename] while testing to be sure it's not a key word issue. The second SELECT works fine if you replace #ua_temp with elig_ua_response. I've tried different names for the temp table. The MessageBox showing the number of rows was just for debugging purposes; it doesn't affect the problem.

7
  • Run SQL Server Profiler, there is a column SPID. If the two statements have different SPID's then you know it is a scoping issue. Jul 8, 2011 at 20:22
  • Client Process ID is the same, SPID is the same.
    – SeaDrive
    Jul 8, 2011 at 20:36
  • can you copy the text out of the trace and run the two statements in management studio? Jul 8, 2011 at 20:43
  • I copied them into Sql Query Analyzer. The first one gave no error, but did not create the table, so the second one bombed. It worked OK with a ##global_temp.
    – SeaDrive
    Jul 8, 2011 at 20:52
  • It seems to be a problem in the create step, I tried taking the SqlParameters out of the first command, and the program ran OK.
    – SeaDrive
    Jul 8, 2011 at 21:00

9 Answers 9

13

Joe Zack's comment is what helped me understand what's happening here. A very clear and concise explanation. This should be an answer so that it's more visible to people arriving here from a google search.

SqlCommand calls sql with parameters via sp_executesql when there are parameters, which means your temp table gets created inside (and then clean up in) a stored procedure so it's not available to future calls - even when they share the same connection

1
  • yes - create your temp table in a command with no parameters. Then you can query it as much as you want in commands with parameters.
    – NYCdotNet
    Aug 15, 2020 at 14:31
11

I think the solution to your problem is to combine the creation of the temp table and selecting from that temp table into one query (see code snippet #3 below). Executing the command twice (as you do in the code in your question) seems to work ok if you are not using command parameters, but fails if they are introduced. I tested a few different approaches and here's what I found.

1) WORKS OK: Use same command object, no command parameters, execute command twice:

using (var conn = new SqlConnection("..."))
{
    conn.Open();
    using (var cmd = conn.CreateCommand())
    {
        const string query = @"
            CREATE TABLE #temp 
                ([ID] INT NOT NULL, [Name] VARCHAR(20) NOT NULL)
            INSERT INTO #temp VALUES(1, 'User 1')
            INSERT INTO #temp VALUES(2, 'User 2')";
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = query;
        cmd.ExecuteNonQuery();

        cmd.CommandText = "SELECT * FROM #temp";
        using (var sda = new SqlDataAdapter(cmd))
        {
            var ds = new DataSet();
            sda.Fill(ds);
            foreach (DataRow row in ds.Tables[0].Rows)
                Console.WriteLine("{0} - {1}", row["ID"], row["Name"]);
        }
    }
}

2) FAILS: Use same command object, command parameters, execute command twice:

using (var conn = new SqlConnection("..."))
{
    conn.Open();
    using (var cmd = conn.CreateCommand())
    {
        const string query = @"
            CREATE TABLE #temp 
                ([ID] INT NOT NULL, [Name] VARCHAR(20) NOT NULL)
            INSERT INTO #temp VALUES(1, @username1)
            INSERT INTO #temp VALUES(2, @username2)
        ";
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = query;
        cmd.Parameters.Add("@username1", SqlDbType.VarChar).Value ="First User";
        cmd.Parameters.Add("@username2", SqlDbType.VarChar).Value ="Second User";
        cmd.ExecuteNonQuery();

        cmd.Parameters.Clear();
        cmd.CommandText = "SELECT * FROM #temp";
        using(var sda = new SqlDataAdapter(cmd))
        {
            var ds = new DataSet();
            sda.Fill(ds);
            foreach(DataRow row in ds.Tables[0].Rows)
                Console.WriteLine("{0} - {1}", row["ID"], row["Name"]);
        }
    }
}

3) WORKS OK: Use same command object, command parameters, execute command once only:

using (var conn = new SqlConnection("..."))
{
    conn.Open();
    using (var cmd = conn.CreateCommand())
    {
        const string query = @"
            CREATE TABLE #temp 
                ([ID] INT NOT NULL, [Name] VARCHAR(20) NOT NULL)
            INSERT INTO #temp VALUES(1, @username1)
            INSERT INTO #temp VALUES(2, @username2)
            SELECT * FROM #temp
        ";
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = query;
        cmd.Parameters.Add("@username1", SqlDbType.VarChar).Value ="First User";
        cmd.Parameters.Add("@username2", SqlDbType.VarChar).Value ="Second User";
        using (var sda = new SqlDataAdapter(cmd))
        {
            var ds = new DataSet();
            sda.Fill(ds);
            foreach (DataRow row in ds.Tables[0].Rows)
                Console.WriteLine("{0} - {1}", row["ID"], row["Name"]);
        }
    }
}
3
  • Thanks for the effort. I'm going to try your third suggestion. I'll create a small temp table to hold the two parameters, then use a join to restrict the big table to the desired rows.
    – SeaDrive
    Jul 11, 2011 at 13:16
  • @SeaDrive You could also look into using EXISTS in your WHERE clause to avoid using the temp table entirely. I didn't put that in the answer because I was just trying to answer the question as asked. Good luck.
    – rsbarro
    Jul 11, 2011 at 13:23
  • It turns out option 3 does not meet my needs because the temp table is not available for additional SELECTs. I got it to work by splitting it into three steps.
    – SeaDrive
    Jul 11, 2011 at 14:00
10

This works. Apparently, if the SqlParameters are in the step that creates the table, the table is not left behind for the next step. Once the table is created, the SqlParameters can be used in a separate step for the INSERT.

        // Create temporary file dropping members from termed groups.
        q = new StringBuilder(500);
        q.Append("create table #ua_param ");
        q.Append("([ID] int not null, fn varchar(50) not null) ");
        sc = new SqlCommand(q.ToString(), db);
        sc.ExecuteNonQuery();

        q = new StringBuilder(500);
        q.Append("insert into #ua_param values(1,@fn1) ");
        q.Append("insert into #ua_param values(2,@fn2) ");
        sc = new SqlCommand(q.ToString(), db);
        sc.Parameters.Add(new SqlParameter("@fn1", sFn));
        sc.Parameters.Add(new SqlParameter("@fn2", sFn2));
        sc.ExecuteNonQuery();

        q = new StringBuilder(500);
        q.Append("select policy_no, name, amt_due, due_date, hic, grp, eff_dt, lis_prem, lis_grp, lis_co_pay_lvl, ");
        q.Append("lep_prem, lapsed, dn_code, [filename], created_dt, created_by ");
        q.Append("into #ua_temp from elig_ua_response inner join #ua_param on [filename] = fn ");
        sc.Parameters.Clear();
        sc.CommandText = q.ToString();
        sc.CommandTimeout = 1800;
        sc.ExecuteNonQuery();
1
  • 11
    SqlCommand calls sql with parameters via sp_executesql when there are parameters, which means your temp table gets created inside (and then clean up in) a stored procedure so it's not available to future calls - even when they share the same connection
    – Joe Zack
    May 25, 2017 at 20:45
3

Its because the temp table is just that. Temporary. You might consider doing your operations in a stored procedure.

5
  • 2
    @Seadrive - if you put this code into a stored proc the issue will disappear, since the stored proc will maintain the table as long as it is executing
    – JNK
    Jul 8, 2011 at 19:54
  • @SeaDrive - if its not helpful to you, go ahead and -1 me. but i am sticking by this answer. Jul 8, 2011 at 20:12
  • 3
    It's an answer to the problem. It's not an answer to the question.
    – SeaDrive
    Jul 8, 2011 at 20:17
  • its up to the database to decide what happens to the table. Jul 8, 2011 at 20:18
  • 1
    It's perfectly valid to use the same temp table in to separate commands, as long as the share the same connection. The problem is when the sqlcommand that creates the temp table takes parameters, then that sql gets executed via sp_executesql - which encloses temp table and eats it.
    – Joe Zack
    May 25, 2017 at 19:59
2

Beyond rolling it into a stored procedure as suggested by @Daniel A White, you can look at BOL article and search for global temporary tables. Also a brief write up on Temporary Tables. Either approach should keep the temporary table alive.

4
  • A global temp table would not work, since the initiating connection is closing before the second connection accesses it. It would still be dropped between queries.
    – JNK
    Jul 8, 2011 at 19:48
  • My bad, I suppose that's what happens when I don't write the code to verify my answer.
    – billinkc
    Jul 8, 2011 at 19:52
  • Actually, the global temp table did work, which is mystifying in it's own way.
    – SeaDrive
    Jul 8, 2011 at 20:22
  • @Bill - if you check BOL about ##globaltemptables it's in there as well, but they only persist as long as either the calling session is active OR they are being accessed
    – JNK
    Jul 8, 2011 at 20:23
2

I had the same problem. I tried the SeaDrive solution and it works, however my tests make me believe that the query execution "flushes" something between "ADO.NET/SQLDriver" and the MS SQL Server.

So, you need to isolate the "CREATE TABLE" statement and submit it to the database before to use it with "INSERT INTO". Composed commands joining CREATE and INSERT in one unique statement doesn't work, unless you can give up the parameters.

1

#TEMP tables only are accessible within the same session or SPID. So if you want to reuse it you need to reuse the connection you used to generate it.

8
  • 1
    It uses the same SqlCommand with the same SqlConnection with no intervening code.
    – SeaDrive
    Jul 8, 2011 at 19:45
  • @Seadrive - It's not reusing the connection, otherwise the table would be visible to the second command.
    – JNK
    Jul 8, 2011 at 19:47
  • 1
    If not, then why not? I've used this technique before without trouble.
    – SeaDrive
    Jul 8, 2011 at 19:56
  • @Seadrive - I'm a SQL guy not a C# guy but if I had to guess I would say it's creating a new SQLDataAdapter in the second code block.
    – JNK
    Jul 8, 2011 at 19:58
  • The SqlDataAdapters are handled in the same way in the place the technique works. I've also tried it without the SqlParameters, and that made no difference.
    – SeaDrive
    Jul 8, 2011 at 20:18
1

Working example with Dapper:

using (var conn = new SqlConnection(connectionString))
{
    conn.Open();
    var expected = Guid.NewGuid();

    // creating the temp table with NO PARAMETERS PASSED IN is the key part.
    conn.Execute("CREATE TABLE #MyTemp (ID UNIQUEIDENTIFIER NOT NULL PRIMARY KEY);");

    // now that the temp table is created, you can run queries with params as
    // much as you want.
    conn.Execute("INSERT INTO #MyTemp (ID) VALUES (@ID)", new { ID = expected });

    var actual = conn.Query<Guid>("SELECT ID FROM #MyTemp;").Single();

    Assert.Equal(expected, actual); // proof it worked
}
1
  • Thank you, none of the other answers made it clear that the CREATE temp table sql must have no parameters and this was holding me back
    – PandaWood
    Oct 25, 2022 at 11:40
0

Using a stored proc makes sense for this sort of thing.

If for some reason that's not feasible, then make sure you are using the same connection for the temp table creation as you are for the temp table selection, else the temp table won't be visible. (it might be that you have this issue randomly if you're using connection pooling.) Alternately, use a real, physical table or even a global temp table (##global_tmp vs #local_tmp), but in either case you'll need to devise a scheme/protocol such that multiple processes aren't trying to create/delete/write to that table.

Again, I'll stress that a stored proc would be a good route, if possible.

2
  • It does work with a ##global_temp. Why would that be? I'm the only user on a development machine (laptop).
    – SeaDrive
    Jul 8, 2011 at 20:04
  • Sry for late reply. It's probably working w/ global (rather than local) temp tables b/c global temp tables are sharable across connections.
    – Garrett
    Jul 14, 2011 at 15:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.