Date convert not working with style 103 - sql

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.

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;

T-SQL only throws error message when converting two varchars to dates

I'm trying to filter a query to select values that are between a given date range. My original predicate was:
WHERE [TheDate] BETWEEN '2016-07-01' AND '2017-06-31'
When I did this, I got the error message, "The conversion of a varchar data type to a datetime data type resulted in an out-of-range value." I then tried multiple variants of the statement:
WHERE [TheDate] BETWEEN CONVERT(datetime, '2016-7-1 00:00:00.000', 103)
AND CONVERT(datetime, '2017-6-31 00:00:00.000', 103)
WHERE [TheDate] BETWEEN CONVERT(date, '2016-7-1', 103)
AND CONVERT(date, '2017-6-31', 103)
WHERE [TheDate] BETWEEN CONVERT(date, '2016-7-1', 101)
AND CONVERT(date, '2017-6-31', 101)
WHERE [TheDate] BETWEEN CAST('2016-7-1' AS date)
AND CAST('2017-6-31' AS date)
But every one gave me the same error message.
Then, just for the heck of it, I tried this:
WHERE [TheDate] > CAST('2016-7-1' AS date)
And Presto - it worked. So then I tried this:
WHERE [TheDate] > CAST('2016-7-1' AS date)
AND [TheDate] < CAST('2017-6-31' AS date)
And got the error message again. I continued to try multiple variants, but the upshot is this:
If I use CAST or CONVERT on two varchar columns to convert them to date or datetime, I get the error message, regardless of my syntax, function selection, etc.
If I use CAST or CONVERT on one varchar column to convert it to a date or datetime, the conversion works without a problem
Does anyone have any ideas what could be causing this?
Thanks.
As it has been mentioned, june 31 is not a valid date.
Here you can see how to find last date of current month
https://blog.sqlauthority.com/2007/08/18/sql-server-find-last-day-of-any-month-current-previous-next/
----Last Day of Previous Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))
LastDay_PreviousMonth
----Last Day of Current Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0))
LastDay_CurrentMonth
----Last Day of Next Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+2,0))
LastDay_NextMonth
just replancing getdate() with your date will give you last day, in your case
declare #iniDate date
declare #endDate date
set #iniDate='2016-07-01'
set #endDate= DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,#iniDate)+1,0))
WHERE [TheDate] BETWEEN #iniDate AND #endDate

How to display particular range values in varchar column in SQL SERVER 2000

My table Name is 'information'
Structure is:
No int,
Name varchar(200),
Date varchar(30)
Records:
No Name Date
=====================================
1 A 25/08/2012
2 B 10/08/2012
3 C 11/08/2012
4 D 01/09/2012
My Problem is i want the No,Name,Date for between 25/08/2012 to 01/09/2012
i was tried the follwing query, but i am unable to get it.
select No,Name,Date
from information
where Date>='25/08/2012' and Date<='01/09/2012'
I don't want to alter the date column(varchar) to datetime
Please help me
Please use the below query you do not need to alter your Date column(varchar) to datetime.
select No,Name,Date from information where CONVERT(date,[DATE],103) >= CONVERT(date,'25/08/2012',103) and CONVERT(date,[DATE],103) <= CONVERT(date,'01/09/2012',103)
As said before, convert your column to a datetime. I'd personally use a between statement as its cleaner.
select No,Name,Date from information where convert(datetime, Date, 103) between convert(datetime, '25/08/2012', 103) and convert(datetime, '01/09/2012', 103)
depending on your input parameters you might be able to convert them into datetime beforehand (so you can check the values entered before they are executed. Example;
declare #startdate datetime
declare #enddate datetime
set #startdate = convert(datetime, '25/08/2012', 103)
set #enddate = convert(datetime, '01/09/2012', 103)
select No,Name,Date from information where convert(datetime, Date, 103) between #stardate and #enddate
You can try to convert varchar to datetime:
SELECT No,Name,Date from information
WHERE CONVERT(datetime, Date, 103) >= CONVERT(datetime, '25/08/2012', 103)
AND CONVERT(datetime, Date, 103) <= CONVERT(datetime, '01/09/2012', 103)
You need to convert VARCHAR datatype to Date. Try,
SELECT No, Name, [Date]
FROM information
where CAST([Date] AS Date) BETWEEN CAST('2012-08-25' AS DATE) AND
CAST('2012-09-09' AS DATE)

SQL VarChar to Date

hi
i am trying to convert a VarChar date field (e.g. 20100320) to a real date field like
'dd/mm/yyyy' (e.g. 20/03/2010).
I have tried two ways:
a)
(SELECT MIN(CAST(A.DateOfAction AS Date)) AS Expr1
FROM ResAdm.Action A
WHERE (A.PersonID = P.PersonID))
AS 'Period From',
b)
(SELECT MIN(CONVERT(DATE, A.DateOfAction, 103)) AS Expr1
FROM ResAdm.Action A
WHERE (A.PersonID = P.PersonID))
AS 'Period From',
both producing the result like
yyyy-mm-dd (e.g. 2010-03-20)
but i want the result like
dd/mm/yyyy (e.g. 20/03/2010)
any help will be appreciated.
thanks.
Try this:
select convert(varchar(8), convert(datetime, min(a.DateOfAction), 112), 103)
Your problem is that once you have a date format, SQL Server will dump it out in its default date format, which you've discovered is yyyy-mm-dd. You need to convert from date to varchar to get the format you want. But to convert from date, you need to first convert to date! 112 is the format for yyyymmdd, and 103 is the format for dd/mm/yyyy, so this is why you need these formats. (Books Online reference for date formats)
Declare #date nvarchar(100)
set #date = '20100320'
select convert(varchar, CONVERT(datetime, #date, 109), 103)
You can use
convert(varchar, CONVERT(datetime, A.DateOfAction, 109), 103)