This code returns the following error: "System.Data.SqlClient.SqlException (0x80131904): Invalid column name 'a51'"
a51 is the correct value inside of the record I'm looking for in the EstablishmentCode column of the Establishments table. Account ID is used to find all entries on the Establishments table with that account ID and populate a dataset with Establishment Code values. Account ID value comes from a session variable. Then I use each of these values in a loop where each iteration calls a datareader while loop. Hope I explained this clearly, but I would gladly clarify more if needed. Here's my code.
myConnection.Open(); SqlCommand getEst = new SqlCommand("SELECT EstablishmentCode FROM Establishments WHERE AccountID = " + ID, myConnection); da = new SqlDataAdapter(getEst); ds = new DataSet(); da.Fill(ds); int maxrows = ds.Tables[0].Rows.Count; for (int x = 0; x < maxrows; x++) { getPhones = new SqlCommand("SELECT * FROM DispatcherPhones WHERE EstablishmentCode = " + ds.Tables[0].Rows[x].ItemArray.GetValue(0).ToString(), myConnection); myReader = getPhones.ExecuteReader(); while (myReader.Read()) { Response.Write("<section id='phone" + myReader["Phone"].ToString() + "' style='padding:20px'>"); Response.Write("<section>Phone Number<br><div class='phone'>" + myReader["Phone"].ToString() + "</div></section>"); Response.Write("<section>Location Code<br><div class='name'>" + myReader["EstablishmentCode"].ToString() + "</div></section>"); Response.Write("<section>Active<br><div class='name'>" + myReader["Active"].ToString() + "</div></section>"); Response.Write("<section class='flex phoneButtonSection'>"); Response.Write("<button type=\"button\" onclick=\"showPhoneForm('" + myReader["ID"].ToString() + "');\">CHANGE</button>"); Response.Write("<button type=\"button\" onclick=\"deletePhones('" + myReader["ID"].ToString() + "');\">DELETE</button>"); Response.Write("</section>"); Response.Write("</section>"); } myReader.Close(); } myReader.Close(); myConnection.Close();
SELECT EstablishmentCode FROM Establishments WHERE AccountID = " + ID, I'm thinking thatIDis set toA51. First, you want'A51'which is a string value rather thanA51which is a column name (that presumably doesn't exist). Second, like @SeanLange said, you should create queries through parameterization rather than concatenation. Not only will this prevent SQL injection, but you wouldn't encounter this error in the first place.