I spent whole days and hours to investigate why cannot create temporary table when I call a stored procedure from C# code.
Let's assume a piece of C# code:
public void GetDataByFilter(string item, string filter ...) {
...
// provide stored procedure in new SqlCommand object
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.Add("@val1", aValue1);
sqlCommand.Parameters.Add("@val2", aValue2);
...
while(sqlDataReader.Read()) { /* process info here */ }
}
and my stored procedure
ALTER PROCEDURE [dbo].[aProcedure]
@val1 VARCHAR(255),
@val2 VARCHAR(255),
...
AS
BEGIN
IF OBJECT_ID(N'tempdb..##aTempTable') IS NULL
CREATE TABLE tempdb..##aTempTable (
id1 INT,
id2 INT,
id3 VARCHAR(255),
...
)
ELSE
TRUNCATE TABLE tempdb..##aTempTable
-- insert information into this table
SELECT @paramList = ' /*list of parameters*/';
EXEC sp_executesql @sql, @paramList, ... parameters
END
In C# code, in another function, I provided
sqlCommand.CommandText = "SELECT * FROM tempdb..##aTempTable";
But exception was thrown that tempdb..##aTemTable
doesn't exists.
If I execute stored procedure inside SSMS (Sql Server Management Studio) then the table is created.
The problem is also for TRUNCATE TABLE
operation not only for CREATE TABLE
.
I need temporary global table for to be used into different stored procedures accordingly with It is possible for created temporary table by a stored procedure to be used in another stored procedure?.
Any solution ?