Sql-server – automating a database backup, restore and stored proc call

backuprestoresql server

How do I create a process that will:

  • backup Database A restore it as Database X (needs to be definable)
  • then run a stored procedure against Database X.
  • shrink and truncate its log file.

Anybody got ideas? Could it be a stored proc on the Master db?

The whole process takes hours and is taking me away from valuable time.

Best Answer

BACKUP DATABASE [Database A]
TO DISK = 'C:\Temp\DatabaseA.bak' WITH FORMAT
GO
use master
GO
RESTORE DATABASE [Database X]
FROM  DISK = N'C:\Temp\DatabaseA.bak'
,  MOVE N'DataFile' TO N'C:\Foo\DatabaseX.mdf'
,  MOVE N'LogFile' TO N'C:\Bar\DatabaseX.ldf'
,  NOUNLOAD,  REPLACE,  STATS = 10

GO
use [Database X]
GO
exec StoredProcedureName...
GO
use master
GO
DBCC ShrinkDatabase( [Database X] )