How to copy an SqlServer Database
How to copy an SqlServer Database
In the current work, we need to solve the problem of copying the entire SqlServer database. The copied content includes the database outline, stored procedures in the database, functions, table structure, primary-foreign key relationships, and all data in the table, that is to say, the copy version is exactly the same as that of the original database. After a period of exploration, we found a simple solution:
(1) Before copying a database, back up the database to a file.
(2) create a new database based on the backup file and Restore it.
The following SQL statement can be used to back up a database:
The Code is as follows:
String. Format ("backup database {0} to disk = '{1}';", dbName, bakFilePath)
You can use the following stored procedure to create and Restore a new database based on the backup file:
The Code is as follows:
Create procedure CopyDB
(
@ NewDbName varchar (50), -- New Database Name
@ DbDataDirPath varchar (100), -- path of the Data folder directory for Database Installation
@ SoureDbName varchar (100), -- source database name
@ SoureBackupFilePATH varchar (100) -- path of the source database backup file
)
AS
Declare @ SQL varchar (3000)
Set @ SQL ='
Create database '+ @ newDbName +'
ON
(
Name = '+ @ soureDbName +' _ Data,
Filename = ''' + @ dbDataDirPath + @ newDbName + '_ Data. mdf '',
SIZE = 10,
FILEGROWTH = 15%
)
LOG ON
(
Name = ''' + @ soureDbName + '_ log '',
Filename = ''' + @ dbDataDirPath + @ newDbName + '_ Log. ldf '',
SIZE = 5 MB,
MAXSIZE = 25 MB,
FILEGROWTH = 5 MB
)
-- Start restoration
Restore database '+ @ newDbName +' from disk = ''' + @ soureBackupFilePATH + ''' WITH REPLACE
'
Exec (@ SQL)
GO
The test code is as follows:
The Code is as follows:
IList ParaList = new List ();
SPParameter para1 = new SPParameter ("newDbName", ParameterDirection. Input, "EASNew9 ");
ParaList. Add (para1 );
SPParameter para2 = new SPParameter ("dbDataDirPath", ParameterDirection. Input, @ "C: \ Program Files \ Microsoft SQL Server \ MSSQL \ Data \");
ParaList. Add (para2 );
SPParameter para3 = new SPParameter ("soureDbName", ParameterDirection. Input, "AutoSchedulerSystem ");
ParaList. Add (para3 );
SPParameter para4 = new SPParameter ("soureBackupFilePATH", ParameterDirection. Input, @ "d: \ sqlDatabase \ AutoSchedulerSystem ");
ParaList. Add (para4 );
IDictionary OutParas = null;
Program. DataAccesser. GetSPAccesser (null). ExcuteNoneQuery ("CopyDB", paraList, out outParas );