MS SQL Server Convert Date - sql-server-2016

I have a Date column, within it, dates are in two formats, see below.
Date
------------------------
2/28/2017 10:00
2017-03-15 10:00:00
I want to convert the dates that are mm/dd/yyyy to yyyy-mm-yy within the date column, however, my script is not converting rows that are mm/dd/yyyy.
I am not sure what I else I might be missing or doing wrong.
My script
SELECT
CONVERT(NVARCHAR, DateColumn, 120) AS [Receipt Date]
FROM
databasename.dbo.sales

Review your SQL Statement NVARCHAR needs a declaration on lenght: NVarchar(10)
declare #mydate datetime
set #mydate = GETDATE();
select CONVERT(nvarchar(10),#mydate,120)

Use
SET DateFormat dmy
Or
SET LANGUAGE French;
Then
declare #mydate datetime
set #mydate = GETDATE();
select CONVERT(nvarchar(10),#mydate,12
0)

Related

Date losing value when being stored

I'm trying to get a set of dates into a particular format (ddmmyy) so that they can be run against a number of scripts that I have.
I have managed to convert the date into the correct format, but when I try to store this as a variable it just returns as null or the un-formatted date.
DECLARE #CurrentDate SMALLDATETIME
SELECT #CurrentDate = getdate()
SELECT #CurrentDate = DATEADD(day, -1, #CurrentDate)
SELECT #CurrentDate = STR_REPLACE(CONVERT(varchar,#CurrentDate,3),'/',null)
--Returns this:
20-Mar-2002 00:00:00
DECLARE #CurrentDate SMALLDATETIME
SELECT #CurrentDate = getdate()
SELECT #CurrentDate = DATEADD(day, -1, #CurrentDate)
SELECT STR_REPLACE(CONVERT(varchar,#CurrentDate,3),'/',null)
--Returns this:
020320
I believe the problem comes from the fact that my declared variable is a smalldatetime object but I'm not sure of how to convert it correctly into a string that can be stored as a variable?
I've tried having a second variable and declaring it as a varchar and then storing my date as the varchar but this isn't working either:
DECLARE #CurrentDate SMALLDATETIME
DECLARE #CurrentDateFinal VARCHAR
SELECT #CurrentDate = getdate()
SELECT #CurrentDate = DATEADD(day, -1, #CurrentDate)
SELECT #CurrentDateFinal = CAST(STR_REPLACE(#CurrentDate,'/',null) AS VARCHAR)
--Returns this:
03-Mar-2020 00:00:00
You can do the current date amendment with the dateadd all in one line - there's no need to do two lines. The below gives you the DDMMYY output although I wouldn't use that format personally as you can come unstuck with regional differences (e.g. US prefer MMDDYY and UK tends to be DDMMYY). Also always use 4 digit years IMO.
DECLARE #FirstDate SMALLDATETIME
DECLARE #FinalDate varchar(20)
SELECT #FirstDate = DATEADD(day, -1,getdate())
set #FinalDate = STR_REPLACE(CONVERT(varchar,#FirstDate,3),'/',null)
SELECT #FinalDate
--------------------
030320
(1 row affected)

SQL Conversion error when converting date and/or time from character string

Query from yesterday date from 5pm
Declare #DATEFROM DATETIME=CONVERT(VARCHAR(10),GETDATE()-1,103) + '17:00:00.00'
select #DATEFROM
Expecting 2018-02-05 17:00:00
Conversion failed when converting date and/or time from character string.
SQL Server 2008. Need format yyyy-mm-dd (2018-02-05 17:22:00.000)
An easy implementation:
SELECT DATEADD(HOUR, 17, GETDATE()-1 - CAST(getDate() as time))
Instead of adding a date string, use dateadd:
Declare #DATEFROM DATETIME=dateadd(hh,17,CONVERT(VARCHAR(10),GETDATE()-1,103))
select #DATEFROM
Or if you must add a date string, cast it into a datetime first:
Declare #DATEFROM DATETIME=CONVERT(VARCHAR(10),GETDATE()-1,103) + cast('17:00:00.00' as datetime)
select #DATEFROM
You have to get varchar first and then cast back to datetime
Declare #DATEFROM varchar(22) = CONVERT(VARCHAR(10),GETDATE()-1,103) + ' 17:00:00.00'
select CAST(#DATEFROM AS datetime)
I'm not sure what you are trying to accomplish, however this will produce the date with the time index you are looking for, unless specifically you're looking for yesterday's date in which you can replace the first 0 with 1
declare #date datetime = dateadd(day, datediff(day, 0, sysdatetime()), 0) + .70833333333333333333
select #date
declare #dateFrom datetime=cast(dateAdd(dd, - 1,cast(getDate() as date) ) as datetime) +'17:00:00'

Concatenate date and string to create datetime in SQL

I need to concatenate a datetime and a time field in SQL to a single date time.
e.g I have a datetime of 2017-09-05 00:00:00.000 and a string time of 11:00. What I want is a single field in a view of 2017-09-05 11:00:00.000
I have tried casting the datetime to a date and then concatenate the new date and string date field together but this doesn't work.
To cast the datetime I am using: CAST(dtDate AS DATE) AS dtNewDate which works fine. When I then use: CAST(dtNewDate + szTime AS datetime) AS dtNewDateTime the creation of the view works fine but selecting the top 1000 returns a "conversion failed when converting date and/or time from character string."
Is there an easier way to do this or can anyone offer some advise (other than storing the date and time in a single datetime field in the first place as it is populated by a third party application which I do not have access to change)
You can add two datetime values together, so try:
CAST(dtDate AS DATETIME) + CAST(CAST(szTime AS TIME) as DATETIME)
Assuming 11:00 stands for 11:00:00, you can do something like this:
SELECT dtDate + CONVERT(DateTime, szTime, 108)
FROM...
See a live demo on rextester
You can try following.
DECLARE #YourDate AS DATETIME
SET #YourDate = CONVERT(VARCHAR(10), '2017-09-05 00:00:00.000', 111) + ' 11:00'
PRINT #YourDate
another way is to get the hour from your stringfield, convert it to int, and add that as hours to the datetime
declare #date datetime = '20170905'
declare #stringtime varchar(5) = '11:00'
select left(#stringtime, 2),
dateadd(hour, convert(int, left(#stringtime, 2)), #date)
If you also need the minutes you can do it like this :
declare #date datetime = '20170905'
declare #stringtime varchar(5) = '11:05'
select left(#stringtime, 2),
right(#stringtime, 2),
dateadd(minute, convert(int, right(#stringtime, 2)), dateadd(hour, convert(int, left(#stringtime, 2)), #date))
This will only work if the stringfield is always in format hh:mm
If you care about precision with DATETIME2,
DECLARE #D DATETIME = '2017-01-01';
DECLARE #T varchar(7) = '11:00';
SELECT DATEADD(day, DATEDIFF(day, '19000101', #D), CAST(CAST(#T AS TIME) AS DATETIME2(7)));
Running example here

SQL Server 2008 Date parameter

I'm passing a start date and end date parameter to my stored procedure. I'm doing a simple test here:
DECLARE #StartDate DATE = '10/06/2013' --dd/mm/yyyy
SELECT #StartDate -- this statement running successfully
DECLARE #EndDate DATE = '30/06/2013' --dd/mm/yyyy
SELECT #EndDate -- this statement giving error
This statement returns the following error
Msg 241, Level 16, State 1, Line 2
Conversion failed when converting date and/or time from character string.
Does anybody have idea what's going wrong with EndDate?
I'm pretty sure the error is on this line:
DECLARE #EndDate DATE = '30/06/2013' --dd/mm/yyyy
Not on the SELECT. It wouldn't make sense that it would be on the SELECT, because processing a variable should be fine.
I would recommend that you use YYYYMMDD formats. The following is my preference:
DECLARE #EndDate DATE = '2013-30-06' ;
However, it can fail for certain internationalization settings. The following is documented to always work:
DECLARE #EndDate DATE = '20133006' ;
'10/06/2013' means 06-Oct-2013 not 10-Jun-2013. There is nothing exists with month 30 as in your #EndDate '30/06/2013'.
DECLARE #StartDate DATE='10/06/2013'
DECLARE #DummyDate DATE = '2013-Oct-06'
IF #StartDate = #DummyDate
BEGIN
SELECT 1
END
By default sql server takes date value in 'yyyy-mm-dd' format,
So you need to follow that format or you need to convert date format accordingly.
T-SQL convert string to datetime - SQL Server convert string to date
SELECT convert(datetime, '10/23/2016', 101) -- mm/dd/yyyy
SELECT convert(datetime, '2016.10.23', 102) -- yyyy.mm.dd
SELECT convert(datetime, '23/10/2016', 103) -- dd/mm/yyyy
SELECT convert(datetime, '23.10.2016', 104) -- dd.mm.yyyy
SELECT convert(datetime, '23-10-2016', 105) -- dd-mm-yyyy
-- mon types are nondeterministic conversions, dependent on language setting
SELECT convert(datetime, '23 OCT 2016', 106) -- dd mon yyyy
SELECT convert(datetime, 'Oct 23, 2016', 107) -- mon dd, yyyy
-- SQL string to datetime conversion without century - some exceptions
SELECT convert(datetime, '10/23/16', 1)   -- mm/dd/yy
SELECT convert(datetime, '16.10.23', 2)   -- yy.mm.dd
SELECT convert(datetime, '23/10/16', 3)   -- dd/mm/yy
SELECT convert(datetime, '23.10.16', 4)   -- dd.mm.yy
SELECT convert(datetime, '23-10-16', 5)   -- dd-mm-yy
SELECT convert(datetime, '23 OCT 16', 6)  -- dd mon yy
SELECT convert(datetime, 'Oct 23, 16', 7) -- mon dd, yy

Best way to compare dates without time in SQL Server

select * from sampleTable
where CONVERT(VARCHAR(20),DateCreated,101)
= CONVERT(VARCHAR(20),CAST('Feb 15 2012 7:00:00:000PM' AS DATETIME),101)
I want to compare date without time
Is above query is ok? or other better solution you suggest
I am using SQL Server 2005
Date saved in UTC format on server
Users against this data belongs different timezone
Simple Cast to Date will resolve the problem.
DECLARE #Date datetime = '04/01/2016 12:01:31'
DECLARE #Date2 datetime = '04/01/2016'
SELECT CAST(#Date as date)
SELECT CASE When (CAST(#Date as date) = CAST(#Date2 as date)) Then 1 Else 0 End
Don't use convert - that involves strings for no reason. A trick is that a datetime is actually a numeric, and the days is the integer part (time is the decimal fraction); hence the day is the FLOOR of the value: this is then just math, not strings - much faster
declare #when datetime = GETUTCDATE()
select #when -- date + time
declare #day datetime = CAST(FLOOR(CAST(#when as float)) as datetime)
select #day -- date only
In your case, no need to convert back to datetime; and using a range allows the most efficent comparisons (especially if indexed):
declare #when datetime = 'Feb 15 2012 7:00:00:000PM'
declare #min datetime = FLOOR(CAST(#when as float))
declare #max datetime = DATEADD(day, 1, #min)
select * from sampleTable where DateCreated >= #min and DateCreated < #max
SELECT .......
FROM ........
WHERE
CAST(#DATETIMEVALUE1 as DATE) = CAST(#DATETIMEVALUE2 as DATE)
The disadvantage is that you are casting the filter column.
If there is an index on the filter column, then, since you are casting, the SQL engine can no longer use indexes to filter the date more efficiently.
Description
Don't convert your Date to a varchar and compare because string comparisson is not fast.
It is much faster if you use >= and < to filter your DateCreated column.
If you have no parameter (like in your sample, a string) you should use the ISO Format <Year><Month><Day>.
Sample
According to your sample
DECLARE #startDate DateTime
DECLARE #endDate DateTime
SET #startDate = '20120215'
SET #endDate = DATEADD(d,1,#startDate)
SELECT * FROM sampleTable
WHERE DateCreated >= #startDate AND DateCreated < #endDate
More Information
MSDN - DATEADD (Transact-SQL)
Use 112 CONVERT's format
select *
from sampleTable
where
CONVERT(VARCHAR(20),DateCreated,112)
= CONVERT(VARCHAR(20),CAST('Feb 15 2012 7:00:00:000PM' AS DATETIME),112)
or
if your sql server version 2008+ use DATE type
select * from sampleTable
where CONVERT(DATE,DateCreated)
= CONVERT(DATE,CAST('Feb 15 2012 7:00:00:000PM' AS DATETIME))
declare #DateToday Date= '2019-10-1';
print #DateToday;
print Abs(datediff(day, #DateToday,CAST('oct 1 2019 7:00:00:000PM' AS DATETIME))) < 3
this is compare whin 3 days.
i test this on SQL Server 2014, it works.
select * from sampleTable
where date_created ='20120215'
This will also compare your column with the particular date
without taking time into account