Geeks With Blogs
AzamSharp Some day I will know everything. I hope that day never comes.
First let me start by saying this, "The code that you will see below is the worst code I have written". Okay my requirment was to compare the date in the ACCESS database and spit out the results depending on the date. The field in the database was varchar and date was stored as '03-04-2005' (mm-dd-yyyy). Now I needed to fetch all the records of a particular month and year. The barries was the inclusion of the day in the database. The month and year was selected using the dropdownlists. Here is my ugly code:

string query =  @"SELECT * FROM [TableName] WHERE [DateCreated] = ";
			string finalQuery = String.Empty; 

			for(int i=1;i<13;i++) 
				string c = ddlMonth.SelectedItem.Value + "/" + i.ToString() + "/" + ddlYear.SelectedItem.Value; 
				finalQuery += query + "'"+c+"'" + " " + "UNION" + " "; 
			int b =  finalQuery.LastIndexOf("UNION"); 
			string sss = finalQuery.Remove(b,5); 

I hate ACCESS database since it has too many limitations like you cannot run multiple queries which you can do in SQL SERVER. So, I had to make a long query string which joins all the queries by using UNION operator. This is probably the ugliest code I have ever written. What about you ? Posted on Saturday, August 6, 2005 9:17 PM | Back to top

Comments on this post: The ugliest code I have ever written

# re: The ugliest code I have ever written
Requesting Gravatar...
Why not just convert the string to a datetime and then compare it? i.e...

string finalQuery = "Select * from [TableName] where year(cdate([DateCreated])) = " + ddlYear.SelectedItem.Value + " AND month(cdate([DateCreated])) = " + ddlMonth.SelectedItem.Value;

It seems that MSACCESS sees that it can convert those values over to a datetime with no problem. the only issues i can forsee with this query is dealing with nulls and dealing with scenario where the month or year wasn't selected. Although i'm unsure as to if you even have to worry about these, seeing as how ur not dealing with them in your example.

Hope this helps
Left by Jeff Wolfer on Aug 07, 2005 2:19 PM

# re: The ugliest code I have ever written
Requesting Gravatar...
Actually the problem was some what different. The interface only allowed to select Month and the Year and the database contained the Date (mm-dd-yyyy). So I had to attach the dd in the middle.

The above loop should run from 1 to 31 and not from 1 to 12.

Left by AzamSharp on Aug 08, 2005 11:05 AM

Your comment:
 (will show your gravatar)

Copyright © Mohammad Azam | Powered by: