I am trying to run a query on a database table and have it a return the results in alphabetical order, however when I run the following statement it returns everything in the same manner that it appears in the database. I am doing an order by the officegroup which from what I understand it should return the result order in alphabetical order.
SELECT
OfficeGroupID, OfficeGroup
FROM
tblofficegroup
INNER JOIN
tblRegion ON tblOfficeGroup.RegionID = tblRegion.RegionID
WHERE
ISNULL(tblofficegroup.Hide, 0) = 0
AND ISNULL(tblRegion.Hide, 0) = 0
AND OfficeGroupID <> 18 --'Not Mapped'
ORDER BY
OfficeGroup -- this should return it in alphabetical order but nogame.
-- I also tried passing the ASC command but neither worked
This is the table from the database, I am displaying the query on a webpage and it shows in the same order which is appears on in the table. I used ASC
but no luck this is a string type (varchar(32)
).
This is the function that makes the query for my webpage, I don't see anything wrong with it:
public static List<Market> GetMarketGroup()
{
List<Market> regionList = new List<Market>();
using (SqlConnection connection = new SqlConnection(_constring))
{
StringBuilder sqlCommandBuilderTxt = new StringBuilder();
sqlCommandBuilderTxt.Append("SELECT OfficeGroupID,OfficeGroup FROM tblofficegroup INNER JOIN tblRegion ON tblOfficeGroup.RegionID = tblRegion.RegionID WHERE ISNULL(tblofficegroup.Hide, 0) = 0 AND ISNULL(tblRegion.Hide, 0) = 0 AND OfficeGroupID <> 18 --'Not Mapped' ORDER BY OfficeGroup ASC ");
SqlCommand sqlCommand = new SqlCommand(sqlCommandBuilderTxt.ToString(), connection);
try
{
connection.Open();
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read())
{
try
{
Market market = new Market();// instance
market.MarketID = reader.GetInt32(0);
market.MarketGroup = reader.GetString(1);
regionList.Add(market);
}
catch (Exception ex)
{
log.Error(ex);
}
}
reader.Close();
connection.Close();
}
catch (Exception ex)
{
log.Error(ex);
}
}
return regionList;
}
Be carefull with the tool (client) you use to execute the query. you are using
--
to comment a part of your statement, your client may wrap your query into a single line and then ignore the order by clauseconsider using an other style of comment:
/* comment here */