简体   繁体   English

在SQL Server中连接两个数据库

[英]Connecting two databases in SQL Server

private void button1_Click(object sender, EventArgs e)
{
        SqlConnection con = new SqlConnection();
        con.ConnectionString = "Data Source= shwn-PC\\SQLEXPRESS;Initial Catalog=database1;Integrated Security=True";

        con.Open();

        SqlCommand cmd = new SqlCommand("select * from table1 where A ='" + textBox1.Text.Trim() + "'", con);

        SqlDataReader dr = cmd.ExecuteReader();

        if (dr.HasRows)
        {
            while (dr.Read())
            {
                textBox2.Text = dr["A"].ToString();
                textBox3.Text = dr["B"].ToString();
            }
        }
        else
            MessageBox.Show("No record  >> " + textBox1.Text.ToString());
    }
}

How can I connect two databases and show a certain column combined with another column from the other database? 如何连接两个数据库并显示某个列与另一个数据库中的另一列组合?

Like in the textbox3 I want to show the B value from this database plus C value from database2, table2 像在文本框3中一样,我想显示此数据库中的B值以及数据库2中的C值,表2

If both databases exist in one single server, you can use database name as prefix for table name: 如果两个数据库都位于一个服务器中,则可以使用数据库名称作为表名称的前缀:

SELECT a.col1, b.col2 FROM db1.TableA a
INNER JOIN db2.TableB b ON b.Id = a.LinkId

Reference 参考

SELECT *  FROM [DB1].[dbo].[Table1],[DB2].[dbo].[Table2]

Try to use something like above. 尝试使用类似上面的内容。 This is just a sample, I have use this to join two table from two different database. 这只是一个示例,我已经使用它来连接来自两个不同数据库的两个表。

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

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