Backup one database and restore to another in a script

**** Please read carefully: This script will knock out all users and restore a database. If you're not qualified to administrate SQL, please do not do this.

This script will require quite a bit of editing, everything between brackets <> needs to be replaced.

After finishing, run these scripts. You'll need to fix the SY00100 table in the company db to match the DYNAMICS..SY01500

select interid, * from dynamics..sy01500
select * from sy00100

--back up the source db
BACKUP DATABASE [<sourcedb>] TO DISK = N'C:\SQLBACKUP\<sourcedb>.BAK'
    WITH  COPY_ONLY, NOFORMAT, INIT,  NAME = N'<sourcedb> Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10
GO
 
--kill all the non-system spids in the destination db
DECLARE @v_spid INT
DECLARE c_Users CURSOR FAST_FORWARD FOR
    SELECT SPID
        FROM master..sysprocesses p (NOLOCK)
            join master.sys.databases db on db.database_id = p.dbid
        WHERE spid > 50 --only non-system spids
            and db.name = '<destination db>'
            AND spid <> @@spid
 
 
OPEN c_Users
FETCH NEXT FROM c_Users INTO @v_spid
WHILE (@@FETCH_STATUS=0)
BEGIN
   PRINT 'KILLing '+CONVERT(VARCHAR,@v_spid)+'...'
   EXEC('KILL '+@v_spid)
   FETCH NEXT FROM c_Users INTO @v_spid
END
 
CLOSE c_Users
DEALLOCATE c_Users
 
RESTORE DATABASE [<destination db>] FROM DISK = N'C:\SQL\<source db>.BAK'
    WITH  FILE = 1, 
    MOVE N'<fix this>.mdf' TO N'C:\<fix this>\<destination db>.mdf'
    MOVE N'<fix this>.ldf' TO N'C:\<fix this>\<destination db>.ldf',
    NOUNLOAD,  REPLACE,  STATS = 10
 
GO


RealWorldCode gives developers practical, real‑world solutions with clean, working code — no fluff, no theory, just answers.
Links
Home
Knowledge Areas
Sitemap
Contact
Et cetera
Privacy Policy
Terms and Conditions
Cookie Preferences