one of my column in my table is of type varchar. which contains hexadecimal values. i need to take average for particular month . the below is my query. please help me how to change the code to achieve it.
select avg(hex) from history where Date between '2016-11-01' and '2017-11-29' group by Date;
Thanks in advance
Advertisement
Answer
You can use CAST
to DateTime
SqlCommand command = new SqlCommand("SELECT Top 1 CAST(TimeStamp AS DATETIME) as TimeStamp FROM HistoryReport ", conn);
For example
SELECT CAST('2017/10/10' AS DATETIME)
The filed should be a DateTime
string or they will be error
EDIT
A small example for you.
The keyPoint is command.ExecuteReader()
get the SQL Query Collection.
string commandText = "SELECT Top 1 CAST(TimeStamp AS DATETIME) as TimeStamp FROM HistoryReport "; string connectionString = "your Connection string"; using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(commandText, conn); try { connection.Open(); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { DateTime date = reader[0] as DateTime; } } catch (Exception ex) { Console.WriteLine(ex.Message); } }