I’m using ASP.NET C# to output the results from a SQL Server database query and trying to get the results to display only one record per court but that also displays multiple contact details per court.
The tables concerned are (PK in bold, FK in Italics):
Court (Court_ID, Court_Name, Note, Town, Postcode)
Contacts (Contact_ID, Contacts_Name, Contacts_no, *Court_ID*, *Court_Contact_Type_ID*)
Contact_Type (Court_Contact_Type_ID, Court_Contact_Type_Desc)
Currently my issue is that I get multiple repetitions of each court detail for as many contacts as each court has. I know why it’s doing it, but I don’t know the method for how to make it work the way I want.
I’m not sure if the solution lies within the SQL query itself (maybe resolved by nesting…?) or with the C# code because I’m using ‘HasRows’. I’ve included both code snippets below.
string myQuery = "SELECT Court_Name, Town, Postcode, Note, Contacts_Name, Contacts_no, Court_Contact_Type_Desc " +
"FROM Court C, Contacts CON, Contact_type CONT " +
"WHERE C.Court_ID = CON.Court_ID AND CON.Court_Contact_Type_ID = CONT.Court_Contact_Type_ID AND C.Court_ID = '3' ";
SqlConnection connection = new SqlConnection(connStr);
SqlCommand myCommand = new SqlCommand(myQuery, connection);
SqlDataReader myDataReader;
connection.Open();
myDataReader = myCommand.ExecuteReader();
if (myDataReader.HasRows)
{
while (myDataReader.Read())
{
string court_name = myDataReader["Court_Name"].ToString();
string court_town = myDataReader["Town"].ToString();
string court_pcode = myDataReader["Postcode"].ToString();
string court_note = myDataReader["Note"].ToString();
string court_contact_name = myDataReader["Contacts_Name"].ToString();
string court_contact_desc = myDataReader["Court_Contact_Type_Desc"].ToString();
string court_contacts_no = myDataReader["Contacts_no"].ToString();
Response.Write("<strong>" + court_name + "</strong><br>" + court_town + "<br>" + court_pcode + "<p>" + court_note + "</p>" + "<p>" + court_contact_name + " - " + court_contact_desc + " : " + court_contacts_no + "</p>");
}
}
The eventual output should look something like this:
Abergavenny Magistrates’ Court
Abergavenny
NP7 5DL
This court is open for hearings only. Additional Court Notes….
Contacts
Contact Name 1 – Acting Court Manager: 01633 64xxxx
Contact Name 2 – Acting Office Manager: 01633 64xxxx
Contact Name 3 – Acting List Officer: 01633 64xxxx
Contact Name 4 – Justices’ Clerk: 01633 64xxxx
As ever any help gratefully received!
Cheers
You can solve the problem like this:
Here is an example of how you can do it: