如何在两个不同的服务器上合并两个数据库?

时间:2015-06-16 18:48:26

标签: sql sql-server connection-string sql-server-express

我有两个不同的数据库,客户端数据库从.MDF文件附加到.\SQLEXPRESS服务器。主服务器正在另一台名为COMPUTER_NAME的计算机上的服务器上运行。

我想使用C#合并这些文件以运行.SQL文件。我将我的代码粘贴在下面以供参考,但基本上我的问题是如果我使用

连接到服务器
 string sqlConnectionString = @"Server=.\SQLEXPRESS; Trusted_Connection=True";

然后我无法在COMPUTER_NAME找到数据库。如果我使用

 string sqlConnectionString = @"Server=COMPUTER_NAME; Trusted_Connection=True";

它会在.MDF的C:驱动器上查找我的COMPUTER_NAME文件,而不是本地计算机。

如何连接到不同服务器上的这两个数据库?

其他信息:

我正在使用的SQL脚本。当两个数据库都在同一台服务器上时,这完全可以恢复,但我不能再那样做了。

CREATE DATABASE ClientDB  
ON (Filename = 'C:\Clayton.mdf')
   , (Filename = 'C:\Clayton_log.ldf') 
FOR ATTACH;

-- update the client from the master 
MERGE [ClientDB].[dbo].[table] trgt
using [MasterDB].[dbo].[table] src
ON trgt.id = src.id 

WHEN matched AND trgt.lastmodified <= src.lastmodified THEN -- if master row is newer 
   UPDATE SET trgt.[info] = src.[info], ...                 -- update the client 

WHEN NOT matched BY source                                  -- delete rows added by client 
   THEN DELETE 

WHEN NOT matched BY target                                  -- insert rows added by master 
   THEN INSERT ( [info], ... ) VALUES (src.[info], ... ); 


-- close all connections to database
ALTER DATABASE ClientDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE; 

-- detach database
EXEC sp_detach_db 'ClientDB', 'true'; 

我使用C#运行它如此:

 string sqlConnectionString = @"Server=.\SQLEXPRESS; Trusted_Connection=True";

 string script = File.ReadAllText(Environment.CurrentDirectory + @"\MergeTotal.sql");
 SqlConnection conn = new SqlConnection(sqlConnectionString);

 IEnumerable<string> commandStrings = Regex.Split(script, @"^\s*GO\s*$",
                            RegexOptions.Multiline | RegexOptions.IgnoreCase);

 conn.Open();
 foreach (string commandString in commandStrings)
 {
     if (commandString.Trim() != "")
     {
         using (var command = new SqlCommand(commandString, conn))
         {
             command.ExecuteNonQuery();
         }
     }
 }

我不在乎整个过程是在.SQL还是C#中发生,只要它具有预期的效果即可。

提前感谢任何指导或建议。

2 个答案:

答案 0 :(得分:2)

如果需要,链接服务器将有助于您同时访问数据。但是,如果您希望将数据合并在一起,我建议您查看sp_generate_merge以将数据拉入合并脚本(非常方便移动数据)。另请参阅关于生成合并数据here的问题。

答案 1 :(得分:0)

好吧,我不得不完全扔掉整个.MDF的东西。我只是设置了数据库,而不是从.MDF附加和重新附加数据库。

这是我在平板电脑上初始化本地数据库的代码:

CREATE DATABASE LocalClaytonDB  
ON (Filename = 'C:\ProgramData\Clayton\Clayton.mdf')
   , (Filename = 'C:\ProgramData\Clayton\Clayton_log.ldf') 
FOR ATTACH;
GO

EXEC sp_addlinkedserver @server='Server'

这是我的同步两个数据库的代码:

-- update the client from the master 
MERGE [LocalClaytonDB].[dbo].[tableName] trgt
using [Server].[Clayton].[dbo].[tableName] src

ON trgt.id = src.id 

WHEN matched AND trgt.lastmodified <= src.lastmodified THEN 
  -- if the master has a row newer than the client
  -- update the client                       
  UPDATE SET trgt.[allColumns]      = src.[allColumns],
             trgt.[id]              = src.[id], 
             trgt.[lastmodified]    = src.[lastmodified] 

-- delete any rows added by a client 
WHEN NOT matched BY source 
THEN 
  DELETE 

-- insert any rows added by the master 
WHEN NOT matched BY target 
THEN 
  INSERT ( [allColumns], 
           [id], 
           [lastmodified]) 
  VALUES (src. [allColumns], 
          src.[id], 
          src.[lastmodified]); 


-- now we update the master from the client
-- Note:
-- because the serverDB is a linked server 
-- we can't use another MERGE statement, otherwise
-- we get the error: "The target of a MERGE statement 
-- cannot be a remote table, a remote view, or a view over remote tables."

UPDATE
    serverDB

SET 
    [allColumns]        = [localDB].[allColumns],
    [id]                = [localDB].[id], 
    [lastmodified]      = [localDB].[lastmodified] 

FROM 
     [Server].[Clayton].[dbo].[tableName] serverDB

INNER JOIN
     [LocalClaytonDB].[dbo].[tableName] localDB

-- update where the id is the same but the client is newer than the master

ON serverDB.id = localDB.id 
       AND localDB.lastmodified >= serverDB.lastmodified