Conversion failed when converting the varchar value '12/31/' - sql-server

I have the following code:
declare #StartDate date
declare #EndDate date
set #StartDate='09/01/2016'
set #EndDate='11/30/2016'
SELECT
1 AS Segment,
'C' AS Subsegment,
100 AS Ent,
'KPAR' AS LOB,
'ATLB' AS Cov,
ClaimNumber AS [Claim#],
'12/31/'+AccidentYear AS AYDate,
convert(date, cast(AccountingPeriodDate as date),101) AS EvalDate
However I get an error
Conversion failed when converting the varchar value '12/31/' to data type int.
I haven't gotten this error before, and was wondering it it's due to a datatype change.

First, you should use ISO standard date formats, such as YYYYMMDD and YYYY-MM-DD.
Then, be explicit about the conversion and use try_convert(). So, I would write this as:
select try_convert(date, concat(accident_year, '1231'))
concat() will automatically convert the number to a date.
Or, alternatively, use datefromparts():
select datefromparts(accident_year, 12, 31)
This is probably the simplest solution.

Probably need to cast accidentyear as varchar
DECLARE #accidentyear AS INT
SET #accidentyear = 2016
SELECT '12/31/' + CAST(#accidentyear AS VARCHAR(4))

try this:
SELECT 1 AS Segment
,'C' AS Subsegment
,100 AS Ent
,'KPAR' AS LOB
,'ATLB' AS Cov
,ClaimNumber AS [Claim#]
,'12/31/'+ CAST(AccidentYear as nvarchar(4)) AS AYDate
,convert(date, cast(AccountingPeriodDate as date),101) AS EvalDate

The advice you got from other users to cast/convert accidentYear to varchar is correct. The reason this is necessary is because the data types are not the same. '12/31' is clearly a string. We also know that AccidentYear is an int because the error message says it's an int.
Since the data types are different, SQL Server attempts an implicit data type conversion. When SQL Server does this, the string is converted to an integer and then math is performed on it.
Since implicit conversion is not possible, you need to use explicit conversion instead. By using the cast or convert function, you are doing an explicit conversion.
The rules for implicit data type conversions can be found here: https://msdn.microsoft.com/en-us/library/ms190309.aspx?f=255&MSPPError=-2147217396

Related

MS SQL error : conversion of a varchar data type to a datetime data type resulted error

I am using MS SQL Server. One table column is defined as order_date varchar(25) and is stored in a format like 05/11/2015 07:54:16
In my select query, I am trying to convert that into a date format like (yyyy-mm-dd HH:MM:SS:000, e.g. 2015-05-11 08:03:10.000
I have tried with
select CONVERT(varchar(50), CAST(order_date AS datetime),121) from <table>
In my table I have around 500 records, but after fetching 10 records in my expected format, I get this error error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value
Is there any issue with my conversion?
There are a couple of problems here. The first is your data type choice, but I'll just repeat my comment for that: ""am trying to convert that into date format "* This is totally the wrong approach. Stop storing dates as a varchar use a date and time data type. The reason you have this error is because your poor data type choices. Fix that and get the presentation layer to work about the formatting."
Now, moving on. You have your expression below:
CONVERT(varchar(50), CAST(order_date AS datetime),121)
Firstly, as your value is a varchar, you need to tell SQL Server the format it is in; dd/MM/yyyy hh:mm:ss (I guess as '05/11' is ambigous)) is not unambiguous. What you have is the UK style, which is style 103:
CONVERT(datetime,'05/11/2015 07:54:16',103)
Now you can convert that to your ISO format:
CONVERT(varchar(23),CONVERT(datetime,'05/11/2015 07:54:16',103),121)
This returns the varchar value '2015-11-05 07:54:16.000'
I'd try to see what the value of order_date is at the time of the error. Perhaps what you assume to be a datetime string in mm/dd/yyyy... format is actually in dd/mm/yyyy....
I.e., the following outputs 2015-05-11 07:54:16.000 as my system is set to datetime format of mm/dd/yyyy.
declare #order_date varchar(100) = '05/11/2015 07:54:16'; -- mm/dd/yyyy...
print CONVERT(varchar(50), CAST(#order_date AS datetime),121);
the following throws an error: The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
set #order_date = '13/09/2015 07:54:16'; -- dd/mm/yyyy...
print CONVERT(varchar(50), CAST(#order_date AS datetime),121);

SQL Server convert ' dd/MM/YYYY H:mm:ss p.m..' to datetime

I am importing a text column into a SQL Server 2008 database.
I have a field 'carcassdate' in the following format
'11/05/2017 9:18:46 a.m.'
'10/05/2017 1:08:27 p.m.'
etc. How can I convert this into a proper SQL Server 2008 datetime (24 hour) column please?
I can't seem to find a proper solution for this.
My desired result is
'11/05/2017 9:18:46 a.m.' converted to 2017-05-11 09:18:46.000
'10/05/2017 1:08:27 p.m.' converted to 2017-05-10 13:08:27.000
Thanks in advance.
What I have tried so far:
strip the date part of the column
select convert(date, convert(varchar(10),carcass_date)) as carcassdate
That's the easy part..But I'm struggling with the time part.
Thanks for your help in advance.
The issue is with the periods in the string. By removing them, you can cast the string as a datetime. e.g.:
SELECT CAST(REPLACE(carcass_date, '.', '') AS DATETIME)
When it comes to date conversion, I suggest that you always be explicit.
Any kind of programming that is not explicit about date formats invites bugs.
I suggest you Never use cast as there is no explicit format. Even though it always assumes ISO format, I've never found any info about how it decides other formats (including your which is not ISO)
Never use convert without a format number.
I suggest you instead use convert with a format number. On my system, this returns two different dates. Cast returns the wrong one.
DECLARE #D AS VARCHAR(100) = '05/11/2017 9:18:46 a.m.'
SELECT CONVERT(DATETIME, REPLACE(#D, '.', ''), 103) as converted
SELECT CAST(REPLACE(#D, '.', '') AS DATETIME) as casted
Number 103 is defined as dd/mm/yyyy format. At least this way you have some degree of self documentation - that's the format you expect
Later versions of SQL have parse but it uses cultures, not format strings.
Perhaps read this
https://www.simple-talk.com/sql/t-sql-programming/how-to-get-sql-server-dates-and-times-horribly-wrong/
There's also a non-decisive discussion here:
datetime Cast or Convert?

data conversion from varchar to decimal

I have a column with varchar data type. I need to convert it into decimal data type in sql server 2014?
For example, varchar value .0462500 into decimal 4.62500
I have seen some similar questions in so, but it didn't work for me.
Thank you for your time and help!
If you know that your VARCHAR variables will require roughly the same conversion rate, you could simply use the CAST() function to convert them and then perform the necessary multiplication :
SELECT CAST(YourValue AS DECIMAL(7,5)) * 100
Likewise the CONVERT() method will essentially accomplish the same thing via a different syntax :
SELECT CONVERT(DECIMAL(7,5),YourValue) * 100
You can use Cast or Convert functions.
Convert:
select convert(decimal(10,5),.0462500)*100
Cast:
select cast(.0462500 as decimal(10,5))*100
Note: If there is malformed data(data which can not be converted), you may need to use Try_Convert or Try_Parse functions instead.
Try_Convert:
select try_convert(decimal(10,5),.0462500)*100
Try_Parse:
select try_parse('.0462500' as decimal(10,5))*100

TSQL Datediff from a string

I have a simple query that I am trying to use this select statement on.
I am trying to get the difference in seconds from the date provided (a UNIX timestamp).
select
DATEDIFF(s, '19700101', CAST(CAST('2014-08-27 08:59:56.0000000' AS DATETIME) AS INT))
When I try this, I get the following error :
Conversion failed when converting date and or time from character string.
I figured casting the string as datetime would have resolved that?
First of all, you should try to avoid using shorthands for the datepart, instead of s, use SECOND.
Another good practice when casting a string to a date is to use CONVERT so you can specify the format to use on the conversion (in your case, it would be 121. Finally, for the whole thing to work, you'll need to use less miliseconds (up to 3):
DECLARE #Date VARCHAR(50)
SET #Date = '2014-08-27 08:59:56.0000000'
SELECT DATEDIFF(SECOND,'19700101',CONVERT(DATETIME,LEFT(#Date,23),121))

Convert long decimal or float to varchar in SQL Server

One of the table I'm trying to query has a field with type decimal(38,19). I need to convert it to varchar in order for my perl DBI module to handle. How should I write the conversion in SQL to make it work? Specifically, if I run this in SQL Server Management Studio:
select convert(varchar, 19040220000.0000000000000000000)
I get:
Msg 8115, Level 16, State 5, Line 1
Arithmetic overflow error converting numeric to data type varchar.
I tried to round the number first:
select convert(varchar, round(19040220000.0000000000000000000, 0))
but that doesn't seem to work either (same error message). In fact round() doesn't seem to have an effect on that number for some reason. What should I do? Thx.
If you don't specify a length for your varchar, it defaults to 30 characters in the case of a CONVERT operation.
That's not long enough to hold your 38-digit decimal. So give your varchar an appropriate length in the CONVERT statement!!
Try this:
select convert(varchar(40), 19040220000.0000000000000000000)
You need to use a varchar with a set length larger than the precision you want, i.e.
select convert(varchar(64), 19040220000.0000000000000000000)

Resources