Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select distinct year from a datetime column and add the result to a comboBox in C#?

I am using visual studio 2010 and SQL Management Studio R2 Although the sql query works fine in sql management studio. Its throws an exception in visual studio. Out of index exception whem i edit to make any other adjustments it throws Out of format exception. Please Help me. The code is as follows:

 string sql = "SELECT DISTINCT Year(tdate) FROM saletransaction ORDER BY Year(tdate) DESC";
 cmd = new SqlCommand(sql, con);                
 dr = cmd.ExecuteReader();
 DateTime dt;
 while (dr.Read())
 {
     if (dr.HasRows == true)
     {
         dt = Convert.ToDateTime(dr["tdate"].ToString()); //tdate is the name of the column (getting an error at this line. )
         comboBox1.Items.Add(dt.Year.ToString());
     }
 }
like image 640
Suvee - Avatar asked May 02 '13 08:05

Suvee -


People also ask

How do I SELECT just the year from a datetime in SQL?

Use the YEAR() function to retrieve the year value from a date/datetime/timestamp column in MySQL. This function takes only one argument – a date or date and time. This can be the name of a date/datetime/timestamp column or an expression returning one of those data types.

How do I filter just the year from a date in SQL?

SQL Year Function This function accepts the date as a literal string or an expression and extracts the year part of the date. Example usage is as shown below: SELECT YEAR(CURRENT_TIMESTAMP); The above returns “2022” as we expected.

Can you use SELECT distinct and GROUP BY?

Well, GROUP BY and DISTINCT have their own use. GROUP BY cannot replace DISTINCT in some situations and DISTINCT cannot take place of GROUP BY. It is as per your choice and situation how you are optimizing both of them and choosing where to use GROUP BY and DISTINCT.


1 Answers

You're not selecting tdate but you select Year(tdate)

I would modify the query to this:

string sql = "SELECT DISTINCT Year(tdate) AS tdate_year FROM saletransaction ORDER BY Year(tdate) DESC";

and access it with dr["tdate_year"]

like image 87
huysentruitw Avatar answered Sep 28 '22 08:09

huysentruitw