简体   繁体   English

使用2个数据库执行sql查询

[英]execute sql query using 2 databases

My query looks like: 我的查询如下:

INSERT INTO [NewModel.Persistence.PersistencyContext].[dbo].[NewPerson] (
    [Name], 
    [Location], 
    [LastUpdate]
    )
SELECT 
    MIN([name]), 
    MIN([location]), 
    MIN([time])
FROM [OldModel.Persistence.PersistencyContext].[dbo].[ExPerson]
GROUP BY name

How do I define the connection string and what is the c# code to execute this query? 如何定义连接字符串以及执行此查询的c#代码是什么?

There are two things going on here. 这里有两件事。

First if your databases are on the same instance of sql server (essentially two different versions of the same database running under the sql instance) then you won't need to have a linked server. 首先,如果您的数据库位于同一个sql server实例(实际上是在sql实例下运行的同一个数据库的两个不同版本),那么您将不需要拥有链接服务器。

However, if they are running on different servers (and possibly different machines) then you'll need to link them as stated by Oded and David. 但是,如果它们在不同的服务器(可能是不同的机器)上运行,那么您需要按照Oded和David的说明链接它们。

I would create a stored procedure and call it from the code as needed. 我会创建一个存储过程并根据需要从代码中调用它。

CREATE PROC usp_AddMyRecords

AS
BEGIN  
INSERT INTO [NewModel.Persistence.PersistencyContext].[dbo].[NewPerson] (  
    [Name],   
    [Location],   
    [LastUpdate]  
    )  
SELECT   
    MIN([name]),   
    MIN([location]),   
    MIN([time])  
FROM [OldModel.Persistence.PersistencyContext].[dbo].[ExPerson]  
GROUP BY name  

END

C# Code To Call the Procedure: 调用程序的C#代码:

SqlConnection dbConnection = new SqlConnection(ConfigurationManager.ConnectionStrings
                                     [YOUR_CONNECTION_STRING_NAME].ConnectionString);  
SqlCommand cmd = new SqlCommand();  
cmd.CommandText = "usp_AddMyRecords";  
cmd.CommandType = CommandType.StoredProcedure;  
cmd.Connection = dbConnection;  
conn.Open();
cmd.ExecuteNonQuery();

If your database is SQL Server, you'll need to create a linked server connection between NewModel and OldModel's servers. 如果您的数据库是SQL Server,则需要在NewModel和OldModel的服务器之间创建链接服务器连接。 You'll need to run the sp_addlinkedserver stored procedure ( MSDN documentation here ). 您需要运行sp_addlinkedserver存储过程( 此处为MSDN文档 )。

As Oded's comment states, your connection string to NewModel will be just a normal connection string (server=NewModelServer;Initial Catalog=NewModel;UID=;PWD=;) and just connect with a user (SQL Server authentication or Integrated Security) that can access both servers. 正如Oded的评论所述,你的NewModel连接字符串只是一个普通的连接字符串(server = NewModelServer; Initial Catalog = NewModel; UID =; PWD =;),只需连接一个用户(SQL Server身份验证或集成安全性)即可访问两台服务器。

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM