One sql command with two connection strings

I want to run this request in C #

SELECT *
FROM [FirstDataBase].[dbo].[table1]
INNER JOIN [SecondDataBase].[dbo].[table2]

and my code is:

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();

but my query requires two connection strings ... one for [FirstDataBase] and one for [SecondDataBase] ... How can I do this? How to insert two SqlConnectionor ConnectionStringone SqlCommand? or How can I do this in other ways?

+4
source share
4 answers

I really re-read your question, you do not need two connection lines. Your query team can affect any database you want after you connect. 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 .

+5

. . , , , .

, Management Studio, , , .

, , ( @Tim Medora).

+6

, " " Management Studio.

  • goto Server Objects โ†’ Linked Servers.
  • Linked Servers " "
  • "" , , , .
  • , "remote", , "".
  • .

, . :

     select * from [2.2.2.2].[Test].[dbo].[MyTable] 
         join [1.1.1.1].[OtherDb].[dbo].[OtherTable] on ...etc

Linked Servers , , . .

+3

Your query has the database "[FirstDataBase]. [Dbo]. [Table1]". That way, you simply connect to the database (even it could be another database that is [FirstDataBase] or [SecondDataBase]). Your code should work well.

+1
source

All Articles