Friday, April 16, 2010

[Install] Restarting your SQL service within SQL

DOES NOT WORK. Not deleting the post below in case someone comes across this. We wound up using powershell instead. WMI-process.

We're building a Powershell script to automatically build out our machines. Not just the install, but the full config: backup jobs, maintenance, tempdb files, model, etc, etc.

So, we need to bounce the service so that all the tempdb files get created, the agent knows the database config, etc.

The trick isn't stopping the server: "net stop mssqlserver" will do that. The real trick is starting it back up, once you've shut down the SQL server. Since our solution is all done via SQLCMD we needed a way, within SQL itself, to start back up.

Our secret is the ampersand; when the command line interpreter catches it, it views it as you hitting the "Enter" key. So, even though the SQL service is off, the job continues.

declare @sql varchar(8000)
select @sql = 'net stop SQLSERVERAGENT & ping -n 15 & '
+ 'net stop MSSQLSERVER & ping -n 15 & '
+ 'net start MSSQLSERVER & ping -n 15 & '
+ 'net start SQLSERVERAGENT'
EXEC xp_cmdshell (@sql)

No comments: