Microsoft SQL Server 2008 (SP1), getting an unexpected ‘Conversion failed’ error.
Not quite sure how to describe this problem, so below is a simple example. The CTE extracts the numeric portion of certain IDs using a search condition to ensure a numeric portion actually exists. The CTE is then used to find the lowest unused sequence number (kind of):
CREATE TABLE IDs (ID CHAR(3) NOT NULL UNIQUE);
INSERT INTO IDs (ID) VALUES ('A01'), ('A02'), ('A04'), ('ERR');
WITH ValidIDs (ID, seq)
AS
(
SELECT ID, CAST(RIGHT(ID, 2) AS INTEGER)
FROM IDs
WHERE ID LIKE 'A[0-9][0-9]'
)
SELECT MIN(V1.seq) + 1 AS next_seq
FROM ValidIDs AS V1
WHERE NOT EXISTS (
SELECT *
FROM ValidIDs AS V2
WHERE V2.seq = V1.seq + 1
);
The error is, ‘Conversion failed when converting the varchar value ‘RR’ to data type int.’
I can’t understand why the value ID = 'ERR' should be being considered for conversion because the predicate ID LIKE 'A[0-9][0-9]' should have removed the invalid row from the resultset.
When the base table is substituted with an equivalent CTE the problem goes away i.e.
WITH IDs (ID)
AS
(
SELECT 'A01'
UNION ALL
SELECT 'A02'
UNION ALL
SELECT 'A04'
UNION ALL
SELECT 'ERR'
),
ValidIDs (ID, seq)
AS
(
SELECT ID, CAST(RIGHT(ID, 2) AS INTEGER)
FROM IDs
WHERE ID LIKE 'A[0-9][0-9]'
)
SELECT MIN(V1.seq) + 1 AS next_seq
FROM ValidIDs AS V1
WHERE NOT EXISTS (
SELECT *
FROM ValidIDs AS V2
WHERE V2.seq = V1.seq + 1
);
Why would a base table cause this error? Is this a known issue?
UPDATE @sgmoore: no, doing the filtering in one CTE and the casting in another CTE still results in the same error e.g.
WITH FilteredIDs (ID)
AS
(
SELECT ID
FROM IDs
WHERE ID LIKE 'A[0-9][0-9]'
),
ValidIDs (ID, seq)
AS
(
SELECT ID, CAST(RIGHT(ID, 2) AS INTEGER)
FROM FilteredIDs
)
SELECT MIN(V1.seq) + 1 AS next_seq
FROM ValidIDs AS V1
WHERE NOT EXISTS (
SELECT *
FROM ValidIDs AS V2
WHERE V2.seq = V1.seq + 1
);
Microsoft SQL Server 2008 (SP1), getting an unexpected ‘Conversion failed’ error.
Not quite sure how to describe this problem, so below is a simple example. The CTE extracts the numeric portion of certain IDs using a search condition to ensure a numeric portion actually exists. The CTE is then used to find the lowest unused sequence number (kind of):
CREATE TABLE IDs (ID CHAR(3) NOT NULL UNIQUE);
INSERT INTO IDs (ID) VALUES ('A01'), ('A02'), ('A04'), ('ERR');
WITH ValidIDs (ID, seq)
AS
(
SELECT ID, CAST(RIGHT(ID, 2) AS INTEGER)
FROM IDs
WHERE ID LIKE 'A[0-9][0-9]'
)
SELECT MIN(V1.seq) + 1 AS next_seq
FROM ValidIDs AS V1
WHERE NOT EXISTS (
SELECT *
FROM ValidIDs AS V2
WHERE V2.seq = V1.seq + 1
);
The error is, ‘Conversion failed when converting the varchar value ‘RR’ to data type int.’
I can’t understand why the value ID = 'ERR' should be being considered for conversion because the predicate ID LIKE 'A[0-9][0-9]' should have removed the invalid row from the resultset.
When the base table is substituted with an equivalent CTE the problem goes away i.e.
WITH IDs (ID)
AS
(
SELECT 'A01'
UNION ALL
SELECT 'A02'
UNION ALL
SELECT 'A04'
UNION ALL
SELECT 'ERR'
),
ValidIDs (ID, seq)
AS
(
SELECT ID, CAST(RIGHT(ID, 2) AS INTEGER)
FROM IDs
WHERE ID LIKE 'A[0-9][0-9]'
)
SELECT MIN(V1.seq) + 1 AS next_seq
FROM ValidIDs AS V1
WHERE NOT EXISTS (
SELECT *
FROM ValidIDs AS V2
WHERE V2.seq = V1.seq + 1
);
Why would a base table cause this error? Is this a known issue?
UPDATE @sgmoore: no, doing the filtering in one CTE and the casting in another CTE still results in the same error e.g.
WITH FilteredIDs (ID)
AS
(
SELECT ID
FROM IDs
WHERE ID LIKE 'A[0-9][0-9]'
),
ValidIDs (ID, seq)
AS
(
SELECT ID, CAST(RIGHT(ID, 2) AS INTEGER)
FROM FilteredIDs
)
SELECT MIN(V1.seq) + 1 AS next_seq
FROM ValidIDs AS V1
WHERE NOT EXISTS (
SELECT *
FROM ValidIDs AS V2
WHERE V2.seq = V1.seq + 1
);
Есть 3 таблицы:
Покупатели — customer(id,name,city,phone,rating)
поставщики — supplier(id,name,city,phone)
договор — contract(id,cust_id,sup_id,date,sum)
Пытаюсь сделать приложение для работы с БД. На одной из форм для таблицы contract использую компонент DBLookupcomboboxEh. В нем появляется список покупателей, выбираю одну из фамилий, а в бд нужно занести его id. Аналогично с поставщиками. Проблема состоит в том, что при добавление новой записи(заключении нового договора) появляется такая ошибка: Ошибка при преобразовании типа данных varchar к int. Как я понимаю в DBLookupcomboboxEh отображается фамилия (тип nvarchar), а id (int). Подскажите пожалуйста как исправить эту ошибку.
Параметры DBLookupcomboboxEh вроде настроены правильно:
Для покупателей:
DataField-cust_id
DataSource-DataModule2.ContractDataSource
KeyField-id
ListField-name
ListSource-DataModule2.CustomerDataSource
C поставщиками аналогично.
Код (для добавления записи):
| Delphi | ||
|
__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь
As per your table structure, there are 3 fields that are of numeric datatype. These are — contactno, pf_acc_no and basic_sal
And the values for these fileds are txtcont.Text, txtqibacc.Text and txtnetsalary.Text respectively, And your are also putting ' around them, that is why they are being treated as varchar filed.
While constructing the sql statement, you should pass the values for these fields as numeric, which is to say without ' marks. So just remove ' before and after these fields and your query should work fine.
SqlCommand cmd = new SqlCommand("INSERT INTO Employee(
empcode,firstname,lastname,gender,address,contactno,bloodgroup,
dateofbirth, country,qid,passportno,passportexpiredate,designation,
doj,doexpid,pf_acc_no, agreementstartdate,agreementenddate,
department,basic_sal,remarks,empimage)
VALUES('" + txtempcode.Text + "','" + txtfrstname.Text + "',
'" + txtlstname.Text + "','" + combogender.Text + "','" +
txtaddr.Text + "'," + txtcont.Text + ",'" + txtblodgrp.Text + "', '" +
dob.Value.ToString("yyyy/MM/dd") + "' ,'" + txtcountry.Text + "','" + tqid.Text + "','" +
txtpassportno.Text + "', '" + passexpdate.Value.ToString("yyyy/MM/dd") + "' ,'" +
combodesig.Text + "', '" + doj.Value.ToString("yyyy/MM/dd") + "', '" + doexpqid.Value.ToString("yyyy/MM/dd") + "', " +
txtqibacc.Text + ", '" + agreestartdate.Value.ToString("yyyy/MM/dd") + "','" + agreeenddate.Value.ToString("yyyy/MM/dd") + "' ,'" + combobranch.Text + "'," + txtnetsalary.Text + ",'" + txtremark.Text + "',@empimage) ", cn);
In case you need to pass null to these numeric fields, use DBNull.Value as shown here —
Assign Null value to the Integer Column in the DataTable
Constructing queries like these are prone to SqlInjection, suggest to use parameterized queries instead.
- Remove From My Forums
-
Question
-
Dear All,
When I am firing a below query I am getting the error
SELECT
Empcode,
Date_of_Joining,
LastWorkingDate,
Tenure,
CASE WHEN CAST( Tenure AS INTEGER) =1 THEN ‘THREE’ ELSE Tenure END TENFROM #TEMP
tenure I AM getting bu substracting lastworking date to date of joining
Error:-
Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the varchar value ‘THREE’ to data type int.Regards,
Vipin jha
Thankx & regards, Vipin jha MCP
-
Changed type
Monday, January 7, 2013 4:41 PM
Question rather than discussion
-
Changed type
Answers
-
Try this,
The problem is you are trying to mix int and varchar datatypes together.
SELECT Empcode, Date_of_Joining, LastWorkingDate, Tenure, CASE WHEN CAST( Tenure AS INTEGER) =1 THEN 'THREE' ELSE Convert(Varchar(100),Tenure) END TEN FROM #TEMP
Regards
satheesh-
Proposed as answer by
Kalman Toth
Monday, January 7, 2013 6:40 PM -
Marked as answer by
Allen Li — MSFT
Monday, January 14, 2013 5:59 AM
-
Proposed as answer by
-
Try
SELECT Empcode, Date_of_Joining, LastWorkingDate, Tenure, CASE WHEN Tenure NOT LIKE '%[^0-9]%' then when CAST( Tenure AS INTEGER) =1 THEN 'THREE' else cast(Tenure as varchar(20)) end ELSE cast(Tenure as varchar(20)) END As TEN
For every expert, there is an equal and opposite expert. — Becker’s Law
My blog
-
Proposed as answer by
Kalman Toth
Monday, January 7, 2013 6:40 PM -
Marked as answer by
Allen Li — MSFT
Monday, January 14, 2013 5:59 AM
-
Proposed as answer by
While developing data processes in SQL Server, under certain circumstances, you might get the error message: error converting varchar to numeric. This error is similar with the conversion error you might get when you are trying to convert a varchar to float, etc.
Read on to find out the reason for getting this error message and how you can easily resolve it within just a minute.
The Numeric Data Type in SQL Server
Prior to discuss how you can reproduce and resolve the issue, it is important that you first understand the numeric data type in SQL Server. As described in the relevant MS Docs article, the numeric data type has fixed precision and scale, and it has equivalent functionality with the decimal data type.
Arguments
The numeric data type takes two arguments, that is precision and scale. The syntax is numeric(precision, scale).
Precision defines the maximum number of decimal digits (in both sides of the number) and its value range is between 1 and 38.
Scale, defines the number of decimal digit that will be stored to the right of the decimal point. Its value can range between 1 and the value specified for precision.
Here’s an example of a numeric data type value in SQL Server:
DECLARE @numValue NUMERIC(10,2); SET @numValue=123456.7890 SELECT @numValue as NumValue; GO
The number returned by the above T-SQL query is: 123456.7890
In the above example I specified as precision 10 and as scale 2.
So, even though I specified 123456.7890 as the numeric value, it was indirectly converted to a numeric(10,2) value and that’s why it returned the value 123456.79
Learn more tips like this! Enroll to our Online Course!
Check our online course titled “Essential SQL Server Development Tips for SQL Developers”
(special limited-time discount included in link).Sharpen your SQL Server database programming skills via a large set of tips on T-SQL and database development techniques. The course, among other, features over than 30 live demonstrations!
(Lifetime Access/ Live Demos / Downloadable Resources and more!) Enroll from $12.99
Reproducing the Conversion Error
Great. Now, let’s reproduce the conversion error by trying to convert a “problematic” varchar value to numeric.
You can find this example below:
DECLARE @valueToConvert VARCHAR(50); SET @valueToConvert='1123,456.7890'; SELECT CAST(@valueToConvert AS NUMERIC(10,2)) as ConvertedNumber; GO
When you execute the above T-SQL code, you will get the below exact error message:
Msg 8114, Level 16, State 5, Line 4
Error converting data type varchar to numeric.
How to Resolve the Conversion Error
As you might have observed in the above example, the @valueToConvert variable, besides the dot (.), it also contains a comma (,).
Therefore, at the time of its conversion to the numeric data type, the comma is considered an illegal character for the destination data type (numeric) and that’s why you get the error message.
In order to resolve the conversion error, you just need to remove the comma (,) from the varchar value that you want to convert to numeric.
Note: At this point, you also need to make sure that the varchar value to be converted, is the actual number you wish to convert to the numeric data type. Also, you need to make sure that you only use the decimal symbol, in this case the dot (.), and not any digit grouping symbols, etc.
So, if we remove the comma from the above example, we can see that the conversion is successful.
DECLARE @valueToConvert VARCHAR(50); SET @valueToConvert='1123456.7890'; SELECT CAST(@valueToConvert AS NUMERIC(10,2)) as ConvertedNumber; GO
Output:

In general, when converting varchar values to numbers (i.e. decimal, numeric, etc.), you need to be careful in order for your varchar value, not contain any digit grouping symbols (i.e. a comma) or any other characters that do not have a meaning as a number.
Check our Online Courses
- SQL Server 2022: What’s New – New and Enhanced Features [New]
- Data Management for Beginners – Main Principles
- Introduction to Azure Database for MySQL
- Working with Python on Windows and SQL Server Databases
- Boost SQL Server Database Performance with In-Memory OLTP
- Introduction to Azure SQL Database for Beginners
- Essential SQL Server Administration Tips
- SQL Server Fundamentals – SQL Database for Beginners
- Essential SQL Server Development Tips for SQL Developers
- Introduction to Computer Programming for Beginners
- .NET Programming for Beginners – Windows Forms with C#
- SQL Server 2019: What’s New – New and Enhanced Features
- Entity Framework: Getting Started – Complete Beginners Guide
- A Guide on How to Start and Monetize a Successful Blog
- Data Management for Beginners – Main Principles
Read Also
Feel free to check our other relevant articles on SQL Server troubleshooting:
- Error converting data type varchar to float
- SQL Server 2022: What’s New – New and Enhanced Features (Course Preview)
- SQLServerAgent could not be started (reason: Unable to connect to server ‘(local)’; SQLServerAgent cannot start)
- ORDER BY items must appear in the select list if SELECT DISTINCT is specified
- There is no SQL Server Failover Cluster Available to Join
- There is insufficient system memory in resource pool ‘internal’ to run this query.
- There is not enough space on the disk. (mscorlib)
- A network-related or instance-specific error occurred while establishing a connection to SQL Server
- Introduction to Azure Database for MySQL (Course Preview)
- [Resolved] Operand type clash: int is incompatible with uniqueidentifier
- The OLE DB provider “Microsoft.ACE.OLEDB.12.0” has not been registered – How to Resolve it
- SQL Server replication requires the actual server name to make a connection to the server – How to Resolve it
- Issue Adding Node to a SQL Server Failover Cluster – Greyed Out Service Account – How to Resolve
- Resolve SQL Server CTE Error – Incorrect syntax near ‘)’.
- SQL Server is Terminating Because of Fatal Exception 80000003 – How to Troubleshoot
- An existing History Table cannot be specified with LEDGER=ON – How to Resolve
- … all SQL Server troubleshooting articles
Featured Database Productivity Tools
Snippets Generator: Create and modify T-SQL snippets for use in SQL Management Studio, fast, easy and efficiently.

Learn more
Dynamic SQL Generator: Convert static T-SQL code to dynamic and vice versa, easily and fast.

Learn more
Subscribe to our newsletter and stay up to date!
Check out our latest software releases!
Check our eBooks!
Rate this article: 



(3 votes, average: 4.33 out of 5)
Loading…
Reference: SQLNetHub.com (https://www.sqlnethub.com)
© SQLNetHub
How to resolve the error: Error converting varchar to numeric in SQL Server
Click to Tweet
Artemakis Artemiou is a Senior SQL Server Architect, Author, a 9 Times Microsoft Data Platform MVP (2009-2018). He has over 20 years of experience in the IT industry in various roles. Artemakis is the founder of SQLNetHub and {essentialDevTips.com}. Artemakis is the creator of the well-known software tools Snippets Generator and DBA Security Advisor. Also, he is the author of many eBooks on SQL Server. Artemakis currently serves as the President of the Cyprus .NET User Group (CDNUG) and the International .NET Association Country Leader for Cyprus (INETA). Moreover, Artemakis teaches on Udemy, you can check his courses here.
Views: 18,638
Я застрял при преобразовании varchar столбца UserID в INT. Я знаю, пожалуйста, не спрашивайте, почему этот UserID столбец не был создан как INT первоначально, длинная история.
Я попробовал это, но это не сработало. и дай мне ошибку:
select CAST(userID AS int) from audit
Ошибка:
Ошибка преобразования при преобразовании значения varchar ‘1581……………………………………………………………………………………………………………. ‘к типу данных int.
Я select len(userID) from audit и он возвращает 128 символов, которые не являются пробелами.
Я попытался определить символы ASCII для тех, кто тянется после идентификатора и значения ASCII = 0.
Я также попытался LTRIM, RTRIM и заменить char(0) на '', но не работает.
Единственный способ это работает, когда я говорю фиксированное количество символов, как это ниже, но UserID не всегда 4 символа.
select CAST(LEFT(userID, 4) AS int) from audit
Ответ 1
Вы можете попробовать обновить таблицу, чтобы избавиться от этих символов:
UPDATE dbo.[audit]
SET UserID = REPLACE(UserID, CHAR(0), '')
WHERE CHARINDEX(CHAR(0), UserID) > 0;
Но тогда вам также нужно будет исправить все, что помещает эти плохие данные в таблицу в первую очередь. Тем временем попробуйте:
SELECT CONVERT(INT, REPLACE(UserID, CHAR(0), ''))
FROM dbo.[audit];
Но это не долгосрочное решение. Исправьте данные (и тип данных, пока вы на нем). Если вы не можете исправить тип данных немедленно, вы можете быстро найти виновника, добавив ограничение проверки:
ALTER TABLE dbo.[audit]
ADD CONSTRAINT do_not_allow_stupid_data
CHECK (CHARINDEX(CHAR(0), UserID) = 0);
ИЗМЕНИТЬ
Итак, это определенно 4-значное целое число, за которым следуют шесть экземпляров CHAR (0). И обходной путь, который я опубликовал, определенно работает для меня:
DECLARE @foo TABLE(UserID VARCHAR(32));
INSERT @foo SELECT 0x31353831000000000000;
-- this succeeds:
SELECT CONVERT(INT, REPLACE(UserID, CHAR(0), '')) FROM @foo;
-- this fails:
SELECT CONVERT(INT, UserID) FROM @foo;
Пожалуйста, подтвердите, что этот код сам по себе (ну, в любом случае, первый SELECT, в любом случае) работает для вас. Если это произойдет, ошибка, которую вы получаете, связана с другим нечисловым символом в другой строке (а если нет, то, возможно, у вас есть сборка, где определенная ошибка не была исправлена). Чтобы попытаться сузить его, вы можете принимать случайные значения из следующего запроса, а затем прокручивать символы:
SELECT UserID, CONVERT(VARBINARY(32), UserID)
FROM dbo.[audit]
WHERE UserID LIKE '%[^0-9]%';
Итак, возьмите случайную строку, а затем вставьте вывод в такой запрос:
DECLARE @x VARCHAR(32), @i INT;
SET @x = CONVERT(VARCHAR(32), 0x...); -- paste the value here
SET @i = 1;
WHILE @i <= LEN(@x)
BEGIN
PRINT RTRIM(@i) + ' = ' + RTRIM(ASCII(SUBSTRING(@x, @i, 1)))
SET @i = @i + 1;
END
Это может занять несколько проб и ошибок, прежде чем вы столкнетесь с какой-либо строкой, которая не работает по какой-либо другой причине, чем CHAR(0) — поскольку вы не можете отфильтровывать строки, содержащие CHAR(0), потому что они могут содержать CHAR(0) и CHAR(something else). Для всех, кого мы знаем, у вас есть значения в таблице, например:
SELECT '15' + CHAR(9) + '23' + CHAR(0);
… который также не может быть преобразован в целое число, заменили ли вы CHAR(0) или нет.
Я знаю, что вы не хотите его слышать, но я действительно рад, что это очень больно для людей, потому что теперь у них больше военных историй, чтобы отбросить назад, когда люди принимают очень плохие решения о типах данных.
Ответ 2
Этот вопрос имеет 91 000 просмотров, поэтому, возможно, многие люди ищут более общее решение проблемы в заголовке «преобразование ошибок varchar в INT»
Если вы используете SQL Server 2012+, одним из способов обработки этих недопустимых данных является использование TRY_CAST
SELECT TRY_CAST (userID AS INT)
FROM audit
В предыдущих версиях вы могли использовать
SELECT CASE
WHEN ISNUMERIC(RTRIM(userID) + '.0e0') = 1
AND LEN(userID) <= 11
THEN CAST(userID AS INT)
END
FROM audit
Оба возвращают NULL, если значение не может быть изменено.
В конкретном случае, который у вас есть в вашем вопросе с известными плохими значениями, я бы использовал следующее.
CAST(REPLACE(userID COLLATE Latin1_General_Bin, CHAR(0),'') AS INT)
Попытка заменить нулевой символ часто проблематична, за исключением случаев, когда используется двоичная сортировка.
Ответ 3
Я бы попробовал обрезать номер, чтобы узнать, что вы получаете:
select len(rtrim(ltrim(userid))) from audit
если это вернет правильное значение, просто выполните:
select convert(int, rtrim(ltrim(userid))) from audit
если это не возвращает правильное значение, тогда я сделал бы замену, чтобы удалить пустое пространство:
select convert(int, replace(userid, char(0), '')) from audit
Ответ 4
Это больше для кого-то Поиск результата, чем оригинал post-er. Это сработало для меня…
declare @value varchar(max) = 'sad';
select sum(cast(iif(isnumeric(@value) = 1, @value, 0) as bigint));
returns 0
declare @value varchar(max) = '3';
select sum(cast(iif(isnumeric(@value) = 1, @value, 0) as bigint));
returns 3
|
|||
| 1ctube
24.06.18 — 15:18 |
День добрый. Из 1с записываю данные в скл. Есть запрос, с условием:
Так вот, после выполнения, 1с выдаёт ошибку: |
||
| shuhard
1 — 24.06.18 — 15:19 |
(0) в 100500 раз |
||
| 1ctube
2 — 24.06.18 — 15:22 |
(1) значит, когда из скл в 1с я получаю данные НаборЗаписей.Fields(«Year»).Value то 1с форматирует число в строку? Если в скл 2018, в 1с получается «2 018»? |
||
| МихаилМ
3 — 24.06.18 — 15:23 |
+(1) |
||
| Смотрящий
4 — 24.06.18 — 15:32 |
Это конечно жесть когда число отдается нечислом … |
||
| youalex
5 — 24.06.18 — 15:36 |
(0) не понял. Ну и, конечно, если записать литерал без пробела, даже в кавычках, то умный скуль его неявно преобразует в int |
||
| spectre1978
6 — 24.06.18 — 15:37 |
(0) а зачем одинарные кавычки? И почему не воспользоваться ADO параметрами вместо того чтобы формировать запрос из кусков? |
||
| hhhh
7 — 24.06.18 — 16:10 |
(0) AND Year = ‘» + Формат(НаборЗаписей.Fields(«Year»).Value, «ЧГ=0») + «‘»; с тебя 500р в кассу мисты. |
||
| Asmody
8 — 24.06.18 — 17:44 |
(4) Жесть когда число при неявном преобразовании в строку получает расделители разрядов. |
||
|
Asmody 9 — 24.06.18 — 17:47 |
Еще большая жесть когда из внешнего источника данные прямо в запрос без проверки пихают. |
![]() |
|
TurboConf — расширение возможностей Конфигуратора 1С |
ВНИМАНИЕ! Если вы потеряли окно ввода сообщения, нажмите Ctrl-F5 или Ctrl-R или кнопку «Обновить» в браузере.
Тема не обновлялась длительное время, и была помечена как архивная. Добавление сообщений невозможно.
Но вы можете создать новую ветку и вам обязательно ответят!
Каждый час на Волшебном форуме бывает более 2000 человек.

