How to convert SQL string date to usable ISO8601 date? - sql

I have a query that I need to check if one date is less than or equal to another. The date is stored in the table as a string in this format 2/1/2020 The SQL Server version on my testing server is 13.0 and the query below works fine but both staging and production is version 11.0.7. Below query is what I have tried so far but get an error
"Conversion failed when converting date and/or time from character string.".
What is the correct way to write this query so that it works on all of the SQL servers?
SELECT TrackingNumber
FROM CarrierTrackingData
WHERE (SUBSTRING(Status, 1, 9) = 'Delivered') AND (CONVERT(date, CAST(DeliveryDate AS date), 23) <= CONVERT(date, CAST(InStoreDate AS date), 23))
GROUP BY TrackingNumber```

You need 101 century mm/dd/yyyy to convert into date format :
WHERE ( SUBSTRING(Status, 1, 9) = 'Delivered' AND
CONVERT(date, DeliveryDate , 101) <= CONVERT(date, InStoreDate , 101)
);
Note : You don't need to use CAST() as CONVERT() with century will do conversation for you.
EDIT : You can check the possible date format using TRY_CONVERT() :
SELECT DeliveryDate,
TRY_CONVERT(DATE, DeliveryDate, 101) AS Possible_DeliveryDate,
InStoreDate,
TRY_CONVERT(DATE, InStoreDate , 101) AS Possible_InStoreDate
FROM table t;
TRY_CONVERT() will return NULL where the conversation fails.

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

SQL Server - How to convert varchar to date

I have a table containing StartDate in the format dd/mm/yyyy and yyyy-mm-dd.
I want to convert this varchar column to DATE type in the format DD/MM/YYYY.
I have tried the below.
select CONVERT(varchar(20),StartDate,103) AS [FormattedDate]
and
CONVERT(VARCHAR(20),(CAST([StartDate] AS DATE)),103)
I get the error -Conversion failed when converting date and/or time from character string.
Pls suggest.
if you only have the date string in dd/mm/yyyy or yyyy-mm-dd
select case when substring(StartDate, 3, 1) = '/'
then convert(date, StartDate, 103)
else convert(date, StartDate, 121)
end
SQL Server is actually quite good about figuring out formats for a date conversion with no formatting argument. However, it is going to assume MM/DD/YYYY for the second format and generate an error.
So, you can use try_convert() and coalesce():
select coalesce(try_convert(date, startdate, 103),
convert(date, startdate)
)
Here is a SQL Fiddle.
Then, you should go into your data and fix the column. Here is one method:
update t
set startdate = coalesce(try_convert(date, startdate, 103),
convert(date, startdate)
);
alter table t alter column startdate date;
You can add additional formatting for the result set by turning the date back into a string, using convert().
To get YYYY-MM-DD use SELECT CONVERT(varchar, getdate(), 23)
To get MM/DD/YYYY use SELECT CONVERT(varchar, getdate(), 1)
For detailed explaination try this.
Here's an example that first tries to convert the VARCHAR from a 'yyyy-mm-dd' format to the 'dd/mm/yyyy' format.
If that doesn't work out, then it just assumes it's already in the 'dd/mm/yyyy' format.
And then defaults to the first 10 characters from the string.
declare #TestTable table (StartDate varchar(10), DateFormatUsed varchar(10));
insert into #TestTable (StartDate, DateFormatUsed) values
(convert(varchar(10),GetDate() ,103), 'dd/mm/yyyy')
,(convert(varchar(10),GetDate(), 20), 'yyyy-mm-dd')
;
select t.*,
coalesce(convert(varchar(10), try_convert(date,StartDate,20),103), left(StartDate,10)) as [FormattedDate]
from #TestTable t;
But try_convert is only available since MS SQL Server 2012.
For MS SQL Server 2008 we can use a CASE WHEN with a LIKE to check the format.
declare #TestTable table (StartDate varchar(30), DateFormatUsed varchar(30));
insert into #TestTable (StartDate, DateFormatUsed) values
(convert(varchar(10),GetDate(), 103), 'dd/mm/yyyy')
,(convert(varchar(10),GetDate(), 20), 'yyyy-mm-dd')
,(convert(varchar(19),GetDate(), 20), 'yyyy-mm-dd hh:mi:ss')
;
select t.*,
(case
when StartDate like '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]%'
then convert(varchar(10), convert(date, left(StartDate, 10), 20), 103)
else left(StartDate, 10)
end) as [FormattedDate]
from #TestTable t;

Date convert not working with style 103

I have saved my date as a nvarchar(50) datatype in SQL Server. When I run this query:
select [Client_code], Date_of_receipt
from [T_Receving]
I am getting output like this:
but I want to filter my records by particular date, so I wrote a query like this
select
convert(date, [Date_of_receipt], 103) as 'Date_of_Receipt'
from
[T_Receving]
where
convert(date, [Date_of_receipt], 103) between '2015-03-06' and '2018-05-06'
but its showing an error
Conversion failed when converting date and/or time from character string
You have to convert to datetime and then convert back to varchar
declare #dtv varchar(20) = '2018-17-04'
declare #dtvdt datetime = convert(datetime, #dtv, 103)
select #dtvdt;
select convert(varchar(20), convert(datetime, #dtv, 103), 103), #dtv
where convert(datetime, #dtv, 103) between '2015-03-06' and '2018-05-06'
You clearly have some bad data. Use try_convert():
select try_convert(DATE, Date_of_receipt, 103) as Date_of_Receipt
from T_Receving
where try_convert(DATE, Date_of_receipt, 103) between '2015-03-06' and '2018-05-06' ;
In SQL Server 2008, you have to work harder to find the culprits. You can start with:
select date_of_receipt
from T_Receving
where date_of_receipt not like '[0-3][0-9]/[0-1][0-9]/[0-9][0-9][0-9][0-9]'
This will find most instances of bad formats. If it still persists, you will have to dig deeper to find bad day or month numbers.

Convert nvarchar to date and Get data between two date

I'm collecting data between two date 01/12/2014 and 31/12/2014 but my sql data type in nvarchar
is my query right?
SELECT * from customer where date >= convert(datetime, '01/12/2014', 105)
AND date <= convert(datetime, '31/12/2014', 105)
Result
Msg 242, Level 16, State 3, Line 1
The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.
can any one solve this problem...
as I know you must separate different parts of a DATE with "-" not with "/" in format 105. here is an example:
SELECT convert(datetime, '23-10-2016', 105) -- dd-mm-yyyy
so you must rewrite your code as:
SELECT * from customer where date >= convert(datetime, '01-12-2014', 105)
AND date <= convert(datetime, '31-12-2014', 105)
The format your string are in, 'dd/mm/yyyy' is 103, not 105 (which is 'dd-mm-yyyy'). So, simply use the correct format:
SELECT *
FROM customer
WHERE [date] >= CONVERT(datetime, '01/12/2014', 103)
AND [date] <= CONVERT(datetime, '31/12/2014', 103)
If your date type is nvarchar why don't you try like this:
SELECT * FROM customer
WHERE date >= '01/12/2014'
AND date <= '31/12/2014'
Do we really need to convert?
SELECT * FROM DBO.CUSTOMER
WHERE CAST([date] AS DATE) >= '01/12/2014' AND
CAST([date] AS DATE) <= '31/12/2014'
I suggest you to use this:
(I think converting to varchar is make more sense)
SELECT *
FROM customer
WHERE CONVERT(varchar, [date], 103) BETWEEN '01/12/2014' AND '31/12/2014'
In Date and Time Styles; 103 is for with British/French standard with century (yyyy) like this dd/mm/yyyy.

How to convert the system date format to dd/mm/yy in SQL Server 2008 R2?

I'm using SQL Server 2008 R2. I want to convert the system date to this format: dd/mm/yy
"2013-01-01 00:00:00.000" to "Score Calculation - 10/01/13".
My column contains the data:
1. DMS01A13010101
2. RMS01A13010201
3. 44
4. 2013-01-01 00:00:00.000
What I want: if the record has 2013-01-01 00:00:00.000 in this format then only I change to Score Caculation - dd/mm/yy
My code is,
select
case
when (CHARINDEX(D30.SPGD30_TRACKED_ADJUSTMENT_X, '-*') > 0 or
CHARINDEX(D30.SPGD30_TRACKED_ADJUSTMENT_X, '*-') > 0)
then 'Score Calculation - ' + CONVERT(VARCHAR(8), D30.SPGD30_TRACKED_ADJUSTMENT_X, 1)
end checkthedate
from
CSPGD30_TRACKING D30
SELECT CONVERT(varchar(11),getdate(),101) -- mm/dd/yyyy
SELECT CONVERT(varchar(11),getdate(),103) -- dd/mm/yyyy
Check this . I am assuming D30.SPGD30_TRACKED_ADJUSTMENT_X is of datetime datatype .
That is why i am using CAST() function to make it as an character expression because CHARINDEX() works on character expression.
Also I think there is no need of OR condition.
select case when CHARINDEX('-',cast(D30.SPGD30_TRACKED_ADJUSTMENT_X as varchar )) > 0
then 'Score Calculation - '+CONVERT(VARCHAR(11), D30.SPGD30_TRACKED_ADJUSTMENT_X, 103)
end
EDIT:
select case when CHARINDEX('-',D30.SPGD30_TRACKED_ADJUSTMENT_X) > 0
then 'Score Calculation - '+
CONVERT( VARCHAR(11), CAST(D30.SPGD30_TRACKED_ADJUSTMENT_X as DATETIME) , 103)
end
See this link for conversion to other date formats: https://www.w3schools.com/sql/func_sqlserver_convert.asp
The query below will result in dd/mm/yy format.
select LEFT(convert(varchar(10), #date, 103),6) + Right(Year(#date)+ 1,2)
SQLFiddle Demo
Try this
SELECT CONVERT(varchar(11),getdate(),101) -- Converts to 'mm/dd/yyyy'
SELECT CONVERT(varchar(11),getdate(),103) -- Converts to 'dd/mm/yyyy'
More info here: https://msdn.microsoft.com/en-us/library/ms187928.aspx
select convert(varchar(8), getdate(), 3)
simply use this for dd/mm/yy
and this
select convert(varchar(8), getdate(), 1)
for mm/dd/yy
The query below will result in dd-mmm-yy format.
select
cast(DAY(getdate()) as varchar)+'-'+left(DATEname(m,getdate()),3)+'-'+
Right(Year(getdate()),2)