Wednesday, October 02, 2013

script for copy a sql server database / Skript zum Kopieren einer Sql Server Datenbank

quell Datenbank Name=x1, Ziel Datenbank Name=x2
source database name =x1, dest database name=x2

select 'backup'  --echo wath I'm doing
go backup database x1 to disk ='D:\BAK\x1.bak' --full backup
go
USE master
go
select 'DropCon'
go
ALTER DATABASE x2 SET OFFLINE WITH ROLLBACK IMMEDIATE --cut all existing connections
go
ALTER DATABASE mydb SET ONLINE WITH ROLLBACK IMMEDIATE --connect again
go
DROP DATABASE mydb --drop to remove mdf and ldf file to create same named files with 
go
select 'restore'  --echo wath I'm doing
go

--get filelist of logical files in restore file, maybe they differ fropm x1 and x1_log
RESTORE FILELISTONLY from disk = 'd:\temp\x.bak'



restore database x2  from disk ='D:\BAK\x1.bak' with file=1,
move 'x1' to 'D:\sqldata\x2_Data.MDF',
move 'x1_Log'  to 'D:\sqldata\x2_Log.LDF'
go


use osql on sql server 2000 or sqlcmd 2005 and later to execute from commandline:
osql:


d:
cd D:\sqldata

osql -U username -P password -i script.sql

No comments: