Showing this error "Conversion failed when converting date and/or time from character string." in SQL - sql

My sp is
EXEC _REPORTS #StartDate=N'17-Sep-2016',
#EndDate=N'17-Sep-2016',
#CustomerID=0,
#ProductID=0,
#BranchID=0,
#NumberOfRecords=100,
#PageNo=1,
#IsBuy=1
here the region of date used in where
AND FCSB.FCBuySellDate
BETWEEN CONVERT(datetime,#StartDate,105) AND CONVERT(datetime,#EndDate,105)

The reason is primarily you are getting some wrong formatted data to convert, For example
declare #StartDate nvarchar(15) = N'17-Septt-2016'
select CONVERT(datetime,#StartDate,105)
You will get this error
Conversion failed when converting date and/or time from character string.
If you get correct date you get it converted, one way to ignore this error is to do TRY_CONVERT which willl return NULL. Best way to solve this problem is to identify why it is getting wrong date as parameter and fix that.
select TRY_CONVERT(datetime,#StartDate,105)

check for null value in FCSB.FCBuySellDate. It might be cause of an error
try this
AND FCSB.FCBuySellDate BETWEEN CONVERT(datetime,#StartDate,105) AND CONVERT(datetime,#EndDate,105)
AND isnull(FCSB.FCBuySellDate,'') <> ''
Also try this, convert column in datetime
AND CONVERT(datetime,FCSB.FCBuySellDate) BETWEEN CONVERT(datetime,#StartDate,105) AND CONVERT(datetime,#EndDate,105)

Related

SQL Error : Conversion failed when converting date and/or time from character string

I'm trying to convert a varchar column to date or datetime but I don't understand why it's not possible it should work and I don't see any kind of error.
The column values is 31-07-2017 and the type is Varchar(250). I tried convert and cast and I get the same error:
Conversion failed when converting date and/or time from character string.
Does anyone have any idea on why it's like this?
The conversion error is because your session setting is other than DATEFORMAT dmy or varchar values do not conform to DMY format.
For the latter case, run the query below to identify problem values:
SELECT YourDateColumn AS InvalidDate
FROM dbo.YourTable
WHERE
YourDateColumn IS NOT NULL
AND TRY_CONVERT(date, YourDateColumn, 103) IS NULL;
As #TimBiegeleisen mentioned in a comment, it is best to choose the most appropriate column type (date in this case) for the data to be stored. Not only will this avoid errors like this, it will improve performance and better ensure data integrity.
I found the issue, it's a very very stupid mistake, there was one column with a text format I couldn't see it because I checked with length, but the SQL gives max length so I used group by and manually check dates until I found one column that's not correct in 1 m account records

Converting date and/or time from character string

Can someone please tell me what 's wrong with this code that I get error:
Conversion failed when converting date and/or time from character string.
, iif(t1.medbuildcmpltdt IS NOT NULL,cast(datediff(day, t1.medbuildcmpltdt,t1.orderingtoolbuildcmpltdt)AS nvarchar(255)), cast(t1.orderingtoolbuildcmpltdt AS nvarchar(255)) AS 'Main_Days Build'
Conversion failed when converting date and/or time from character string.
The problem is where SQL Server wants a date or datetime and is receiving a string. The only thing in the code you provided that requires a date or datetime is
datediff(
day,
t1.medbuildcmpltdt,
t1.orderingtoolbuildcmpltdt
)
So, t1.medbuildcmpltdt or t1.orderingtoolbuildcmpltdt is a string ([n][var]char) and contains values that cannot be interpreted as valid date or datetime values.

Finding row causing error in type conversion in SQL Server

I am trying to cast a column as smalldatetime from varchar. There are some rows containing errors, how can I find them?
SELECT
PA.EAR_TAG
,ISNULL(B.DISPOSAL_DATE, H.DISPOSAL_DATE) as HB_Date
,Y.[DATE OF MOVEMENT] as Y_Date
,DATEDIFF(DAY, ISNULL(B.DISPOSAL_DATE, H.DISPOSAL_DATE), cast(Y.[DATE OF MOVEMENT] as smalldatetime))
FROM
DairyTelomere.dbo.PROJECT_ANIMALS AS PA
LEFT JOIN
Langhill.dbo.YOUNG_STOCK_BULL AS B ON Pa.EAR_TAG = B.EAR_TAG
LEFT JOIN
Langhill.dbo.YOUNG_STOCK_HEIFER AS H ON PA.EAR_TAG = H.EAR_TAG
LEFT JOIN
DairyTelomere.dbo.Young_Stock_culls AS Y ON PA.EAR_TAG = Y.Ear_Tag
The error I get is:
Msg 242, Level 16, State 3, Line 1
The conversion of a varchar data type to a smalldatetime data type resulted in an out-of-range value.
I know that if the column was in a date format I could check it by using ISDATE() but unfortunately I can't change the column type (don't have permissions).
Any ideas will be greatly appreciated.
you can use the isdate to get a list of all the ones that are not converting for you. You dont need to change the column type to use this so i am confused by your statement
if the column was in a date format I could check it by using ISDATE() but unfortunately I can't change the column type (don't have permissions)
Will help more if you can clarify but this query should get you a list of rows that have bad date values.
select table.date_as_varchar
from table
where isdate(table.date_as_varchar) = 0
adding to #workabyte answer you can also try using TRY_PARSE, TRY_CAST OR TRY_CONVERT, all of them return NULL if the conversion failed, that way you can know wich rows caused the error.
TRY_PARSE
as the documentation says:
Use TRY_PARSE only for converting from string to date/time and number
types. For general type conversions, continue to use CAST or CONVERT.
Keep in mind that there is a certain performance overhead in parsing
the string value.
Usage example:
SELECT TRY_PARSE(your_date AS DATETIME USING 'es-ES') as date
FROM your_table
es-ES is a culture parameter,different culture paramaters yield different results in your conversions, you can find the full list of parameters in the documentation
TRY_CONVERT
as the documentation says:
TRY_CONVERT takes the value passed to it and tries to convert it to
the specified data_type. If the cast succeeds, TRY_CONVERT returns the
value as the specified data_type; if an error occurs, null is
returned. However if you request a conversion that is explicitly not
permitted, then TRY_CONVERT fails with an error.
Usage example:
SELECT TRY_CONVERT(DATETIME,your_date,103) as date
FROM your_table
The 103 being the style/format of the date you are converting, here you can find a list of the formats avaliable
TRY_CAST
as the documentation says:
TRY_CAST takes the value passed to it and tries to convert it to the
specified data_type. If the cast succeeds, TRY_CAST returns the value
as the specified data_type; if an error occurs, null is returned.
However if you request a conversion that is explicitly not permitted,
then TRY_CAST fails with an error.
Usage example:
SELECT TRY_CAST(your_date AS DATETIME) as date
FROM your_table

TSQL derived column with date convert that checks for non-date convertible strings

I have a date column with dates stored as strings, such as 20120817. Unfortunately, the text form field that populates this column is free text, so I cannot guarantee that an occasional "E" or "whatever" shows up in this column. And more than a few already have.
What I need to do is convert the string column into a date column. Of course the convert will reject the random string characters. Is there any way to create a derived column that will not only convert the strings but exclude the non-date convertible strings?
If there were no non-date convertible strings in the table, the following would work:
ADD [convertedDate] AS CONVERT(DATE, [stringDate], 102)
And it does work perfectly in a test table I created. But when I introduce other non-convertible strings, I receive the dreaded "Conversion failed when converting date and/or time from character string" error for obvious reasons.
Is there a function that will catch non-convertible elements that I can add on to this derived column code? Or is a view or function the only - or best - way to handle this? I played around with IsDate() with little luck.
Thank you!
There's a function called ISDATE(date), maybe you can use it in a CASE statement or in the WHERE part of the query... It depends on how you're doing it, maybe something like this
ADD [convertedDate] AS CASE WHEN ISDATE([stringDate]) = 1 THEN CONVERT(DATE,[stringDate], 102) ELSE NULL END
If you're using SQL Server 2012 you can make use of the try_convert function
http://msdn.microsoft.com/en-us/library/hh230993.aspx
It will work normally if the conversion succeeds but return null if the conversion fails
ADD [convertedDate] AS TRY_CONVERT(DATE, [stringDate], 102)
This should give you some ideas...
DECLARE #date1 varchar(50)
DECLARE #date2 varchar(50)
SET #date1 = '20120101'
SET #date2 = 'e20120101'
SELECT
ISDATE(#date1),
ISDATE(#date2),
CASE WHEN ISDATE(#date1) = 1 THEN CONVERT(SMALLDATETIME,#date1) END,
CASE WHEN ISDATE(#date2) = 1 THEN CONVERT(SMALLDATETIME,#date2) END

Converting SQL Server null date/time fields

Whenever the value is null for this query
SELECT ISNULL(someDateTime,'')
FROM someTable
the result is
someDateTime
------------
1900-01-01 00:00:00.000
I want it to be "No", so if I run this:
SELECT ISNULL(someDateTime,'No')
FROM someTable
then there's this error:
Conversion failed when converting datetime from character string.
How to do it? Thanks in advance!
The result of the expression will need to be a single type. If you want a character string (and you do, since 'No' is not a DateTime), you'll need to convert the datetime to such a string:
SELECT ISNULL(cast(someDatetime as varchar(20)), 'No') FROM someTable
As others have suggested, though, code like this smells bad, and you may want to pass the null to a client component and do the conversion there.
isnull() is trying to convert the second argument to the datatype of the field you specify in the first argument.
If you are going to be returning a string you need to cast the DateTime field to a string type so that isnull() can work properly - see Michael Petrotta's answer for a way to accomplish this.
You're still selecting a DateTime column, and so the result of that expression still needs to be a DateTime value rather than a string. To suggest an appropriate work-around, we'll need to know more about what you're really trying to do with this data.
You can't as such directly. It's easier to trap NULL in the client and change it to "no" there.
However, you could use a token value such as "17530101" which is a valid datetime, or CONVERT SomeDateTime first to varchar.
Otherwise, we need more info on why etc
In your Update Stored Proc: Update your previous date value to a new Null value:
.Parameters.AddWithValue("#Date_Value", Nothing).IsNullable = True