Using SMO to copy a database and data

后端 未结 4 1002
陌清茗
陌清茗 2021-01-31 18:49

I am trying to make a copy of a database to a new database on the same server. The server is my local computer running SQL 2008 Express under Windows XP. Doing this should be q

4条回答
  •  时光说笑
    2021-01-31 19:40

    Well, after contacting Microsft Support I got it working properly, but it is slow and more or less useless. Doing a backup and then a restore is much faster and I will be using it as long as the new copy should live on the same server as the original.

    The working code is as follows:

    ServerConnection conn = new ServerConnection("rune\\sql2008");
    Server server = new Server(conn);
    
    Database newdb = new Database(server, "new database");
    newdb.Create();
    
    Transfer transfer = new Transfer(server.Databases["source database"]);
    transfer.CopyAllObjects = true;
    transfer.CopyAllUsers = true;
    transfer.Options.WithDependencies = true;
    transfer.DestinationDatabase = newdb.Name;
    transfer.DestinationServer = server.Name;
    transfer.DestinationLoginSecure = true;
    transfer.CopySchema = true;
    transfer.CopyData = true;
    transfer.Options.ContinueScriptingOnError = true;
    transfer.TransferData();
    

    The trick was to set the DestinationDatabase property. This must be set even if the target is that same as the source. In addition I had to connect to the server as a named instance instead of using the other connection options.

提交回复
热议问题