SQL database date column is comparing with current date - c#

My problem is that I want to select records from data base if the date field is greater than current date
I use the following code
SELECT
Id, eve_name, eve_date, eve_place,eve_desc
FROM
EventDetails
WHERE
CONVERT(varchar(10), eve_date, 101) >= CONVERT(varchar(10), " + DateTime.Now.ToShortDateString() + ",101)"
but it is not working
I take date column in database as DateTime.. and save the date time using jquery datetime picker

Assuming the server date is acceptable, and that this is SQL Server (it looks like it since you're using CONVERT), you can just do this in SQL:
SELECT
Id, eve_name, eve_date, eve_place,eve_desc
FROM
EventDetails
WHERE
eve_date >= DATEADD(day,DATEDIFF(day,0,CURRENT_TIMESTAMP),0)
And this can also use an index on eve_date, if one is available - because I'm no longer applying any functions to it. I'm using DATEADD/DATEDIFF to remove the time component from the current datetime (obtained via CURRENT_TIMESTAMP).

If you are using SQL Server, you can use the GETDATE() function. This returns the current date/time. If your date-time fields only contain a DATE part, you will need to strip the time part of the result of GETDATE().
SELECT
*
FROM
eventdetails
WHERE
eve_date>=CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME);
You will see that the time part is stripped of the result of GETDATE() by casting it to float, flooring it and casting it back to DATETIME type. There are other ways of doing this, cf Damien's solution. Since DATETIME under the hood is stored as a FLOAT, only one trivial function is called (FLOOR), and performs better than the DATEADD/DATEDIFF trick.
If the eve_date can also contain a TIME part, and you want to compare only the DATE part, you will also have to CAST/CONVERT the eve_date to make the comparison:
SELECT
*
FROM
eventdetails
WHERE
CAST(FLOOR(CAST(eve_date AS FLOAT)) AS DATETIME)>=CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME);
Now this is all written in the perspective of SQL Server 2005 and below, where a DATE type does not exist. For SQL Server 2008 and above, casting to the DATE type will strip the TIME part away as well:
SELECT
*
FROM
eventdetails
WHERE
CAST(eve_date AS DATE)>=CAST(GETDATE() AS DATE);
Note that the GETDATE function is the equivalent of CURRENT_TIMESTAMP function as defined by ANSI SQL standard.

Try this,
it is simple and fulfills your requirement
:-
Assuming you are using SQL SERVER
SELECT
Id, eve_name, eve_date, eve_place,eve_desc
FROM
EventDetails
WHERE
eve_date >= getdate()
Since in Database eve_date column type is Datetime ,so there should not be any problem.

Change datatype inside CONVERT to datetime from varchar
Try This SQL QUERY:
SELECT
Id, eve_name, eve_date, eve_place,eve_desc
FROM
EventDetails
WHERE
eve_date>= CONVERT(datetime, '#dtp',101)
C# code avaoiding SQL Injection:
try
{
cmd=new SqlCommand(SELECT Id, eve_name, eve_date, eve_place,eve_desc FROM EventDetails WHERE eve_date >= CONVERT(datetime, '#dtp',101),con);
da=new SqlDataAdapter(cmd);
cmd.Parameters.AddWithValue("#dtp", DateTime.Now.ToShortDateString());
ds=new DataSet();
da.fill(ds);
//Further Processing
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
This will work.

Related

C# SQL Server compare date with string

I have to compare a table field that is a date stored as varchar in the format 'dd/MM/yyyy' with a date value, but the comparison fails. I have exception
Conversion failed when converting date and/or time from character string.
I tried converting the date to compare i nstring, like this
string dateFormat = date.ToString("dd/MM/yyyy");
and then write the query like this:
string sql = "select * from TB_RICHIESTE where CONVERT(DATE, Date) <= CONVERT(DATE, '" + dateFormat + "')";
But I have this excpetion. Someone can help me? Thanks
First, you should not store dates as strings.
As Panagiotis Kanavos wrote in his comment - this is a serious bug. You can't sort by such a column, you can't search for date ranges, and most important - you can't control if someone enters an invalid value - nothing is stopping someone from entering "Alfredo" to that column.
For more information, read Aaron Bertrand's Bad habits to kick : choosing the wrong data type.
Second, you should not pass dates from .Net to Sql server as strings. you should pass instances of DateTime as parameters.
The .Net DateTime maps directly to SQL Server's Date.
If you can't change the data type of the column, you can at least convert it to date using the proper convert style (103 in your case).
Here is a better way to do it:
var sql = "select * from TB_RICHIESTE where CONVERT(DATE, [Date], 103) <= #Date";
Then you add the #Date parameter to the SqlCommand:
com.Parameters.Add("#Date", SqlDbType.Date).Value = date.Date;
Use Parameter to pass date values refer #Zohar Peled post. This is the proper method handling date values.
OR
You can pass the date value in ISO format, refer the below code.
string dateFormat = date.ToString("yyyy/MM/dd");
string sql = "select * from TB_RICHIESTE where CONVERT(DATE, Date) <= CONVERT(DATE, '" + dateFormat + "')";

record not fetching from database in SQL query

I am using this command it is not fetching record.
my command
select * from policy_record_manual where (CONVERT(VARCHAR(MAX), enddate, 103) BETWEEN CONVERT(VARCHAR(MAX), '25/02/2015', 103) AND CONVERT(VARCHAR(MAX), '04/03/2015', 103))
I have two records in enddate column which lies between 25/02/2015 and 04/03/2015 but still not fetching any result.
please help
Use proper date formats and your query should work:
select *
from policy_record_manual
where enddate between '2015-02-05' and '2015-03-04'
You are doing the comparison as strings. Don't compare date/times as strings. Compare them using the native types.
You should always compare dates/datetimes with dates - and not strings. Most databases -- including SQL Server -- support the ISO standard for dates and recognize strings in that format.
If you use SQL Server, you can change the date format in the query by using SET DATEFORMAT statement.
set dateformat dmy
declare #begin datetime='25/02/2015'
declare #end datetime='04/03/2015'
select *
from policy_record_manual
where enddate between #begin and #end
try this
select *
from policy_record_manual
where (CONVERT(VARCHAR(MAX), enddate, 103) BETWEEN CONVERT(VARCHAR(MAX), '02/25/2015', 103) AND CONVERT(VARCHAR(MAX), '03/04/2015', 103))

Date Format in a SELECT filter query

I have a field Date type. I'm recording data in the format dd/mm/yyyy.
It's displaying just fine. But when I try to use a filter in my select query it returns me every single row. I tried this:
SELECT *
FROM MyTable
WHERE dt_start >= '01/04/2007'
and
SELECT *
FROM MyTable
WHERE dt_start >= DATE_FORMAT('01/04/2007', "%d/%m/%yyyy")
Now, if I try this, it works perfect:
SELECT *
FROM MyTable
WHERE dt_start >= '2007/04/01'
I know it's the standar MySQL date format on it's Site. But I'd like to know a way to achieve this goal.
The syntax you want to convert your dates is like this:
UPDATE [table name] SET [date field name] = STR_TO_DATE('01/04/2007', '%Y-%m-%d')
That will convert all of our dates to the standard like Gordon Linoff said. IF you want them to look like your dates originally when you pull them out, then you can use dateformat in your query:
SELECT DATE_FORMAT([date field], '%m/%d/%Y') AS myDate FROM [table name]
Does that make sense?
I also agree with Gordon that it's easier to store your dates with the standard format. You can manipulate and compare dates more easily this way.
EDIT
SELECT * FROM [your table] WHERE date >= STR_TO_DATE('01/04/2007', '%m/%d/%Y')
With this, you don't have to change your date types and you can just change the string you want to evaluate against to a date in the where clause. Is that what you wanted?
This has to do with the conversion between dates and strings when you do a comparison. You can put the constant that you want as:
SELECT *
FROM MyTable
WHERE dt_start >= STR_TO_DATE('01/04/2007', '%d/%m/%yyyy') ;
However, I would strongly recommend that you use the ISO standard date format in your queries. This is YYYY-MM-DD. You can output whatever format you like, but using the standard in your queries is a good idea.

Retrieve only todays data from SQL Server database

I need to retrieve only today's data from a SQL Server database table.
I am developing an application in C#, VS 2010 and there is need that to retrieve only today's data.
Not getting the exact query how should it be. Also need to retrieve that data order by Desc.
How can we do this?
Yoou have to take the Date_time Column in Your TABLE That will keep the information of time when your row entered in table.
SELECT Date_Time
FROM TableThantYouWantAcees
WHERE Date_Time = CONVERT(date, Getdate())
ORDER BY Date_Time DESC
GETDATE() is an SQLServer function which will return the today date, like 2013-11-20 14:05:54.943. Cast it in DATE to only keep the date part, ie 2013-11-20.
Try this
SELECT * FROM <table_name>
WHERE <date_field> >= CONVERT(<date_field>,
DATEDIFF(DAY, 0, GETDATE()))ORDER BY <date_field> DESC
Extract the date part from your date_column with convert
select * from your_table
where CONVERT (DATE, date_column) = CONVERT (DATE, GETDATE())
order by date_column desc
If you are concerned about only having the date and not the time, you could so something like this:
SELECT *
FROM tblPhoneAsign
WHERE receivedTime > CAST(FLOOR(CAST(GETDATE() AS FLOAT))AS DATETIME)
That will give you only the date portion of today's date. Doing the adding of zero hours to the GETDATE method is a very complex and costly way of doing things.

How to select a record based on a date which is saved as a string?

The Bill_Date is saved as a string in the database. Now I want to select the records based on this Bill_Date. So I input two dates ie. fromDate and toDate (which are also in string).
All the date values use the U.S. format mm/dd/yyyy (e.g. 11/28/2011).
So how will be the query?
Firstly, your life will be much easier (and the query much faster) if everything was a datetime.
The query (as it stands) would be:
SELECT *
FROM TABLE
WHERE CONVERT(datetime, BILL_Date, 101)
BETWEEN CONVERT(datetime, #fromDate, 101) AND CONVERT(datetime, #toDate, 101)
CONVERT is detailed here.
If the Strings are in the format YYYY-MM-DD (or any other format, where the dates would be chronologically ordered if you sort by the string) you can use between:
select * from table where Bill_date between fromDate and toDate
If a different date format is used you need to parse the strings and create dates, either in c# or in sql. In Oracle you would use TO_DATE, i assume there is something similar in SQL server.

Categories