I have run into this again and had to spend time compiling the answer, so I am posting it for future use.
I needed to convert a string to numeric in SQL. Seems pretty straightforward, right?
select convert(numeric(19,5),'0.0')
So what happens with my string looks like this?
select convert(numeric(19,5),'abc0.0')
Error converting data type varchar to numeric.
Ok, so I need to make sure it is a number first.
select case isnumeric('abc0.0') when 1 then convert(numeric(19,5),'abc0.0') else 0 end
All done, right? Not so fast. All of the following return 1 (true)
select isnumeric('$0.0')
select isnumeric('123,000.0')
But the following result in an error:
select convert(numeric(19,5),'$0.0')
select convert(numeric(19,5),'123,000.0')
So we need to make some basic decisions about what we consider to be valid in our numeric value and replace out those offending characters before evaluating it.
select case isnumeric(replace(replace(replace(replace('123,000.0',',',''),'$',''),'+',''),'-','')) when 1 then convert(numeric(19,5),replace(replace(replace(replace('123,000.0',',',''),'$',''),'+',''),'-','')) else 0 end
Did this help you? If so, please leave a comment!
David Jedziniak maintains this blog and posts helpful tips and tricks on SQL Server and Dynamics GP development. The opinions expressed here are those of the author and do not represent the views, express or implied, of any past or present employer. The information here is provided without warranty of fitness for any particular purpose.
Subscribe to:
Post Comments (Atom)
SQL 2022 TSQL snapshot backups!
SQL 2022 now actually supports snapshot backups! More specifically, T-SQL snapshot backups. Of course this is hardware-dependent. Here ...
-
If you are reading this, you are probably aware of the fact that you cannot deploy SSRS 2008 reports on an SSRS2005 server. SSRS reports ar...
-
SQL Job to refresh TEST from PRODUCTION Last Updated: 2018.11.12 I like to include each of these steps as a separate job step. If you ...
-
I ran into an issue today where I had a report parameter default that I couldn't seem to get rid of. In BIDS, I deleted the defaults f...
No comments:
Post a Comment