incorrect results while passing a datetime instead of getdate() - sql

I am working on a SQL query which returns all records between two dates from a table as follows
select convert(varchar(2),TestDate,108) from dbo.Table
where TestDate between convert(datetime,convert(varchar,GETDATE(),101))
and dateadd(day,1,convert(datetime,convert(varchar,GETDATE(),101)))
The above query works fine and gives me the desired results but when I tried to use a normal date string instead of getdate(), the query returns and empty result as follows
select convert(varchar(2),TestDate,108) from dbo.Table
where TestDate between convert(datetime,convert(varchar,'2015-12-27 00:00:00.000',101)) and dateadd(day,1,convert(datetime,convert(varchar,2015-12-27 00:00:00.000',101)))
The above query returns an empty result set which is not what I wanted.
I tried passing date string in different formats but that didn't work.
May I know a correct way to do it?

Why would you convert dates to a string for comparisons? Just do the comparisons as dates.
In addition, you can use datepart() to extract the hour, rather than using some esoteric format to convert():
select datepart(hour, TestDate)
from dbo.Table
where TestDate between cast(GETDATE() as date) and
cast(dateadd(day, 1, getdate()) as date)
If you want the hour as a string instead of a number, then use datename() rather than datepart().

I guess that you are having an extra CONVERT.
Wherever you have this
convert(varchar,GETDATE(),101)
just replace with your date:
'2015-12-27 00:00:00.000'
because the purpose of the CONVERT function is to translate a Date into a Varchar

In addition to Gordon's answer, you can substitute string dates as so:
select datepart(hour, TestDate)
from dbo.Table
where TestDate between cast('2015-12-27 00:00:00.000' as date) and
cast(dateadd(day, 1, '2015-12-27 00:00:00.000') as date)
Assuming this is for a webapp, be sure to use placeholders instead of actual text to prevent SQL insertion attacks.

Related

Change a datetime2 column to date

I'm trying to convert a column in SQL Server Express from a datetime2(7) format to a date format.
I have tried convert, a number of different ways with brackets and parenthesis but I'm having issues either with 'binding' or syntax.
dbo.stateByStatehood.annexDate
USE bigCity
--1.
SELECT CONVERT(datetime2(7), GETDATE()) annexDate;
--2.
SELECT CONVERT (datetime2(7)), stateByStatehood.annexDate date
You can go for cast to date datatype as given below:
SELECT CONVERT(date, GETDATE()) as annexDate;
SELECT CAST(GETDATE() AS DATE) as annexDate
annexDate
2021-08-27

Why does my query return records which doesn't meet the where clause conditions?

I have written a query which returns records with dates that are actually older than the mentioned date.
Declare #DateFrom date
Set #DateFrom= '02/Oct/2019'
SELECT 1, Convert(varchar(11), AppliedDateTime, 106)
FROM [MC_Tenders].[dbo].[AppliedWorks]
Where
Convert(varchar, AppliedDateTime,106) >= Convert(varchar, #DateFrom,106)
Applied dates are saved in table as datetime e.g. 2017-04-25 15:51:25.257
You are doing the comparison as strings rather than dates. Remove the conversion:
SELECT 1, Convert(varchar(11), AppliedDateTime, 106)
FROM [MC_Tenders].[dbo].[AppliedWorks]
WHERE AppliedDateTime >= #DateFrom;
Type 106 is dd mm yyyy. When you compare as strings, the strings are compared, not the dates. With format 106, the days are compared first, so: '18-10-2017' < '25-12-1900' because "1" < "2".
Just to finish Gordon Linoff's thought, your code should look something like this:
SELECT
1
, CAST(AppliedDateTime AS DATE) AS AppliedDate
FROM
[MC_Tenders].[dbo].[AppliedWorks]
WHERE
CAST(AppliedDateTime AS DATE) >= #DateFrom;
Edit: I'm assuming AppliedDateTime is actually stored as a datetime, or some data type other than DATE. The explicit CAST to the DATE type will strip out the time component and allow SQL to just compare the date component to your variable.

Removed Time from Date in SQL

I wrote the following query. This query returns two fields. Firstly, it returns an integer that represents a date, and it then converts that integer into a date.
select DISTINCT date_column,
cast(convert(varchar(10), date_column) as date) as [Week Label]
from table_one
order by date_column desc;
The conversion works well. However, the date that is returned contains a time. How can I get rid of the time?
You can simply use this to remove time part
convert(date, getdate())
OR
you can use this also
convert(varchar(10), getdate(),120)
convert(varchar(10), getdate(),101) doesn't have a time part, just the date.
I used http://www.w3schools.com/sql/func_convert.asp for the options but this one from MSDN may be better: http://msdn.microsoft.com/en-us/library/ms187928.aspx

How to filter only the date from a string stored in a varchar

Ii have values stored in the SQL Server in the following manner : 02-Jul-12 12:00:00 AM here the time and minutes, seconds can be anything like 02-Jul-12 12:15:52 PM ,02-Jul-12 6:02:12 AM so on.
I want to have a where condition which will omit the time and take the data based on the date like the following where some_Date='02-Jul-12'
How would I do this?
SELECT * FROM whatever WHERE some_Date LIKE '02-Jul-12%';
If you are on SQL2008 or later, you can cast your DATETIME to DATE.
See this post: http://blog.sqlauthority.com/2012/09/12/sql-server-get-date-and-time-from-current-datetime-sql-in-sixty-seconds-025-video/
But in a WHERE-clause it is better to search between dates, like this:
DECLARE #startDate DATETIME = '02-Jul-2012'
DECLARE #endDate DATETIME = DATEADD(DAY, 1, #startDate)
SELECT * FROM [table] WHERE [some_Date] BETWEEN #startDate AND #endDate
SELECT * FROM dbo.tbl_MyTable
WHERE
REPLACE(CONVERT(VARCHAR(9), DateTimeValueColumn, 6), ' ', '-')='02-Jul-12'
or
On chage in code is instead of using getdate function voncert you datestring in datetime format and do compare this follow query will work for you
SELECT * FROM dbo.tbl_MyTable
WHERE
CAST(CONVERT(CHAR(10), DateTimeValueColumn, 102) AS DATE) =
CAST(CONVERT(CHAR(10),GETDATE(),102) AS DATE)
If you are storing dates as characters -- which is not recommended -- you should at least use ISO format: YYYY-MM-DD hh:mm:ss. This makes the date useful for sorting and comparisons ("<" works, ">" works, "between" works as well as equals).
To extract the date, you can then use left(datestr, 10). In your format, you would use:
where left(datestr, 9) = '01-Jan-13'
If you are storing the fields as a datetime or smalldatetime, you may think they are stored as a string. They are not. They are stored as some number of days since some particular date, with day parts stored as fractional days. If you are using SQL Server 2005 or greater, then the best way is:
where cast(datetime as date) = '2013-01-01' -- I recommend ISO formats, even for constants. '20130101' is even better
To select rows with today's date (not time)
select * from myTable where datediff(dd, dateColumn, getdate()) = 0

Microsoft SQL Server 2008 - Dates

I have a couple of questions in regards to dates in SQL Server.
How do I separate a datetime value "2011-08-10 14:56:17.267" into date and timestamp in two separate columns. Eg. Date "2011-08-10" and timestamp "14:56:17"
I want remove the timestamp from datetime value into "2011-08-10" and still be able to order the data by date (therefore not converted to varchar). Also is there away to change the date value as '10 Aug 2011' and still can sort (not alphabetically but in real date order).
Thank you,
HL
For the first one:
UPDATE atable
SET
DateColumn = CAST(DateTimeColumn AS date),
TimeColumn = CAST(DateTimeColumn AS time)
As for the second one, date display format is something that is unrelated to the date value. You can order the result set by your date column, but in the SELECT clause you can use CONVERT to display the date in the desired format. For example:
SELECT
CONVERT(varchar, DateColumn, 106) AS Date,
…
FROM atable
ORDER BY DateColumn
use CONVERT function with parameters from resource http://www.mssqltips.com/tip.asp?tip=1145
-- simple conversion example:
SELECT CONVERT(VARCHAR(10), GETDATE(), 102) -- for date
SELECT CONVERT(VARCHAR(10), GETDATE(), 8) -- for time