简体   繁体   中英

Caching dynamic sql in stored procedure

I have dynamic SQL in stored procedure which creates dynamic table and inserts data. My question is, will this query plan cached.

Here is a simple example of how I am currently building the dynamic SQL inside stored procedure.

CREATE PROCEDURE [dbo].[GetOrders] 
@CustID AS INT
AS 

BEGIN

DECLARE @SQL NVARCHAR(MAX) 

DECLARE @TableName AS VARCHAR(500)

    SET @TableName = CONVERT(VARCHAR(255), NEWID())

    SET @SQL = 'CREATE TABLE [dbo].[' + @TableName + ']
(
  [OrderID] [int] NOT NULL
) '

    EXEC sp_executesql @SQL

    SET @SQL = 'insert [dbo].[' + @TableName + '](OrderID) 
            select OrderID from dbo.Orders where CustomerID=@CustID'

    EXEC sp_executesql @SQL, N'@CustID INT', @CustID = @CustID


 END
 GO

Yes, this query plan will be cached. You can see this by running your code and then immediately running this query:

SELECT *
FROM sys.dm_exec_query_stats s
CROSS APPLY sys.dm_exec_query_plan(s.plan_handle) qp
WHERE creation_time >= DATEADD(SECOND, -10, GETDATE())

Since you are creating a new table each time based on NEWID(), you will get a separate plan each time.

Yes, the execution plan will be created and cached in memory (not disk) on the first execution. As you're creating a new table for every query, I don't think the plan will be reused, but I haven't tested this.

The fact that the stored procedure plan is cached in memory and not on disk means that it will fall out of the cache on a server restart or due to low re-use. It can also fall out of cache if the data on which the procedure depends changes enough to cause the statistics to be invalidated. This causes SQL Server to invalidate the plan.

You can check the execution plan that's created with the following query:

SELECT sc.*
FROM master.dbo.syscacheobjects AS sc
WHERE sc.cacheobjtype = 'Executable Plan'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM