I am trying to develop an application using ADO.NET. I have two tables in two different databases. Each of them have a portion of the complete data. Now I need to write a query such that I am able to fetch the complete record from the two tables. As an example say table 1 has Index_no,emp_ID and contact no. Table 2 has index_no, emp_name, salary and dept. The index_no is same for the same record portion in each table.
Following is the code to fetch all records where salary <20000.
sqlCmd2 = new SqlCommand("SELECT * FROM table1 WHERE Index_No =@Index_No",
TestCon);
int i = 0;
while (reader.Read()) {
ListBox1.Items.Add(reader.GetInt32(0) + " - " +
reader.GetString(1) + " - " + reader.GetString(2));
// Name.Text += reader["Name"] + "<br />"; ;
// Depart.Text += reader["Depart"] + "<br />"; ;
array1[i] = reader.GetInt32(0);
i++;
}
sqlCmd2.Parameters.Add("@Index_No", System.Data.SqlDbType.Decimal);
i = 0;
do {
sqlCmd2.Parameters["@Index_No"].Value = array1[i];
reader1 = sqlCmd2.ExecuteReader();
reader1.Read();
ListBox2.Items.Add(reader1.GetString(1));
i++;
} while (i < array1.Length);
The problem with this is that I am getting only one record info from table2 while for table 1 I get all the desired record info. The do-while loop seems to terminate after one iteration only.
It depends, what two different databases means. If the two databases run on the same SQL-Server, it is easy to access the table of the other database
If not, I would suggest you to create a database link between the two databases (see SO question How do I create and query linked database servers in SQL Server?). Then you can access the other table as above.
In both cases you can use a JOIN query to join the two tables. Then you will need only one data reader
UPDATE
If the number of involved records is small, then querying the second table only once by using a
INclause would be far more efficient, if you cannot link the two servers for some reason.You would create this SQL statement like this
The idiomatic way of doing the second loop would be (not
do while)