Few days back I leanrt about a configuration option in SQL Server called 'scan for startup procs'.
Scan for startup procs option is used to execute stored procedures during SQL Instance startup. By default this option is not enabled. You can enable it using ‘sp_configure’, below is the command. SQL Service needs to be restarted to make 'scan for startup procs' configuration effective. I will also be enabling ‘XP_CMDSHELL’ for this demonstration.
EXEC SP_CONFIGURE 'show advanced options',1
USE MASTER
To check the list of procedures added to startup procedure use below command
Now we’ll remove this SP from the startup proc by running below command and check the status.
Scan for startup procs option is used to execute stored procedures during SQL Instance startup. By default this option is not enabled. You can enable it using ‘sp_configure’, below is the command. SQL Service needs to be restarted to make 'scan for startup procs' configuration effective. I will also be enabling ‘XP_CMDSHELL’ for this demonstration.
EXEC SP_CONFIGURE 'show advanced options',1
GO
RECONFIGURE
EXEC SP_CONFIGURE 'scan for startup procs',1
GO
RECONFIGURE
EXEC SP_CONFIGURE 'XP_CMDSHELL',1
GO
RECONFIGURE
Now it’s time to do some bad things. Run the below script, which will create a stored procedure named ‘Destroy’ in master database and that will be added to scan for startup procs. This SP will get executed during the SQL Instance startup.
USE MASTER
GO
CREATE PROCEDURE DESTROY
AS
EXEC XP_CMDSHELL 'NET STOP MSSQL$SQL2012'
GO
EXEC SP_PROCOPTION @PROCNAME = 'DESTROY',
@OPTIONNAME = 'STARTUP',
@OPTIONVALUE = 'ON'
In above script change the SQL instance name according to your instance type.
Hope you know what happens if this gets executed :-)
Now go ahead and stop/start or restart your SQL Instance. You will not be able to start your SQL Instance. If you look at the error log, you’ll find below messages.
Once the recovery is completed scan for startup procedure is made and SP is executed.
So now how to come out from this situation?
Start SQL in single user mode (/m) and remove this procedure from startup/drop this procedure/disable this configuration. Let’s have a look at the SQL error log.
Start SQL in single user mode (/m) and remove this procedure from startup/drop this procedure/disable this configuration. Let’s have a look at the SQL error log.
We can see only recovery part is completed and no startup procedure is executed.
To check the list of procedures added to startup procedure use below command
SELECT NAME FROM SYS.PROCEDURES WHERE IS_AUTO_EXECUTED=1
Now we’ll remove this SP from the startup proc by running below command and check the status.
EXEC SP_PROCOPTION @PROCNAME = 'DESTROY', @OPTIONNAME = 'STARTUP', @OPTIONVALUE = 'OFF'
Cheers,
Naveen
PS
Testing this script is at your own risk. Please test/play with this in your
test environment.