views:

137

answers:

2

How is it possible to run a stored procedure when SQL Server Express Edition starts?

+9  A: 

Use the system stored procedure sp_procoption to define the stored procedure you wish to be executed at SQL Server Service startup.

exec sp_procoption 
        @ProcName    = 'procedureName',
        @OptionName  = 'startup', 
        @OptionValue = 'true'
John Sansom
Excellent answer, thanks :)
Thomas Bratt
You're welcome, glad to help.
John Sansom
+1  A: 
USE master;
GO
-- first set the server to show advanced options
EXEC sp_configure 'show advanced option', '1';
RECONFIGURE
-- then set the scan for startup procs to 1
EXEC sp_configure 'scan for startup procs', '1';
RECONFIGURE

IF OBJECT_ID('spTest') IS NOT NULL
    DROP PROC spTest
GO
-- crate a test stored procedure
CREATE PROC spTest
AS
-- just create a sample database
EXEC('CREATE database db1')

GO
-- set it to run at sql server start-up
exec sp_procoption N'spTest', 'startup', 'on'
Pace
A comment that might explain the code above:"Only the system administrator (sa) can mark a stored procedure to execute automatically. In addition, the stored procedure must be in the master database and owned by sa and cannot have input or output parameters."
Thomas Bratt