I am attempting to copy an SQL Server database into a new database on the same server without transferring the data (that is, I'm trying to build an identical, empty database).
The code below works correctly on a sample database that I built specifically for testing. But when applied to the actual target database, it fails at the .TransferData()
call (after several seconds of execution) with the error System.Data.SqlClient.SqlException : 'LocalAdmin' is not a valid login or you do not have permission.
The account under which I'm developing and testing program can be used to log into the SQL Server instance in question and perform database creation, and creation of objects within both the source and target databases.
After the failure, the database specified in targetDb has, in fact, been created, but it has no tables or other structures.
Can anyone tell me how to fix the following code so that it will be able to successfully copy my database structure?
/* Ref: Microsoft.SqlServer.ConnectionInfo.dll
Microsoft.SqlServer.Management.Sdk.Sfc.dll
Microsoft.SqlServer.Smo.dll
Microsoft.SqlServer.SmoExtended.dll
Microsoft.SqlServer.SqlEnum.dll */
using Microsoft.SqlServer.Management.Smo;
using System;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
CopyEmptyDatabase(@"server_name\instance_name", "sourceDb_name", "targetDb_name");
}
public static void CopyEmptyDatabase(string instance, string sourceDb, string targetDb)
{
var server = new Server(instance);
var transferAgent = new Transfer(server.Databases[sourceDb]);
transferAgent.CopyAllObjects = true;
transferAgent.DropDestinationObjectsFirst = true;
transferAgent.CopySchema = true;
transferAgent.CopyData = false;
// Transfer requires the target DB to exist
var target = new Database(server, targetDb);
target.Create();
transferAgent.DestinationServer = instance;
transferAgent.DestinationDatabase = targetDb;
transferAgent.DestinationLoginSecure = true;
transferAgent.Options.IncludeIfNotExists = true;
try
{
transferAgent.TransferData();
}
catch (Exception exc)
{
Debug.Print(exc.Message);
throw;
}
}
}
}
Try making a new db from the SQL tools and see if you can drop the sprocs that are in the newly created db. If you're not the
dbo
, you probably won't have permissions to drop them. Note that the objects therein are copied from themodel
db...so it won't be completely empty at the start. Your organization may have added things to themodel
as well...so you'll need to look into that.Edit:
Another way to test this theory...just remove the line that says
transferAgent.DropDestinationObjectsFirst = true;