I have confusion regarding query plan when using dynamic query.
Case 1: Insert the result of dynamic query in temp table and then selecting the temp table
When I run the following query:
USE AdventureWorks;
DECLARE @Sql NVARCHAR(255)
DECLARE @FromID INT
DECLARE @ToID INT
SET @FromID = 10
SET @ToID = 100000
CREATE TABLE #Temp ( EmployeeID INT )
SELECT @sql = 'Select EmployeeID from HumanResources.Employee Where
EmployeeID between @FromID AND @ToID';
INSERT INTO #Temp
EXEC sp_executesql @sql, N'@FromID int,@ToID int', @FromID = @FromID,
@ToID = @ToID
SELECT EmployeeID
FROM #Temp
DROP TABLE #Temp
The execution plan I see is:
The query plan shows nothing about my select query which I wrote inside the dynamic sql query i.e the plan regarding this stuff "Select EmployeeID from HumanResources.Employee Where EmployeeID between @FromID AND @ToID" is missing. Now consider the second case:
Case 2: Just executing the dynamic query (no use of temp table here):
USE AdventureWorks;
DECLARE @Sql NVARCHAR(255)
DECLARE @FromID INT
DECLARE @ToID INT
SET @FromID = 10
SET @ToID = 100000
SELECT @sql = 'Select EmployeeID from HumanResources.Employee Where EmployeeID between @FromID AND @ToID';
EXEC sp_executesql @sql, N'@FromID int,@ToID int', @FromID = @FromID,
@ToID = @ToID
For this query I am seeing the following plan:
This time it shows the execution plan of following stuff "Select EmployeeID from HumanResources.Employee Where EmployeeID between @FromID AND @ToID"
My question here is that what happened in the first case? Why it didn't show anything about select query (present inside dynamic query) plan? Is it performance wise good or bad to use dynamic query in the way I used in first case? I was thinking to use this case:
INSERT INTO #Temp
EXEC sp_executesql @sql, N'@FromID int,@ToID int', @FromID = @FromID,
@ToID = @ToID
because after that query I will apply the paging on the #Temp table.
Also where goes the following part in the first execution plan:
INSERT INTO #Temp
EXEC sp_executesql @sql, N'@FromID int,@ToID int', @FromID = @FromID,
@ToID = @ToID