SQL Server 2012 and Later

Just use Try_Convert instead:

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.

Read more about Try_Convert.

SQL Server 2008 and Earlier

The traditional way of handling this is by guarding every expression with a case statement so that no matter when it is evaluated, it will not create an error, even if it logically seems that the CASE statement should not be needed. Something like this:

SELECT
   Account_Code =
      Convert(
         bigint, -- only gives up to 18 digits, so use decimal(20, 0) if you must
         CASE
         WHEN X.Account_Code LIKE '%[^0-9]%' THEN NULL
         ELSE X.Account_Code
         END
      ),
   A.Descr
FROM dbo.Account A
WHERE
   Convert(
      bigint,
      CASE
      WHEN X.Account_Code LIKE '%[^0-9]%' THEN NULL
      ELSE X.Account_Code
      END
   ) BETWEEN 503100 AND 503205

However, I like using strategies such as this with SQL Server 2005 and up:

SELECT
   Account_Code = Convert(bigint, X.Account_Code),
   A.Descr
FROM
   dbo.Account A
   OUTER APPLY (
      SELECT A.Account_Code WHERE A.Account_Code NOT LIKE '%[^0-9]%'
   ) X
WHERE
   Convert(bigint, X.Account_Code) BETWEEN 503100 AND 503205

What this does is strategically switch the Account_Code values to NULL inside of the X table when they are not numeric. I initially used CROSS APPLY but as Mikael Eriksson so aptly pointed out, this resulted in the same error because the query parser ran into the exact same problem of optimizing away my attempt to force the expression order (predicate pushdown defeated it). By switching to OUTER APPLY it changed the actual meaning of the operation so that X.Account_Code could contain NULL values within the outer query, thus requiring proper evaluation order.

You may be interested to read Erland Sommarskog's Microsoft Connect request about this evaluation order issue. He in fact calls it a bug.

There are additional issues here but I can't address them now.

P.S. I had a brainstorm today. An alternate to the "traditional way" that I suggested is a SELECT expression with an outer reference, which also works in SQL Server 2000. (I've noticed that since learning CROSS/OUTER APPLY I've improved my query capability with older SQL Server versions, too--as I am getting more versatile with the "outer reference" capabilities of SELECT, ON, and WHERE clauses!)

SELECT
   Account_Code =
      Convert(
         bigint,
         (SELECT A.AccountCode WHERE A.Account_Code NOT LIKE '%[^0-9]%')
      ),
   A.Descr
FROM dbo.Account A
WHERE
   Convert(
      bigint,
      (SELECT A.AccountCode WHERE A.Account_Code NOT LIKE '%[^0-9]%')
   ) BETWEEN 503100 AND 503205

It's a lot shorter than the CASE statement.

Answer from ErikE on Stack Overflow
Top answer
1 of 6
39

SQL Server 2012 and Later

Just use Try_Convert instead:

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.

Read more about Try_Convert.

SQL Server 2008 and Earlier

The traditional way of handling this is by guarding every expression with a case statement so that no matter when it is evaluated, it will not create an error, even if it logically seems that the CASE statement should not be needed. Something like this:

SELECT
   Account_Code =
      Convert(
         bigint, -- only gives up to 18 digits, so use decimal(20, 0) if you must
         CASE
         WHEN X.Account_Code LIKE '%[^0-9]%' THEN NULL
         ELSE X.Account_Code
         END
      ),
   A.Descr
FROM dbo.Account A
WHERE
   Convert(
      bigint,
      CASE
      WHEN X.Account_Code LIKE '%[^0-9]%' THEN NULL
      ELSE X.Account_Code
      END
   ) BETWEEN 503100 AND 503205

However, I like using strategies such as this with SQL Server 2005 and up:

SELECT
   Account_Code = Convert(bigint, X.Account_Code),
   A.Descr
FROM
   dbo.Account A
   OUTER APPLY (
      SELECT A.Account_Code WHERE A.Account_Code NOT LIKE '%[^0-9]%'
   ) X
WHERE
   Convert(bigint, X.Account_Code) BETWEEN 503100 AND 503205

What this does is strategically switch the Account_Code values to NULL inside of the X table when they are not numeric. I initially used CROSS APPLY but as Mikael Eriksson so aptly pointed out, this resulted in the same error because the query parser ran into the exact same problem of optimizing away my attempt to force the expression order (predicate pushdown defeated it). By switching to OUTER APPLY it changed the actual meaning of the operation so that X.Account_Code could contain NULL values within the outer query, thus requiring proper evaluation order.

You may be interested to read Erland Sommarskog's Microsoft Connect request about this evaluation order issue. He in fact calls it a bug.

There are additional issues here but I can't address them now.

P.S. I had a brainstorm today. An alternate to the "traditional way" that I suggested is a SELECT expression with an outer reference, which also works in SQL Server 2000. (I've noticed that since learning CROSS/OUTER APPLY I've improved my query capability with older SQL Server versions, too--as I am getting more versatile with the "outer reference" capabilities of SELECT, ON, and WHERE clauses!)

SELECT
   Account_Code =
      Convert(
         bigint,
         (SELECT A.AccountCode WHERE A.Account_Code NOT LIKE '%[^0-9]%')
      ),
   A.Descr
FROM dbo.Account A
WHERE
   Convert(
      bigint,
      (SELECT A.AccountCode WHERE A.Account_Code NOT LIKE '%[^0-9]%')
   ) BETWEEN 503100 AND 503205

It's a lot shorter than the CASE statement.

2 of 6
12

There's no guarantee that SQL Server won't attempt to perform the CONVERT to numeric(20,0) before it runs the filter in the WHERE clause.

And, even if it did, ISNUMERIC isn't adequate, since it recognises £ and 1d4 as being numeric, neither of which can be converted to numeric(20,0).(*)

Split it into two separate queries, the first of which filters the results and places them in a temp table or table variable, the second of which performs the conversion. (Subqueries and CTEs are inadequate to prevent the optimizer from attempting the conversion before the filter)

For your filter, probably use account_code not like '%[^0-9]%' instead of ISNUMERIC.


(*) ISNUMERIC answers the question that no-one (so far as I'm aware) has ever wanted to ask - "can this string be converted to any of the numeric datatypes - I don't care which?" - when obviously, what most people want to ask is "can this string be converted to x?" where x is a specific target datatype.

🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 228262 › cant-fix-error-converting-data-type-varchar-to-num
cant fix Error converting data type varchar to numeric. - Microsoft Q&A
January 12, 2021 - You probably get that error because sql server is trying to convert the column Phone (from VARCHAR) to a number, and in your existing table, some records contains some extra characters that fail the conversion.
Discussions

having this error while trying to populate a temptable, Error converting data type varchar to numeric. code below
The error message "Error converting data type varchar to numeric" indicates that there is an issue when trying to convert a value from a varchar (string) datatype to a numeric datatype (decimal(10,2)) in your query. The problem seems to be occurring in the conversion of the Assets column. The CASE statement in your query attempts to convert the Assets column to a decimal, but it seems there are non-numeric values in the Assets column of the Accounts_Financial table that cannot be converted. To handle this issue, you can use the TRY_CAST function to safely attempt the conversion, and if it fails, assign a default value. Here's how you can modify the CASE statement: TRY_CAST(AF.Assets AS decimal(10, 2)) AS Assets Here's the modified SELECT statement: SELECT DISTINCT AD.AcctDateID, AP.DateOfBirth, AP.first_name, AP.last_name, TRY_CAST(AF.Assets AS decimal(10, 2)) AS Assets, AP.SSN, AP.AddressLine1, AP.AddressLine12, AP.AddressCity, AP.AddressState, AP.gender, AP.OpenDate, AP.AddressZipCd, AD.PathCoreID, AP.email FROM Accounts_Profile AS AP INNER JOIN [dbo].[Accounts_Financial] AS AF ON AP.AcctNo = AF.AcctNo INNER JOIN [dbo].[Accounts_Date] AS AD ON AD.AcctNo = AP.AcctNo WHERE AP.channel = 'saving'; By using TRY_CAST, the query will attempt to convert the Assets column to a decimal, and if it's not possible (e.g., due to non-numeric values), it will return NULL. You can then handle NULL values as needed or assign a default value like you did with 0 in your original query. Try this query to achieve the result. More on reddit.com
🌐 r/SQL
4
4
July 26, 2023
Error converting data type varchar to numeric issue
I tried a lot of things to fix it, and no success. I have a field called MASTER_BOL_NUMBER . According to documentation it is CHAR. I see that inside it has only blanks and numbers When I try to CAST( MASTER_BOL_N… More on community.spiceworks.com
🌐 community.spiceworks.com
24
8
August 3, 2022
Error converting data type varchar to numeric issue – SQLServerCentral Forums
Error converting data type varchar to numeric issue Forum – Learn more on SQLServerCentral More on sqlservercentral.com
🌐 sqlservercentral.com
August 3, 2022
sql server - Error converting data type varchar to numeric when using CASE - Stack Overflow
SELECT ID, CASE WHEN ISNUMERIC(COL_VALUE) = 1 THEN CONVERT(NUMERIC, COL_VALUE) * 1000 ELSE COL_VALUE END AS [COL_VALUE] FROM Table The original data type is varchar that is why I convert COL_VAL... More on stackoverflow.com
🌐 stackoverflow.com
🌐
SQLServerCentral
sqlservercentral.com › forums › topic › issue-error-converting-data-type-varchar-to-numeric
Issue "Error converting data type varchar to numeric." – SQLServerCentral Forums
August 1, 2022 - -- WHERE CAST(wf.SMP_FLAG as char) = 'X' -- Error converting data type varchar to numeric. -- WHERE CAST(wf.SMP_FLAG AS numeric) = 'X' -- Error converting data type varchar to numeric. -- WHERE CONVERT(VARCHAR(50), wf.SMP_FLAG) = 'X' -- Error converting data type varchar to numeric.
🌐
Reddit
reddit.com › r/sql › having this error while trying to populate a temptable, error converting data type varchar to numeric. code below
r/SQL on Reddit: having this error while trying to populate a temptable, Error converting data type varchar to numeric. code below
July 26, 2023 -

drop table #Population

CREATE TABLE #Population

(

AcctNo varchar(25) NULL,

DateOfBirth varchar(50) NULL,

First\_Name varchar(50) NULL,

Last\_Name varchar(50) NULL,

Address1 varchar(50) NULL,

Address2 varchar(50) NULL,

AddressCity varchar(25) NULL,

AddressState varchar(5) NULL,

AddressZip varchar(50) NULL,

Listdate datetime NULL,

Campaign\_Name varchar(50) NULL,

Email\_Address varchar(100) NULL,

Pathcoreid varchar(25) NULL,

Scrub varchar (500) default 'Available',

Detail1 varchar(30) NULL,

Detail2 varchar(30) NULL,

Detail3 varchar(30) NULL,

Detail4 varchar(30) NULL,

Channel varchar(50) NULL,

Opendate varchar(50) NULL,

SSN varchar(50) NULL,

Gender varchar(50) NULL,

Assets decimal(10,2) 

)

INSERT INTO #Population

(

AcctNo,

DateOfBirth,

First_Name,

Last_Name,

Address1,

Address2,

AddressCity,

AddressState,

AddressZip,

Email_Address,

Pathcoreid,

Opendate,

SSN,

Gender,

Assets

)

SELECT DISTINCT

AD.AcctDateID,

AP.DateOfBirth,

AP.first_name,

AP.last_name,

CASE

WHEN ISNUMERIC(AF.Assets) = 1 THEN CONVERT(decimal(10,2), AF.Assets)

ELSE 0 -- Handle non-numeric values with a default

END AS Assets,

AP.SSN,

AP.AddressLine1,

AP.AddressLine12,

AP.AddressCity,

AP.AddressState,

AP.gender,

AP.OpenDate,

AP.AddressZipCd,

AD.PathCoreID,

AP.email

FROM

Accounts_Profile AS AP

INNER JOIN

[dbo].[Accounts_Financial] AS AF ON AP.AcctNo = AF.AcctNo

INNER JOIN

[dbo].[Accounts_Date] AS AD ON AD.AcctNo = AP.AcctNo

WHERE

AP.channel = 'saving';

Top answer
1 of 4
2
The error message "Error converting data type varchar to numeric" indicates that there is an issue when trying to convert a value from a varchar (string) datatype to a numeric datatype (decimal(10,2)) in your query. The problem seems to be occurring in the conversion of the Assets column. The CASE statement in your query attempts to convert the Assets column to a decimal, but it seems there are non-numeric values in the Assets column of the Accounts_Financial table that cannot be converted. To handle this issue, you can use the TRY_CAST function to safely attempt the conversion, and if it fails, assign a default value. Here's how you can modify the CASE statement: TRY_CAST(AF.Assets AS decimal(10, 2)) AS Assets Here's the modified SELECT statement: SELECT DISTINCT AD.AcctDateID, AP.DateOfBirth, AP.first_name, AP.last_name, TRY_CAST(AF.Assets AS decimal(10, 2)) AS Assets, AP.SSN, AP.AddressLine1, AP.AddressLine12, AP.AddressCity, AP.AddressState, AP.gender, AP.OpenDate, AP.AddressZipCd, AD.PathCoreID, AP.email FROM Accounts_Profile AS AP INNER JOIN [dbo].[Accounts_Financial] AS AF ON AP.AcctNo = AF.AcctNo INNER JOIN [dbo].[Accounts_Date] AS AD ON AD.AcctNo = AP.AcctNo WHERE AP.channel = 'saving'; By using TRY_CAST, the query will attempt to convert the Assets column to a decimal, and if it's not possible (e.g., due to non-numeric values), it will return NULL. You can then handle NULL values as needed or assign a default value like you did with 0 in your original query. Try this query to achieve the result.
2 of 4
2
Column order doesn't match. In the insert section you have the assets column last, but in the select its in the middle
Find elsewhere
🌐
SQLServerCentral
sqlservercentral.com › forums › topic › error-converting-data-type-varchar-to-numeric-issue-2
Error converting data type varchar to numeric issue – SQLServerCentral Forums
August 3, 2022 - If the following code gives you a varchar/numeric conversion error, there is no doubt at all that the datatypes of the columns involved in the joins do not match. 100%. SELECT MASTER_BOL_NUMBER FROM WF_AR_LD ar LEFT OUTER JOIN WF_LODM wf ON ...
🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 635551 › error-converting-data-type-varchar-to-numeric
Error converting data type varchar to numeric - Microsoft Q&A
I highly recommend to use DECIAL instead of NUMERIC in your code. ... This is the most important point here! Do not store decimal data as text! Text usually cost more place than decimal. check example below · Working with the data (math, compare, sort...) cost less since there is no need to CONVERT · Avoid such issue related to wrong format of the data. ... declare @D decimal(18,2),@T VARCHAR(18) SELECT @D = 1, @T = '1' SELECT DATALENGTH(@D),DATALENGTH(@T) -- 5:1 SELECT @D = 1.01, @T = '1.01' SELECT @D, DATALENGTH(@D),DATALENGTH(@T) -- 5:4 SELECT @D = 11.01, @T = '11.01' SELECT @D, DATALENGTH(@D),DATALENGTH(@T) -- 5:5 SELECT @D = 111.01, @T = '111.01' SELECT @D, DATALENGTH(@D),DATALENGTH(@T) -- 5:6 SELECT @D = 1234567891234567.01, @T = '1234567891234567.01' SELECT @D, DATALENGTH(@D),DATALENGTH(@T) -- 9:18
🌐
Reddit
reddit.com › r/sql › [ms sql] getting "error converting data type varchar to numeric"
r/SQL on Reddit: [MS SQL] Getting "Error converting data type varchar to numeric"
January 24, 2017 -

I'm working on a query that needs to return a blank field if it's equal to zero, otherwise it needs to return a decimal. However I can't get it to run

SELECT

case when a.field1 <>0 then cast(a.field1 as DECIMAL (9,2)) else '' end as Weight1

FROM

a

any help would be appreciated. I don't know some SQL basics, and I figured this out at one point, but I forgot how I did it.

🌐
GitHub
github.com › r-dbi › odbc › issues › 257
Error converting data type varchar to numeric when writing more than 1024 numeric digits rows to SQL SERVER · Issue #257 · r-dbi/odbc
February 21, 2019 - dbWriteTable(con, "temp_table_001", value = test_tb[1:1024, ], append = TRUE, field.types = c(x = "decimal(18,4)")) dbWriteTable(con, "temp_table_001", value = test_tb[1:1025, ], append = TRUE, field.types = c(x = "decimal(18,4)")) #> Error in result_insert_dataframe(rs@ptr, values): nanodbc/nanodbc.cpp:1587: 42000: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Error converting data type varchar to numeric.
Author   shizidushu
🌐
MSSQLTips
mssqltips.com › home › handling error converting data type varchar to numeric in sql server
Handling error converting data type varchar to numeric in SQL Server
September 3, 2015 - They appear as numerical characters, yet don’t convert. If we copy the values directly and do a direct SELECT CAST(‘1.00000’ AS DECIMAL(22,8)), they convert without error. If they come with extra spaces, no trimming function works to remove the error. We seldom stumble on these types of data, but they can create encumbrances for developers, so it’s good to know a work-around when transforming these VARCHARs into numerical data points.
🌐
SQLTeam
forums.sqlteam.com › other sql server topics
Error converting data type varchar to numeric - Other SQL Server Topics - SQLTeam.com Forums
February 8, 2017 - There are two parts to the monitor. One displays the number of exceptions (count) and the other part displays the exception bank loan id's. The count is working fine, but for the display portion of the query I'm getting an "Error converting data type varchar to numer...
🌐
SQLServerCentral
sqlservercentral.com › forums › topic › error-converting-data-type-varchar-to-numeric-16
Error converting data type varchar to numeric – SQLServerCentral Forums
September 22, 2007 - A varchar value is not explicitly convertible to a numerical value. Instead of using the Str() function, another option is to use: ISNULL(CONVERT(decimal(15,2),pre.C_CLAIMTOT), 0) My blog: SQL Soldier[/url] SQL Server Best Practices: SQL Server Best Practices Twitter: @SQLSoldier My book: Pro ...
🌐
Jenstirrup
jenstirrup.com › home › articles › error converting data type varchar to numeric where isnumeric finds only numbers
Error converting data type varchar to numeric where ISNUMERIC finds only numbers - Jennifer Stirrup: AI Strategy, Data Consulting & BI Expert | Keynote Speaker
November 6, 2019 - However, on this occasion, using ISNUMERIC failed to identify any columns as being non-numeric. ISNUMERIC returned all of the rows as TRUE, and that confused me. I knew that something was triggering the CONVERT instruction to go wrong.
Top answer
1 of 15
10

Hello,

I am not sure why but I have a difficult time selecting fields that have a value ‘X’ in one of the fields.

I have a field wf.SMP_FLAG where I should have only two values ’ ’ (blank) and ‘X’ (letter X). I am not sure what kind of data type it is in the system, but I am constantly getting an error “Error converting data type varchar to numeric.”

This field is defined in CTE when in one of the tables I type ‘X’ AS ‘SMP_FLAG’ and in the next CTE I am selecting all the fields that are of ‘X’ type. I am getting an error:

Error converting data type varchar to numeric.

When I am selecting WHERE wf.SMP_FLAG = ‘X’ (in the next SELECT statement)

I am getting an error " Error converting data type varchar to numeric. "

I tried to change it to such queries

WHERE wf.SMP_FLAG = 'X’ – Error converting data type varchar to numeric.
WHERE CAST(wf.SMP_FLAG as char) = ‘X’ – Error converting data type varchar to numeric.
WHERE CAST(wf.SMP_FLAG AS numeric) = ‘X’ – Error converting data type varchar to numeric.
WHERE CONVERT(VARCHAR(50), wf.SMP_FLAG) = ‘X’ – Error converting data type varchar to numeric.

When I

TRY_CAST(wf.SMP_FLAG as float) = ‘X’ I am not getting errors but everything is blank as if there were no ‘X’ (but they were in the previous CTE).

Still no luck. Maybe someone may have an idea.

2 of 15
0

You’ll want to use a case statement I think.

WHERE (CASE WHEN  wf.SMP_FLAG = '' THEN 0
      WHEN  wf.SMP_FLAG = 'X' THEN 1
      ELSE 0
    END) = 1

🌐
YouTube
youtube.com › watch
How to Fix Arithmetic Overflow Error Converting Varchar to Data Type Numeric in VBA SQL Updates - YouTube
A step-by-step guide to resolving the common `Arithmetic Overflow Error` in SQL updates executed through VBA, along with best practices for data type handlin...
Published   May 27, 2025
Views   1