I got motivated to write this post as there was a question on twitter which was like –
The user was checking if there was a way to prevent procedures which are created with RECOMPILE hint.
I was pretty sure that Policy Based Management did provide us a Stored Procedure Facet, and there will be some expressions which we can create using the same to ensure that no new stored procedures are created with this hint.
Will I use RECOMPILE hint ever in my stored procedure? That’s a huge ‘It depends’ question. I might not use it within a stored procedure, but at times I might have to use it during run time.
Kendra Little(B/T) has an excellent video on recompile, and you can find it here. [Really nice stuff out there !]
I did reply to the user that I’m positive that there will be some option, but it needs to be tested out .
So, this post is my test case to try and see if we can actually prevent users from creating stored procedures with RECOMPILE hint using PBM .
First of I created a condition using facet stored procedure and added an expression like what is shown in the image below –
I went ahead and created a policy which used the condition which was created in the first step, and chose evaluation mode as On Change : Prevent
Note – I’m doing this check for every database and every stored procedures as this is a test case. This can be checked against a single db using another condition and that’s the recommended approach.
Once the policy is created I made sure that its in enabled state.[Apparently nothing will be validated if the policy is not enabled ]
Next step is to try and create a stored procedure with recompile hint. For this purpose I will be using a database called SuperMan (Yes,just for fun).This db got a table called People and it has 3 rows of data.
I tried to create a simple stored procedure named FindSuperMan which will do a simple SELECT * from the table.This stored procedure will try to force a RECOMPILE hint.
CREATE PROCEDURE dbo.FindSuperMan WITH RECOMPILE AS SELECT * FROM [dbo].[People] GO
As soon as I ran the command there was an error which said –
Policy ‘Policy_Prevent_Recompile’ has been violated by ‘SQLSERVER:\SQL\TESTServer\DEFAULT\Databases\SuperMan\StoredProcedures\dbo.FindSuperMan’.
This transaction will be rolled back.
Policy condition: ‘@Recompile != True()’
Policy description: ”
Additional help: ” : ”
Statement: ‘CREATE PROCEDURE dbo.FindSuperMan
Msg 3609, Level 16, State 1, Procedure sp_syspolicy_dispatch_event, Line 65
The transaction ended in the trigger. The batch has been aborted.
What actually happens here is the transaction will be rolled back as it violated the policy which was defined.
This proves the fact that PBM can indeed be used to prevent some conditions which you don’t want to happen in your db/environment.
Thanks for reading and keep watching this space for more !