Converting a Date to Datetime gives error in sql - sql

I am storing a date in a varchar(50) column with values like thie:
1/01/2018
I want to convert these to a Datetime value eg: 2018-01-22 00:00:00.0000000
My SQL is like;
select
[Site],
CONVERT(VARCHAR(50), CAST([InvDay] AS DATETIME), 101) as Date,
from tableA;
But I am getting;
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
I tried like this also but same error;
CONVERT(datetime, [InvDay]) as Date,
How can I make this work?

Look at the values that cannot be converted:
select invday
from tableA
where try_cast(invday as date) is null and invday is not null;
It is also unclear if your format is mm/dd/yyyy or dd/mm/yyyy. You can specify a format using convert():
-- mm/dd/yyyy
select invday
from tableA
where try_convert(date, invday, 101) is null and
invday is not null;
-- dd/mm/yyyy
select invday
from tableA
where try_convert(date, invday, 103) is null and
invday is not null;

I think you want to use set dateformat dmy. Here is an example:
declare #d varchar(15)
set #d='13/1/2018'
set dateformat dmy
select convert(datetime,#d)

Related

Convert varchar to date without timestamp

I am trying to convert/select the nvarchar datatype to date format (YYYY-MM-DD).
The table contains the date in DD/MM/YYYY format & also the null values.
Below SQL query is working fine but it has timestamp in the output
select Date4 = Convert(datetime, Last_Paid_Date, 103) FROM table
2021-01-30 00:00:00.000
My requirement is to have only the date in (YYYY-MM-DD) format
normally this should work
select Convert(date, Last_Paid_Date, 103) from tablename
But if you get conversion errors you can try this
SELECT convert(date, convert(datetime, Last_Paid_Date, 103)) FROM TableName
if Date cannot be used to convert from your format, the trick is to convert to a datetime first, and then convert that into a date.
Much much better would be to store the data in a column with type Date instead of varchar off course
I find this also some good reading
EDIT
if you keep getting conversion errors, then probably there are invalid dates in your varchar column. That is why you should never never never store dates/time in a varchar column.
To fix this, you could use this
SELECT try_Convert(date, Last_Paid_Date, 103) from tablename
this will put NULL in all columns that have an invalid date/time.
Drawback is that from all the rows that will have a value NULL, you cannot know if the original value was also NULL or an invalid date/time value.
Please try the below.
SELECT Date4 = CONVERT(DATE, Last_Paid_Date, 103) FROM TableName
OR
SELECT Date4 = CAST(GETDATE() AS DATE) FROM TableName
This will remove the Timestamp and give you only the Date values in the (YYYY-MM-DD) format.
You can go for simple conversion.
SELECT Convert(date, '20/01/2020', 103)
2020-01-20
You can go for conversion for the table as given below:
SELECT Convert(date, val, 103) as dateval FROM
(
values
('20/01/2020'),(null)
) as t(val)
dateval
2020-01-20
NULL
The issue with your query is that the column: "Last_Paid_Date" contains NULL String, which needs the conversion as they are characters.
You can try the below query:
SELECT convert(date, REPLACE(Last_Paid_Date,'NULL','01/01/2001'), 103)
, convert(datetime, REPLACE(Last_Paid_Date,'NULL','01/01/2001'), 103)
FROM table
The query will replace the NULL strings with a default value if any and then do the date/datetime conversions accordingly
You can chain two conversions : the first one converts the original dd/mm/yyyy (103) to a datetime value, and the second conversion turns that datetime into a yyyy-mm-dd (120) string.
select Date4 = convert(varchar(10), convert(date, Last_Paid_Date, 103), 120)
from table

How to convert string in 'DD/MM/YYYY' or 'YYYY-MM-DD' into date in SQL Server?

I've got a string here which needs to be converted into date but the problem is that it could either be in 'DD/MM/YYYY' or 'YYYY-MM-DD' format.
I've already tried convert which only works for one of the two formats but not both:
declare #string nvarchar(255) = '2019-05-21'
declare #table table (date date)
insert into #table
select convert(date, #string, 111) as date
select * from #table
declare #string nvarchar(255) = '21/05/2019'
declare #table table (date date)
insert into #table
select convert(date, #string, 103) as date
select * from #table
Both of the above solutions result in an error is I use the other format.
Is there a way to get a string converted to date regardless of what format it is in?
Use try_convert():
insert into #table
select coalesce(try_convert(date, #string, 111),
try_convert(date, #string, 103)
) as date
try_convert() returns NULL if the conversion fails. In that case, the conversion will move on to the next pattern. With coalesce(), you can have as many different formats as you like.
You can use TRY_PARSE or PARSE to parse the date literal using a specific culture.
The second format YYYY-MM-DD is an unambiguous date format for the "new" date types like date and datetime2. It's not affected by the DATEFORMAT setting like datetime.
This means you only need to find one culture that can handle the first format. All of the following queries will return the same value :
select parse('21/05/2019' as date using 'en-GB')
-----
2019-05-21
select parse('2019-05-21' as date using 'en-GB')
-----
2019-05-21
select try_parse('21/05/2019' as date using 'en-GB')
-----
2019-05-21
select try_parse('2019-05-21' as date using 'en-GB')
-----
2019-05-21
If you are on SQL 2012 and above, you can use the FORMAT function.
The signature of this function is - FORMAT (value,format[,culture])
Example: SELECT FORMAT (getdate(), 'dd-MM-yyyy') as date and in your case SELECT FORMAT(CAST(<str_value> as DATE), 'yyyy-mm-dd')

sql server convert datetime failed

I want to convert this time_stamp column (nvarchar50) into datetime column in SQL server. the value of time_stamp is "2018-02-16 13:30:27+09:00".
I don't know which datetime code should I use to convert it. Can you help?
This is what I tried:
select convert(datetime,time_stamp, 110) from table;
select convert(datetime,time_stamp, 120) from table;
It is failing because of the timezone embedded in the string. However, it will work if you remove the timezone using string function such as LEFT.
SELECT CONVERT(DATETIME, LEFT(time_stamp, 19), 110)
FROM tableName
Here's a Demo.
There is timezone offset in your sample date. If we want to ignore timezone offset then we can use below code -
declare #x nvarchar(50) = '2018-02-16 13:30:27+09:00'
select convert(datetime,convert(datetimeoffset, #x))
Declare #dt NVARCHAR(100) = '2018-02-16 13:30:27+09:00'
select CAST(SWITCHOFFSET(TODATETIMEOFFSET( LEFT(#dt , 19) ,RIGHT(#dt, 6)),0) AS DATETIME)
Returns:
2018-02-16 04:30:27.000

ddmmyyyy to sql datetime in SQL

I need to convert a nvarchar value to datetime in T-SQL. The value is in ddmmyyyy format, e.g. 23072009
I need to convert to datetime in T-SQL.
I tried
select convert(datetime, '23072009', 103)
But it is throwing error.
"The conversion of a nvarchar data type to a datetime data type
resulted in an out-of-range value."
Any idea
Thanks
Rebuild your format to yyyymmdd.
declare #D varchar(8)
set #D = '23072009'
select cast(right(#D, 4)+substring(#D, 3, 2)+left(#D, 2) as datetime)
The style 103 will accept strings with dd/mm/yyyy format. So your code should be
declare #date varchar(8)
set #date='23072009'
select convert(datetime,stuff(stuff(#date,5,0,'/'),3,0,'/') , 103)
You can define custom function like this:
CREATE FUNCTION [dbo].[GetCustomDate] (#customDateString NVARCHAR(MAX))
RETURNS DATETIME
AS
BEGIN
RETURN CONVERT(DATETIME, RIGHT(#customDateString, 4) + RIGHT(LEFT(#customDateString, 4), 2) + LEFT(#customDateString, 2))
END
Change VARCHAR (dd-mm-yyyy) to date (yyyy-mm-dd) in SQL Server.
DECLARE #VarDate VARCHAR(10)
SET #VarDate = '22-02-1994'
SELECT CONVERT(DATETIME, CONVERT(VARCHAR, CONVERT(DATE, #VarDate, 103), 102))
You need to cast a string and not a int. Put some quotes:
convert(datetime, '23072009', 103)
And 103 gets the string like 'dd/mm/yyyy' and not 'ddmmyyyy'.

conversion of a varchar datatype to a datetime datatype resulted in an out-of-range value

The conversion of a varchar datatype to a datetime datatype resulted in an out-of-range value
select a.DLNO,
a.NAME,
b.TOPSTRING,
Convert(datetime,a.DOB,103) as DOB,
Convert(datetime,a.DOI,103) as DOI,
Convert(datetime,b.datepushed,103) as datepushed
from
PLInfo_Demo a,DLInfo_Demo b
where
a.dlno=b.DLNO
Type 103 requires that you have datetimes with the European date/month order: 'dd/mm/yyyy'
If you store month first, this may result in this error (say for '01/13/2012')
If it's the case, use type 101 ('mm/dd/yyyy')
It's always better to store datetimes as DATETIME.
sp_helptext sp_displayClinicRecordsbyclinicid
alter procedure sp_displayClinicRecordsbyclinicid
(
#id bigint,
#category char(1)
)
as
select id,ClinicName,
CONVERT(varchar(10), cast(Visitdate as datetime),101) Visitdate ,
CONVERT(varchar(19), cast(visitTime as datetime) ,101) visitTime ,
patient_first,patient_last,patient_address,patient_city,patient_state, CONVERT(varchar(10), cast(patient_dob as datetime),101) patient_dob,
precriber,prescriptionnum,CONVERT(varchar(10),cast(pharmacyfilldate as datetime) ,101) pharmacyfilldate,CONVERT(varchar(10),cast(prescriptionenddate as datetime) ,101) prescriptionenddate,drugname,drugformat,npi,dea,
licence,clinicid,Category,PatientFullname,Prescriber_first,Prescriber_last,Qty,Days
from tblClinicRecords where clinicid=#id and Category=#category