2016-10-27 61 views
0

我需要運行一個SELECT語句,它在Powershell腳本的兩個不同數據庫中的兩個表之間執行右外連接。 我的代碼可以連接到一個數據庫並在那裏運行select,但我不知道如何將第二個數據庫的數據庫連接附加到同一個System.Data.Odbc.OdbcCommand對象。這可能嗎?在Powershell中的多個MSSQL數據庫中進行選擇?

回答

0

連接你一個基地,嘗試這樣的事情:代碼C#

 Select * 
     From yourbase1.dbo.yourtable1 f1 right 
Outer Join yourbase2.dbo.yourtable2 f2 
     On f1.key1=f2.key1 

例如

 string connetionString = null; 
     OdbcConnection cnn; 
     connetionString = "Driver={SQL Server};Server=COLOSSUS\\SQLEXPRESS;Database=test;Trusted_Connection = Yes; "; 
     cnn = new OdbcConnection(connetionString); 
     try 
     { 
      cnn.Open(); 
      using (OdbcCommand com = new OdbcCommand("select * from test.dbo.DemoTable f1 right outer join dbremy57.dbo.NewTable f2 on f1.ID=f2.ID", cnn)) 
      { 


       using (OdbcDataReader reader = com.ExecuteReader()) 
       { 
        while (reader.Read()) 
        { 
         string word = reader.GetString(0); 
         // Word is from the database. Do something with it. 
        } 
       } 
      } 
      cnn.Close(); 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show("Can not open connection ! "); 
     } 
+0

我試過'選擇 dbo.ALL_EVENTS.ID,dbo.ALL_EVENTS.PRIORITY,yourbase2 .dbo.NODE_1.A_NAME FROM yourbase2.dbo.NODE_1 RIGHT OUTER JOIN dbo.ALL_EVENTS ON(dbo.ALL_EVENTS.NODE_ID = right(sys.fn_sqlvarbasetostr(yourbase2.dbo.NODE_1.NODE_ID),32)) ;'but得到了一個例外「米最終部分標識符'yourbase2.dbo.NODE_1.A_NAME'無法綁定。 – reibuehl

+0

嘗試在yourbase2的表中的yourbase1中創建一個視圖,並在您的視圖上選擇 – Esperento57

+0

不幸的是,我不允許對兩個DB中任何一個的DB模式進行修改。 – reibuehl

相關問題