Saturday, February 25, 2012

Can't copy a database

I want to make a working copy of a database to a new name on the same server. I use the wizard giving the same name for source and destination, but giving the db copy a new name. I get an error that says "One or m ore arguments are invalid."

But no hint as to what is wrong.

Is it that I can't copy on the same machine?

You want to do a 'backup database' and 'restore database' to create a new database based on the old database.

Here is a script that you can use.

use master
go
declare @.db1 sysname,@.db2 sysname,
@.name1 sysname, @.name2 sysname,
@.file1 sysname,@.file2 sysname,
@.sql nvarchar(1000)

set @.db1='Northwind'
set @.db2='NewBD'

set @.sql='select @.name1=name,@.file1=filename from '+@.db1+'..sysfiles where fileid=1'
exec sp_executesql @.sql,N'@.name1 sysname out,@.file1 sysname out',@.name1 out,@.file1 out

set @.sql='select @.name2=name,@.file2=filename from '+@.db1+'..sysfiles where fileid=2'
exec sp_executesql @.sql,N'@.name2 sysname out,@.file2 sysname out',@.name2 out,@.file2 out

select @.name1=ltrim(rtrim(@.name1)),
@.name2=ltrim(rtrim(@.name2)),
@.file1=substring(@.file1,1,(len(@.file1)-charindex('\',reverse(rtrim(@.file1)))))+'\'+@.db2+'.mdf',
@.file2=substring(@.file2,1,(len(@.file2)-charindex('\',reverse(rtrim(@.file2)))))+'\'+@.db2+'.ldf'

set @.sql='backup database '+@.db1+' to disk=''c:\db1.tmp'' with init'
exec master..sp_executesql @.sql

set @.sql='restore database '+@.db2+' from disk=''c:\db1.tmp''
with replace,
move '+quotename(@.name1,char(39))+' to '+quotename(@.file1,char(39))+',
move '+quotename(@.name2,char(39))+' to '+quotename(@.file2,char(39))+',
recovery'

exec master..sp_executesql @.sql|||

I will give this a try. Thanks!

(But one wonders why simple stuff like this can't be handled by the GUI.)

No comments:

Post a Comment