I have C# code that executes a Dapper Query, creates a temporary table, and uses a parameter to pass a value. In a subsequent query temp table is not available and will throw an error
Invalid object name #TempTable
Whereas if I do not use a parameterized query, then it works properly.
Below is my code -
public async void MyMethod()
{
using(var connection = _unitOfWork.GetConnection())
{
connection.Open();
var id = await connection.QueryAsync<int>(@"CREATE TABLE #TempTable(Id int);
INSERT INTO #TempTable SELECT TOP 1 ID from XYZ WHERE P_ID = @PID",
new { PID = 12345 }).ConfigureAwait(false);
await connection.ExecuteAsync("SELECT ID FROM #TempTable");
)
}
}
Here, #TempTable will not be available in the second query.
How to avoid this issue? I want to use a parameterized query (like @parameter)
I don't want to use param like $"Select ID from XYZ where P_ID = { pid }
-
2Based on the syntax it seems that you are using SQL Server. From the comment to the accepted answer of the first duplicate - "When you include parameters in the command, .net wraps your sql with an "exec sp_executesql" call, which makes your temp table accessible only within that context. If you don't include parameters, your sql is executed directly, so it is available for subsequent commands."Guru Stron– Guru Stron2025年11月24日 09:24:51 +00:00Commented yesterday
1 Answer 1
Temp tables exist only for the single session, so temp table only exists in scope of the first query. When you execute second query, it's already different session and any temp table created in other query won't be accessible in your second query.
So in order for that to work, you need to include second query within the first one:
var id = await connection.QueryAsync<int>(
@"CREATE TABLE #TempTable(Id int);
INSERT INTO #TempTable SELECT TOP 1 ID from [test].[dbo].[Items] WHERE ID = @PID;
SELECT ID FROM #TempTable",
new { PID = 6 }).ConfigureAwait(false);