[英]Copy SQL Server database in code
I have two SQL Server connection strings, CX and CY. 我有两个SQL Server连接字符串,CX和CY。
What I need to do is 我需要做的是
Haven't found what I am looking for yet. 还没找到我要找的东西。 I don't want a tool to do this, I need to do it in C# code at runtime because the action of adding a new Client needs to copy a master DB to an empty DB.
我不想要一个工具来执行此操作,我需要在运行时使用C#代码执行此操作,因为添加新客户端的操作需要将主数据库复制到空DB。 I can't use a pre-made script because I need to also copy data, and the master DB could have been updated only seconds before the new client was added.
我不能使用预制脚本,因为我还需要复制数据,并且主数据库可能在添加新客户端之前几秒就已更新。
===UPDATE=== === UPDATE ===
I am using Smo.Backup and Smo.Restore. 我正在使用Smo.Backup和Smo.Restore。 When I try to restore I get:
当我尝试恢复时,我得到:
ERROR 3154 The backup set holds a backup of a database other than the existing database. 错误3154备份集包含现有数据库以外的数据库的备份。
Can anyone tell me how to get around this? 谁能告诉我如何解决这个问题? Other than that I have a working solution!
除此之外,我有一个有效的解决方案!
Thanks 谢谢
Pete 皮特
A Solution with Database Backup: 数据库备份解决方案:
1) Ensure no tables 1)确保没有表格
select COUNT(*) from sys.sysobjects where xtype = 'U'
2) Backup 2)备份
BACKUP DATABASE MyFirstDatabase TO DISK= @path WITH FORMAT
3) Restore 3)恢复
RESTORE DATABASE MySecondDatabase FROM DISK = @path WITH REPLACE
See SQL Books Online for more Details: http://msdn.microsoft.com/en-us/library/ms186865.aspx 有关详细信息,请参阅SQL联机丛书: http : //msdn.microsoft.com/en-us/library/ms186865.aspx
You can use SQL Server Management Objects (SMO). 您可以使用SQL Server管理对象(SMO)。 Check out http://msdn.microsoft.com/en-us/library/ms162169.aspx .
查看http://msdn.microsoft.com/en-us/library/ms162169.aspx 。 Information specifically on backing up a database is at http://technet.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.backup.aspx .
有关备份数据库的具体信息,请访问http://technet.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.backup.aspx 。
I understand your desire to do this in C# code, but I really think just calling a command line tool to do it for you would be easiest. 我理解您希望在C#代码中执行此操作,但我真的认为只是调用命令行工具来为您执行此操作将是最简单的。
That said, this guy has a script that looks like it would do what you want. 也就是说, 这家伙有一个看起来像你想要的脚本。 You could probably wrap that up in a SPROC and call it easily enough.
您可以将其包装在SPROC中并轻松调用它。
I think you need to look into the 我想你需要调查一下
SqlServer.Management.Smo.Backup class
see this technet article also, this article could be a reference, depending on your specific needs. 另请参阅此technet文章 ,根据您的具体需求, 本文可以作为参考。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.