Hello,

Running out of ideas how to fix this case. I am getting an error: Error converting data type varchar to numeric.

CASE
WHEN sopHdr.SOPTYPE = 4
THEN CONVERT(int,(sopHdr.DOCAMNT - inv.TaxTotal) - CONVERT(int, inv.CostTotal)) * - 1 * CONVERT(int,proj.UserText1) / 100.0
ELSE CONVERT(int,(sopHdr.DOCAMNT - inv.TaxTotal) - inv.CostTotal) * CONVERT(int,proj.UserText1) / 100.0
END

Please help.

Answer from dimablys on community.spiceworks.com
Discussions

.net - "Error converting data type nvarchar to int" when executing Stored Procedure and reading return value - Stack Overflow
I have a clr stored procedure which has an output value I am calling the sp from a vb.net app with the code below. I am getting an error that says 'Error converting data type nvarchar to int. 1125... More on stackoverflow.com
🌐 stackoverflow.com
SQL Server : error converting data type varchar to numeric - Stack Overflow
Returns a value cast to the specified data type if the cast succeeds; otherwise, returns null. ... I think the problem is not in sub-query but in WHERE clause of outer query. When you use ... SQL server will try to convert every value in your Account_code field to integer to test it in provided condition. Obviously it will fail to do so if there will be non-integer characters in some rows. ... If you are using varchar ... More on stackoverflow.com
🌐 stackoverflow.com
sql - Conversion failed when converting the varchar value 'simple, ' to data type int - Stack Overflow
BUT a.value is ntext so I need to CONVERT it what I actually did, but I am getting an error: Conversion failed when converting the varchar value 'simple, ' to data type int. More on stackoverflow.com
🌐 stackoverflow.com
UPDATE - SQL Server : error converting data type varchar to int - Stack Overflow
SQL Server is causing an error: Error converting data type varchar to int This is the code where I explicitly convert ID to int and I'm not getting error: SELECT DISTINCT CONVERT(int, f.ID) AS More on stackoverflow.com
🌐 stackoverflow.com
🌐
Stack Overflow
stackoverflow.com › questions › 50530270 › error-converting-data-type-nvarchar-to-int-when-executing-stored-procedure-and › 50532349
.net - "Error converting data type nvarchar to int" when executing Stored Procedure and reading return value - Stack Overflow
The problem is that SqlDbType.NVarChar is an enum yet is being used incorrectly here as the "value" to imply the datatype from. The datatype is, by default, int. This is why you are getting an error converting the stored procedure's Result parameter into the int that was declared for the SqlCommand parameter via the line shown above.
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.

🌐
CodeProject
codeproject.com › Questions › 1172426 › Error-converting-data-type-varchar-to-int
https://www.codeproject.com/Questions/1172426/Erro...
Do not try and find the page. That’s impossible. Instead only try to realise the truth - For those who code; Updated: 1 Jul 2007
Find elsewhere
🌐
Janzednicek
janzednicek.cz › home › sql error – conversion failed when converting the varchar value to data type int
SQL Error - Conversion failed when converting the varchar value to data type int | Jan Zedníček
October 30, 2025 - The error message “Conversion failed when converting the varchar value to data type int” occurs in SQL Server client (for example Management Studio) when attempting to convert a value stored as the varchar (text) data type to an integer data type.
🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 1412981 › conversion-failed-when-converting-the-varchar-valu
Conversion failed when converting the varchar value 'N/A' to data type int. - Microsoft Q&A
November 2, 2023 - @Christoph Muthmann correctly explained that SQL Server will attempt to convert the "N/A" value to int due to data type precedence rules, which results in an error because "N/A" is not a valid integer. Converting a NULL value to "N/A" is arguably a job best done in the application data presentation layer rather than T-SQL. That being said, you avoid the conversion error by explicitly casting the int value to varchar(11) so that both values are strings:
🌐
SQLServerCentral
sqlservercentral.com › forums › topic › conversion-failed-when-converting-the-varchar-value-to-data-type-int-6
Conversion failed when converting the varchar value to data type int. – SQLServerCentral Forums
October 21, 2021 - My guess is that it is how SQL is parsing it. VARCHAR/INT will try to convert the VARCHAR to an INT and 10.1 cannot be converted to INT. An alternate approach to CASTing would be to change the INT (12) to a DECIMAL (12.0 for example). Then the VARCHAR will be implicitly CAST to the same datatype.
Top answer
1 of 8
4

OK. I finally created a view that works:

SELECT TOP (100) PERCENT id, CAST(CASE WHEN IsNumeric(MyCol) = 1 THEN MyCol ELSE NULL END AS bigint) AS MyCol
FROM         dbo.MyTable
WHERE     (MyCol NOT LIKE '%[^0-9]%')

Thanks to AdaTheDev and CodeByMoonlight. I used your two answers to get to this. (Thanks to the other repliers too of course)

Now when I do joins with other bigint cols or do something like 'SELECT * FROM MyView where mycol=1' it returns the correct result with no errors. My guess is that the CAST in the query itself causes the query optimizer to not look at the original table as Christian Hayter said may be going on with the other views

2 of 8
2

Ideally, you want to try to avoid storing the data in this form - would be worth splitting the BIGINT data out in to a separate column for both performance and ease of querying.

However, you can do a JOIN like this example. Note, I'm not using ISNUMERIC() to determine if it's a valid BIGINT because that would validate incorrect values which would cause a conversion error (e.g. decimal numbers).

DECLARE @MyTable TABLE (MyCol VARCHAR(20))
DECLARE @OtherTable TABLE (Id BIGINT)

INSERT @MyTable VALUES ('1')
INSERT @MyTable VALUES ('Text')
INSERT @MyTable VALUES ('1 and some text')
INSERT @MyTable VALUES ('1.34')
INSERT @MyTable VALUES ('2')
INSERT @OtherTable VALUES (1)
INSERT @OtherTable VALUES (2)
INSERT @OtherTable VALUES (3)

SELECT *
FROM @MyTable m
    JOIN @OtherTable o ON CAST(m.MyCol AS BIGINT) = o.Id
WHERE m.MyCol NOT LIKE '%[^0-9]%'

Update: The only way I can find to get it to work for having a WHERE clause for a specific integer value without doing another CAST() on the supposedly bigint column in the where clause too, is to use a user defined function:

CREATE  FUNCTION [dbo].[fnBigIntRecordsOnly]()
RETURNS @Results TABLE (BigIntCol BIGINT)
AS
BEGIN
INSERT @Results
SELECT CAST(MyCol AS BIGINT)
FROM MyTable
WHERE MyCol NOT LIKE '%[^0-9]%'
RETURN
END

SELECT * FROM [dbo].[fnBigIntRecordsOnly]() WHERE BigIntCol = 1

I don't really think this is a great idea performance wise, but it's a solution

🌐
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
September 27, 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
🌐
GitHub
github.com › sqlalchemy › sqlalchemy › discussions › 11543
Error converting data type nvarchar to int · sqlalchemy/sqlalchemy · Discussion #11543
June 28, 2024 - ProgrammingError at /helpdesk/submit (pyodbc.ProgrammingError) ('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Error converting data type nvarchar to int. (8114) (SQLExecDirectW)') [SQL: EXEC [dbo].[sp_HelpdeskInitializeTicketUpdate] empid_it_assigned, importance_id] ... The issue has to do with the last parameter, importance_id. Unlike the first parameter, this one is an integer type. My code works fine with VARCHAR parameters.
Author   sqlalchemy
Top answer
1 of 2
1

It looks like you may have missed a field in your line to execute the stored procedure. I quickly copied the stored proc input values into a spreadsheet followed by the values in your test line that throws the error. Have a look, it looks like you're missing perhaps the Day value? After that is entered it should line everything up correctly. I marked up the first line that after a quick glance looks like it is causing the error (others lower will too though, until the missing value is fixed).

2 of 2
0

Basic debugging would be to check your parameters... And if we do that...

Exec usp_New_Program_4 21, --@MemberNumber int
                       3, --@TrainerID int
                       '2020-06-06', --@ProgramStartDate date
                       '2020-07-07', --@TrainerReviewDate date
                       'Y', --@Active char(1)
                       'Chest & Arms', --@Description varchar(50)
                       SCOPE_IDENTITY, --@Day varchar(10)
                       'Bench 
                               Press', --@ProgramID int
                       '50kg Barbell', --@ExerciseType_1 varchar(30)
                       3, --@Equipment_1 varchar(30)
                       6, --@Sets_1 int
                       'Press Ups', --@Reps_1 int
                       'Floor Mat', --@ExerciseType_2 varchar(30)
                       3, --@Equipment_2 varchar(30)
                       15, --@Sets_2 int
                       'Bicep Curls', --@Reps_2 int
                       '15kg 
                               Dumbells', --@ExerciseType_3 varchar(30)
                       3, --@Equipment_3 varchar(30)
                       6, --@Sets_3 int
                       'Tricep Extensions', --@Reps_3 int
                       '15kg Dumbells', --@ExerciseType_4 varchar(30)
                       3, --@Equipment_4 varchar(30)
                       6, --@Sets_4 int
                       SCOPE_IDENTITY --@Reps_4 int

Pretty clear now. The value 'Bench Press' is not an int. Neither are 'Press Ups' , 'Bicep Curls' or 'Tricep Extensions'.

This is why using the format EXEC PROC {Proc Name} @{Parameter Name} = {Parameter Value} is really important for any procedures that have more than 1 or 2 parameters; you don't make simple mistakes like missing a parameter out.

In this case, you clearly missed out a value for @Day (as I assume you wanted to pass SCOPE_IDENTITY for @ProgramID), and thus all your parameters after that are wrong. The SP still ran fine though, as your last parameter (@WorkoutID) has a default value, and so didn't "mind" being omitted.