Search code examples
c#sql-server-2008temp-tables

C# Insert into temp table


I have a temporary table #PORTAL_PRODUTOS, on sql manager I can insert values into it but when I try to use C# it returns me a error saying there is no #PORTAL_PRODUTOS object.

My code

string sql_insert = @"INSERT INTO #PORTAL_PRODUTOS (DESCRICAO, STRCODIGO, STRREFERENCIA) VALUES (@DESCRICAO, @STRCODIGO, @STRREFERENCIA)";

                        SqlCommand _cmd_insert = new SqlCommand(sql_insert, Conexao);

                        _cmd_insert.Parameters.AddWithValue("@DESCRICAO", tmpProdutoVO.DESCRICAO);
                        _cmd_insert.Parameters.AddWithValue("@STRCODIGO", tmpProdutoVO.STRCODIGO);
                        _cmd_insert.Parameters.AddWithValue("@STRREFERENCIA", tmpProdutoVO.STRREFERENCIA);

                        _cmd_insert.ExecuteNonQuery();
                        _cmd_insert.Parameters.Clear();
                        _cmd_insert.Dispose();

The error is on the ExecuteNonQuery line. "Invalid object name #PORTAL_PRODUTOS"

Thanks in advance for any help.


Solution

  • A temporary table is scope limited to the stored proc or connection etc So you probably have a different connections or you close it.

    You'll have to change the code so you open and close once: keep it alive for all your SQL actions