MVC 5 and SQL Server date filter issue - sql-server-2005

I have datetime values in my database table like 05/05/2015 23:00:00. I am putting date filter in my query and try to fetch all the data of 05/05/2015 like this:
select *
from table
where date <= "05/05/2015".
It's not returning the records which have value 05/05/2015 23:00:00 in database.
Please suggest the way..

Using this where clause here
where date <= "05/05/2015"
means: return every row with a date before 05/05/2015 (including the ones with 05/05/2015 00:00:00 - but nothing more).
If you want to get all records for that day, too, you should use
where date < '20150506'
I'd also recommend to use the ISO-8601 date format yyyyMMdd to prevent any regional settings from interfering with your strings representing dates.
And I would also recommend to use something more expressive than just date for your column name - in SQL Server 2008 and newer, DATE is a reserved T-SQL keyword, too - use something like HireDate, SaleDate or something that tells you want kind of date this is

Related

count records in specific date format with SQL

i'm trying to define a rule that count rows where date format is dd/mm/yyyy and greater than a specific date in sql but i couldn't find the right function to use.
The second part is working : SELECT COUNT (*) FROM CUSTOMER WHERE DAT_0 >= '01/01/1995' but how could i specify the format too
In Standard SQL, the WHERE clause would look like:
WHERE DAT_0 >= DATE '1995-01-01'
Many databases would simply accept this without the DATE as well:
WHERE DAT_0 >= '1995-01-01'
In your comment DATE_0 is a date column
Therefore we can change it to any format as below using to_char then to_date
to_date(to_char(DATE_0,'yyyymmdd'),'yyyy-mm-dd')
When comparing you can try this, converting the date to_number, i find it very easy
to_number(to_char(DATE_0,'yyyymmdd')) > 19950101
if datatype of "DAT_0" is date or datetime or timestamp , they are recorded as a specific format specified by default datetime setting in your database engine , therefore you can't have multiple format inside the column , so there is no concern there

Sql Server Table date query showing incorrect result

I have a Sql server table which contains below Date values(4th october)
Now Below query is not showing any result
select
*
from [dbo].[TB_AUDIT] TBA
where TBA.ActionDate >= '10/01/2018' and TBA.ActionDate <= '10/04/2018' which is not correct.
But If I write
select
*
from [dbo].[TB_AUDIT] TBA
where TBA.ActionDate >= '10/01/2018' and TBA.ActionDate <= '10/05/2018' it is returning me all results.
What I am doing wrong.
There are two problems with this query. The first, is that it's using a localized string. To me, it looks like it's asking for rows between January and April. The unambiguous date format is YYYYMMDD. YYYY-MM-DD by itself may not work in SQL server as it's still affected by the language. The ODBC date literal, {d'YYYY-MM-DD'} also works unambiguously.
Second, the date parameters have no time which defaults to 00:00. The stored dates though have a time element which means they are outside the search range, even if the date parameter was recognized.
The query should change to :
select
*
from [dbo].[TB_AUDIT] TBA
where
cast(TBA.ActionDate as date) between '20181001' and '20181004'
or
cast(TBA.ActionDate as date) between {d'2018-10-01'} and {d'2018-10-04'}
Normally, applying a function to a field prevents the server from using any indexes. SQL Server is smart enough though to convert this to a query that covers the entire date, essentially similar to
where
TBA.ActionDate >='2018:10:01T00:00' and TBA.ActionDate <'2018-10-05T00:00:00'
When you don't specify a time component for a DATETIME, SQL Server defaults it to midnight. So in your first query, you're asking for all results <='2018-10-04T00:00:00.000'. All of the data points in your table are greater than '2018-10-04T00:00:00.000', so nothing is returned.
You want
TBA.ActionDate >= '2018-10-01T00:00:00.000' and TBA.ActionDate < '2018-10-05T00:00:00.000'`
Use properly formatted dates!
select *
from [dbo].[TB_AUDIT] TBA
where TBA.ActionDate >= '2018-10-01' and TBA.ActionDate <= '2018-10-04'
YYYY-MM-DD isn't just a good idea. It is the ISO standard for date formats, recognized by most databases.
when you just filter by the date, it is with regard to the time as per the standard.

Strange behaviour of Sql query with between operator

There is this strange error in sql query.
The query is something like this.
select * from student where dob between '20150820' and '20150828'
But in the database the column of dob is varchar(14) and is in yyyyMMddhhmmss format,Say my data in the row is (20150827142545).If i fire the above query it should not retrive any rows as i have mentioned yyyyMMdd format in the query.But it retrives the row with yesterday date (i.e 20150827112535) and it cannot get the records with today's date (i.e 20150828144532)
Why is this happening??
Thanks for the help in advance
You can try like this:
select * from student
where convert(date,LEFT(dob,8)) between
convert(date'20150820') and convert(date,'20150828'))
Also as others have commented you need to store your date as Date instead of varchar to avoid such problems in future.
As already mentioned you would need to use the correct date type to have between behave properly.
select *
from student
where convert(date,LEFT(dob,8)) between '20150820' and '20150828'
Sidenote: You don't have to explicitly convert your two dates from text as this will be done implicitly as long as you use an unambiguous date representation, i.e. the ISO standard 'YYYYMMDD' or 'YYYY-MM-DD'. Of course if you're holding the values in variables then use date | datetime datatype
declare #startdate date
declare #enddate date
select *
from student
where convert(date,LEFT(dob,8)) between #startdate and #enddate
Sidenote 2: Performing the functions on your table dob column would prevent any indexes on that column from being used to their full potential in your execution plan and may result in slower execution, if you can, define the correct data type for the table dob column or use a persistent computed column or materialised view if your performance is a real issue.
Sidenote 3: If you need to maintain the time portion in your data i.e. date and time of birth, use the following to ensure all records are captured;
select *
from student
where
convert(date,LEFT(dob,8)) >= '20150820'
and convert(date,LEFT(dob,8)) < dateadd(d,1,'20150828')
All you have to do is to convert first the string to date.
select *
from student
where dob between convert(date, '20150820') and convert(date, '20150828')
Why is this happening?
The comparison is executed from left to right and the order of characters is determined by the codepage in use.
Sort Order
Sort order specifies the way that data values are sorted, affecting
the results of data comparison. The sorting of data is accomplished
through collations, and it can be optimized using indexes.
https://msdn.microsoft.com/en-us/library/ms143726.aspx
There are problems with between in T-SQL.
But if you want a fast answer convert to date first and use >= <= or even datediff to compare - maybe write a between function yourself if you want the easy use like between and no care about begin and start times ...
What do BETWEEN and the devil have in common?

Select most recent records by DB2 date in form of YYYYMMDD

I am importing records from a DB2 data source into a MS SQL Server destination.
The records are coming in with the date format of 20150302/YYYYMMDD, but I only want the last 14 days based on current server date.
Can some advise on how to select based on this date format against DATEADD(d, - 1, { fn CURDATE() }) please.
Thanks!
It would be better to do this on the DB2 side, to reduce the number of records brought over.
Additionally, it's better from a performance standpoint to convert the static date into a numeric date and compare to the column in your table. Rather than convert the numeric date in your table to a actual date type for comparison.
where numdate >= int(replace(char(current_date - 14 days,iso),'-',''))
Doing it this way will allow you to take advantage of an index over numdate. In addition, DB2 will only need to perform this conversion once.
Depending on your platform & version, you may have an easier way to convert from a date data type to a numeric date. But the above works on DB2 for i and should work on most (all?) DB2 versions and platforms.
You may find it worthwhile to create a UDF to do this conversion for you.
If you want logic in SQL Server, then you are in luck, because you can just convert the YYYYMMDD format to a date:
where cast(datecol as date) >= cast(getdate() - 14 as date)
(This assumes no future dates.)
If you want to do this on the DB2 side, you can use to_date():
where to_date(datecol, 'YYYYMMDD') >= current date - 14 days

Datetime Format in Sql server

I have field in sql table DateIn, in table date exists like '01/04/2012 00:00:00'. when i run query on query analyzer DateIn comes like '2012-04-01 00:00:00.000' i am passing date from text box like 'dd/mm/yyyy' format but not working. I have function where i am passing date variable Dim StrDate as DateTime from text box to query. Please guide me.
If the column is datetime please stop thinking it is stored in some format like mm/dd/yyyy or dd/mm/yyyy. Date/time values are stored internally without any of this regional formatting applied - this is just the way Management Studio is presenting it to you. You should write queries using yyyymmdd for date literals, like:
SELECT <cols>
FROM dbo.table
WHERE DateIn >= '20120601'
AND DateIn < '20120626';
Anything else is prone to not work if a different user executes, if the regional settings on the machine change, or if you move your code to another server. Please see:
What do BETWEEN and the devil have in common?
Bad habits to kick : mis-handling date / range queries
Also be sure you are using string delimiters. If you say:
WHERE DateIn > 01/06/2012
That is the same as:
WHERE DateIn > (1 divided by 6 divided by 2012)
Which yields, due to integer math:
WHERE DateIn > 0
In SQL Server, 0 as a date/time is '1900-01-01' - therefore this clause will return all non-NULL rows.