0

当我从组合框中选择名称时,如何显示 3 个表中的数据。我假设我需要加入有问题的 3 个表,但我不确定语法。

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {


        string constring = ("Data Source=****************");

        string Query = "select * from Table1 where Last='" + cbUsers.SelectedItem.ToString() + "' ;";

        SqlConnection conDataBase = new SqlConnection(constring);
        SqlCommand cmdDataBase = new SqlCommand(Query, conDataBase);
        SqlDataReader myReader;

        try
        {
            conDataBase.Open();
            myReader = cmdDataBase.ExecuteReader();

            while (myReader.Read())
        {

            string sFirst = myReader.GetString(2); //From Table1
            string sLast = myReader.GetString(1); //From Table1
            string sdob = myReader.GetString(3);//From Table2
            string scode = myReader.GetString(1);//From Table3


            txtFirst.Text = sFirst;
            txtdob.Text = sdob;
            txtcode.Text = scode;
4

2 回答 2

1

通用代码是

select
table1.sFirst,
table1.sLast,
table2.sdob,
table3.scode
from table1 
inner join table2 on table1.keycol=table2.keycol
inner join table3 on table2.keycol=table3.keycol
where table1.Last='some value'
于 2013-11-04T10:48:31.727 回答
0

由于我的意思是您只忘记加入 3 个表,因此请以这种方式更改代码:

私人无效ComboBox_SelectionChanged(对象发送者,SelectionChangedEventArgs e){

    string constring = ("Data Source=****************");

    string Query = "select t1.sFirst, t1.Last, t2.sdob, t3.scode from Table1 as t1 Table2 as t2, table 3 as t3 where t1.Last='" + cbUsers.SelectedItem.ToString() + "' AND t1.key = t2.key AND t2.key = t3.key";

    SqlConnection conDataBase = new SqlConnection(constring);
    SqlCommand cmdDataBase = new SqlCommand(Query, conDataBase);
    SqlDataReader myReader;

    try
    {
        conDataBase.Open();
        myReader = cmdDataBase.ExecuteReader();

        while (myReader.Read())
    {

        string sFirst = myReader.GetString(1); //From Table1
        string sLast = myReader.GetString(2); //From Table1
        string sdob = myReader.GetString(3);//From Table2
        string scode = myReader.GetString(4);//From Table3


        txtFirst.Text = sFirst;
        txtdob.Text = sdob;
        txtcode.Text = scode;
于 2013-11-04T10:55:59.490 回答