一个带有两个连接字符串的sql命令 [英] one sql command with two connection string
问题描述
我想在C#中运行此查询
I want to run this query in C#
SELECT *
FROM [FirstDataBase].[dbo].[table1]
INNER JOIN [SecondDataBase].[dbo].[table2]
我的代码是:
SqlConnection cn = new SqlConnection(myConnectionString);
SqlCommand cmd = new SqlCommand(@"SELECT * FROM [FirstDataBase].[dbo].[table1]
INNER JOIN [SecondDataBase].[dbo].[table2]");
cmd.Connection = cn; // here is my question !!!
cn.Open();
int x = (int)cmd.ExecuteScalar();
但是我的查询需要两个连接字符串...一个用于[FirstDataBase],第二个对于[SecondDataBase] ...我怎样才能做到这一点 ?如何将两个 SqlConnection
或 ConnectionString
插入一个 SqlCommand
中?或者我该怎么办呢?
but my query needs two connection string ... one for [FirstDataBase] and second
for [SecondDataBase]...
How can I do this ?
How can I insert two SqlConnection
or ConnectionString
to one SqlCommand
? or
How can I do it in other ways ?
推荐答案
我实际上已经重读了您的问题,您不需要两个连接字符串.连接后,您的查询命令可以影响您想要的任何数据库.例如:
I've actually reread your question, you don't need two connection strings. Your query command can affect any database you wish, once you've connected. For instance:
string query = @"SELECT * FROM [FirstDataBase].[dbo].[table1]
INNER JOIN [SecondDataBase].[dbo].[table2]";
using(SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionString[@"db"].ConnectionString))
using(SqlCommand command = new SqlCommand(query, connection))
{
// Logic
}
如果您的查询对两个数据库都有影响,那将影响两个数据库.您能够使用SQL Management Studio中存在的相同层次结构来执行任务.
That would impact both databases should your query impact both of them. Your able to use the same hierarchy that is present in SQL Management Studio to perform your task.
这篇关于一个带有两个连接字符串的sql命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!