Date comparison doesn't take year into account - sql-server

I'm trying to retrieve records by comparing date values as follows :
declare #fromdate as date
declare #todate as date
set #fromdate='2013-04-01'
set #todate='2013-04-13'
select createdon,
convert(varchar,PhoneCall.createdon,101) as createdon,
convert(varchar,#fromdate,101) as fromdate
from
PhoneCall
where convert(varchar,PhoneCall.createdon,101) >= convert(varchar,#fromdate,101) and convert(varchar,PhoneCall.createdon,101) <= convert(varchar,#todate,101)
There is something wrong in the comparison, I've tried using various conversion formats but I'm not receiving correct results.
The query above has been my latest trial, although it looks correct, it doesn't take into account the comparison of the Year. So the results displayed are as follows:
Createdon ConvertedCreatedOn ConvertedFromDate
2013-05-08 14:13:16.000 05/08/2013 05/01/2013
2014-05-01 17:10:03.000 05/01/2014 05/01/2013
EDIT:
This is a query I'll use for a report. The #fromdate and #todate are report parameters that will be entered manually by the user, so I have to make sure that they're in the same format with the database date format.

Why do you convert all DATE fields/params to VARCHAR? Just use DATE comparison:
where PhoneCall.createdon BETWEEN #fromdate AND #todate
IF you NEED to use varchar then you should use 102 format (yyyy.mm.dd) instead of 101 (mm/dd/yyyy). In this case it can be used to compare dates as strings.

Related

how to have date time column converted into date and displaying as 103 style

Hi i've a column the_date which is having sample data like
1900-01-01 00:00:00.000
1990-01-01 00:00:00.000
1990-01-02 00:00:00.000
1990-01-03 00:00:00.000
1990-01-04 00:00:00.000
1990-01-05 00:00:00.000
1990-01-06 00:00:00.000
1990-01-07 00:00:00.000
now i just want to select only date only and displaying it into 103 style and convert the column into Date format. i've tried this syntaxconvert(varchar,THE_DATE , 103) but then the column is not in Date format.
any help please.
This Works try it once
SELECT CONVERT(varchar,CAST(DATE_TIME AS DATE),103)AS Date_Time From <yourTable>
It's a little confusing because regardless of the datatype, you will always get the same answer with CONVERT. I'll illustrate this with 2 declared variables, 1 datetime datatype, the other date datatype:
DECLARE #mydatetime datetime = '1990-01-01 00:00:00.000'
DECLARE #mydate date = '1900-01-01'
SELECT convert(varchar,#mydatetime, 103) as mydatetime
SELECT convert(varchar,#mydate, 103) as mydate
Produces:
mydatetime
01/01/1990
mydate
01/01/1900
So you don't need to cast to date, then to 103 format.
If you don't like the time with date in your table (datetime) then you can always ALTER the column in the table to the date datatype. This can be done using SSMS or you can do the SQL:
ALTER TABLE mytable ALTER COLUMN mycolumn DATE
Where DATE is the new datatype. And then only the date is stored in the table.
Converting a string (or an equivalent database type) to another type is called "parsing". Converting another type to string is called "formatting".
The DATE or DATETIME type (or equivalent type in the front-end) does not store dates as string and has therefore no format. A number is used to represent the date internally which counts the days since a reference date (1753-01-01 for SQL-Server). The time is represented as decimal fraction.
Of course you always see the date as formatted when you open the table, because it is converted to a text for display, but it is not stored as formatted.
So, what you have to do if your date is given as text, is to parse it using the 121 format (YYYY-MM-DD HH:MI:SS.MMM (24h)) to get a DATE (or DATETIME).
CONVERT(DATE, the_date, 121) or CONVERT(DATETIME, the_date, 121)
If the_date is already of DATE (or DATETIME) type and you want to display it in the 103 format (DD/MM/YYYY)
CONVERT(VARCHAR(10), the_date, 103)
If the date is given as DATETIME type and you just want to strip off the time part and return the result as DATETIME type again, you can do
DATEADD(dd, DATEDIFF(dd, 0, the_date ), 0)
Note that no date format is involved here, since the date does never appear as text.
thanks for all your answer but for anyone who has my same query i got the solution from here
solution

SQL Server - Select between 2 dates of type DD/MM/YYYY

I want to query a datetime field using a range of dates provided in the format DD/MM/YYYY.
I know that to convert datetime to a DD/MM/YYYY format that I can use:
CONVERT(CARCHAR(10), ORDERDATE,103)`
And this works fine when querying a single date, eg:
SELECT DISTINCT
CONVERT(DATE, ORDERDATE),
CONVERT(CARCHAR(10), ORDERDATE,103)
FROM ORDERS
WHERE CONVERT(CARCHAR(10), ORDERDATE,103) = '19/10/2017'
Returns: 2017-10-19, 19/10/2017
However it does not work on a range of dates, eg:
WHERE CONVERT(CARCHAR(10), ORDERDATE,103) BETWEEN '17/10/2017' AND '19/10/2017'
Returns:
2014-02-05
2016-12-12
2013-04-30
I know there are hundreds of threads about SQL dates, but they all seem to be regarding reformatting the output and not preparing the input. Do I need to reformat my DD/MM/YYYY inputs?
To query a range of dates, use the DATE-datatype instead of VARCHAR.
If datatype of column ORDERDATE is DATETIME:
WHERE CONVERT(DATE, ORDERDATE) BETWEEN
CONVERT(DATE, '17/10/2017', 103) AND CONVERT(DATE, '19/10/2017', 103)
The conversion of ORDERDATE is only necessary if the start and end date are the same. (in this case, when no conversion is done, only dates with a time value of '00:00:00.000' will be returned)
EDIT:
To omit the conversion of ORDERDATE you can add the time to the dates and convert them to DATETIME instead of DATE, like this:
WHERE ORDERDATE BETWEEN
CONVERT(DATETIME, '19/10/2017 00:00:00') AND CONVERT(DATETIME, '19/10/2017 23:59:59.999');
Or even simpler, like suggested in #Used_By_Already's answer:
WHERE ORDERDATE >= '20171017' AND ORDERDATE < '20171020' --Note the end date is here +1 day
SQL Server date information should NOT be stored "in a format". If if they are literally stored in that format then they are NOT dates as far as the database is concerned (they are "strings" that look like dates) and you will have a nightmare to deal with if they are DD/MM/YYYY because they simply will not behave like dates should.
There are several specific data types in SQL Server for date/time information (datetime, datetime2, smalldatetime, date, time) but ALL of these do not store data in a human readable format at all. Instead they stored as groups of numbers, which will be displayed in a human readable manner, and in your case - by default - you are seeing then in DD/MM/YYYY format. A user in China might prefer to see a date in YYYY.MM.DD or in the USA as MM/DD/YYYY. This is possible because a human format is applied on top of the numbers that are stored before they get displayed.
So. In SQL Server there is a "safe" date literal in the form of 'YYYYMMDD' and this may be used without the need to CONVERT or CAST:
IF your [ORDERDATE] column is a date (or smalldatetime/datetime/datetime2) then this will work:
WHERE ORDERDATE BETWEEN '20171017' AND '20171019'
OR, you may explicitly convert a string to but you need a "style number" to be present to make these fully reliable. Style 103 for example is for DD/MM/YYYY
WHERE ORDERDATE BETWEEN CONVERT(date, '17/10/2017',103) AND CONVERT(date, '19/10/2017',103)
Although "between" has been used in the discussion above a far more reliable method of forming date ranges is to NOT use "between", instead do it this way:
WHERE ORDERDATE >= '20171017' AND ORDERDATE < '20171020'
With this pattern (note the second day is now +1) it does not matter which date precision is stored in the column. For example, see Bad habits to kick : mis-handling date / range queries

Change value of SSRS report parameter based on the input of another parameter

I have a SSRS 2005 report with three parameters: #FromDate, #ToDate and #Period. #FromDate and #ToDate default to the first day and the last day of last month, respectively.
The #Period parameter is a multi-value parameter. So if I choose for instance "Current quarter", I want the #FromDate and #ToDate to change to the corresponding values based on the input in #Period.
My problem is not getting the correct datetime expressions, but rather how to make the parameters interact with each other as desired.
To achieve your requirement, we need use cascading parameters in SSRS.
In your scenario, you need create the parameter #FromDate that get values from a dataset which select FromDate based on the #Period parameter. Then create parameter #ToDate that get values from a dataset which select ToDate based on the #FromDate parameter.
The following document is for your reference:
https://technet.microsoft.com/en-us/library/aa337498(v=sql.105).aspx

Convert and sort varchar Date dd-MMM-yyyy

I'm using a table that has the date as varchar. example dateformat:
17-Jun-2015
I have tried the following ways to convert and sort the date(dd-MMM-yyyy) to dateTime.
SELECT date, name, author
FROM sometable
ORDER BY CONVERT(DATETIME, date, 106) DESC
I have also tried converting the date in the select statement. doesn't work. The error is
Conversion failed when converting date and/or time from character string.
The conversion types through some similar questions but I have not found any solutions to the format I have. Is there some way of selecting the delimiter between the day month and year??
I also had a browse through this link which has the formats for datetime formats. 106 was the closest to my varchar date. Only my date in the table has '-' between day month and year.
https://msdn.microsoft.com/en-us/library/ms187928.aspx
Appreciate any help.
It should be absolutely fine to use 106 to convert your date format.
But I guess your table contains some of the invalid values in the column causes the error, try to spot them out by TRY_CONVERT:
SELECT date, name, author, TRY_CONVERT(datetime, date, 106) AS convertresult
FROM sometable
WHERE TRY_CONVERT(datetime, date, 106) IS NULL AND date IS NOT NULL
I would use date style 113 to convert to datetime format like this:
DECLARE #date VARCHAR(20) = '17-Jun-2015';
SELECT CONVERT(VARCHAR(20),CAST(#date AS DATETIME),113)

Comparing dates with current date in Sql server

I have a table which has list of some events with dates. I am trying to write a stored procedure that will return only the upcoming events.
I have written the following query in the stored procedure:
SELECT *
FROM Events
WHERE tDate >= (select CAST(GETDATE() as DATE))
But this is not returning correct result. This is also showing results that have dates less than current date. How to write a query that will return all the events that have date equal or greater than today's date.
Edit: Dates that have been entered on the table have the format yyyy/dd/mm and getdate() returns date in the format yyyy/mm/dd. I think this is causing the problem. Dates that have been entered into the table has been taken using jquery date picker. Any solution to this problem?
Not sure why you have an additional select
SELECT *
FROM Events
WHERE tDate >= CAST(GETDATE() as DATE)
your DATE data is incorrectly stored within Sql Server. When your application passes the string '2015-09-04' and you save that your date column, it is saved as 4th Sept 2015 and not 9th April 2015. Hence your query returns such rows as they are greater than GETDATE().
Example
DECLARE #D VARCHAR(10) = '2015-09-04'
SELECT CONVERT(VARCHAR(20),CONVERT(DATE,#D),109)
you need to fix your data and then use a CONVERT with style when saving dates in your table from application, using something like this. CONVERT(DATE, '20150409',112)
DECLARE #D VARCHAR(10) = '20150409'
SELECT CONVERT(VARCHAR(20),CONVERT(DATE,#D,112),109)
Refer these threads for more info:
Impossible to store certain datetime formats in SQL Server
Cast and Convert

Resources