Ошибка при преобразовании типа данных nvarchar к bigint

  • Remove From My Forums
  • Question

  • Hi experts,

    I execute the next code:

    SELECT CAST(Order_Number AS bigint)
    FROM Orders 
    WHERE Order_Number IS NOT NULL
    AND ISNUMERIC(Order_Number) = 1
    AND Order_Number NOT LIKE ‘%-%’
    AND Order_Number NOT LIKE ‘%.%’

    And besides having all those checks, it falis with: ‘Error converting data type nvarchar to bigint.’

    How can I spot the row that is breaking this? The table has 1,000,000 rows, so I can’t look for it visually.

    Thanks in advance!!!

Answers

  • Using NOT LIKE ‘%[^0-9]%’ should exclude any OrderNumber that has any character other than ‘0’ through ‘9’.  Putting that in a CTE would certainly ensure that the NOT LIKE is true before trying the conversion, but it shouldn’t be trying the conversion
    on a record that will not be selected.  (If I know that I’m not going to select the record, why would I try to do work on it???)

    I’m wondering, do you need to CONVERT(BIGINT, 2147483647)??  Might it be trying to convert the BIGINT into an INT to do the comparison??  (Just a WAG, but I’ve seen stranger things…)

    HTH,

    Carl

    • Proposed as answer by

      Thursday, April 21, 2016 6:08 AM

    • Marked as answer by
      Sam ZhaMicrosoft contingent staff
      Saturday, April 30, 2016 2:47 AM

Why is query #2 giving me an error converting data type nvarchar to bigint?

Query #1:

SELECT CAST(CAST(AsnNumber AS bigint) AS nvarchar(33)) AS AsnNumber 
FROM [DB1].Schema1.Table1 (nolock)

Tried with Convert as well, but get the same error:

SELECT Convert(nvarchar(33), Convert(bigint, AsnNumber)) AS AsnNumber 
FROM [DB1].Schema1.Table1 (nolock)

Query #2:

SELECT AsnNumber
FROM Query1
WHERE AsnNumber = '1777188'

Here AsnNumber is of type nvarchar(33), null in Table1

asked Aug 18, 2015 at 19:15

user793468's user avatar

user793468user793468

4,89823 gold badges81 silver badges126 bronze badges

6

I’m putting this as an answer, even though it doesn’t really answer the question, because I can’t fit this properly in a comment.

I ran this against SQL Server 2008 and I don’t get any errors..

BEGIN
  DECLARE @t TABLE(AsnNumber NVARCHAR(33))

  INSERT INTO @t (AsnNumber) VALUES('1777188')
  INSERT INTO @t (AsnNumber) VALUES('1777189')

  SELECT AsnNumber FROM @t

  SELECT CAST(AsnNumber AS BIGINT) as AsnNumber 
  FROM @t
  WHERE AsnNumber = '1777188';

  SELECT CAST(CAST(AsnNumber AS BIGINT) AS NVARCHAR(33)) as AsnNumber 
  FROM @t
  WHERE AsnNumber = '1777188';

  SELECT query1.*
  FROM (SELECT CAST(CAST(AsnNumber AS BIGINT) AS NVARCHAR(33)) as AsnNumber FROM @t) as query1
  WHERE AsnNumber = '1777188';

  WITH query1 (AsnNumber) AS 
  (SELECT CAST(CAST(AsnNumber AS BIGINT) AS NVARCHAR(33)) as AsnNumber FROM @t)
  SELECT AsnNumber FROM query1
  WHERE AsnNumber = '1777188';

END

This demonstrates that your query #1 works fine, and it also demonstrates that I can use it as a subquery and I can use it in a common table expression, and still no error. I have no idea why you’re getting an error.

Perhaps you can include a full set of statements to create the table, populate it with data, and then the exact query you’re running that produces the error? If you do that, it would help me to reproduce the issue, and then I could probably explain why it’s occurring. For now, I can’t reproduce your issue.

answered Aug 18, 2015 at 20:28

Jim's user avatar

JimJim

6,75312 gold badges44 silver badges72 bronze badges

1

  • Remove From My Forums
  • Question

  • Hi: I am getting this data conversion error while I am trying to insert one table into another existing table (appending data). I would really appreciate any assistance on this please.

    Thanks

Answers

  • Hi,

    You should list the columns in your SELECT statement in order of the INSERT columns list. But here you haven’t inserted any column. Also you can use a SELECT INFO statement. Therefore a table will be automatically created and you won’t have these problems.

    • Marked as answer by

      Friday, February 21, 2020 9:44 AM

When I run following query with SELECT * I get error saying :

[S0005][8114] Error converting data type nvarchar to bigint.

SELECT * FROM (
                SELECT * , ROW_NUMBER() OVER (ORDER BY CAST(id as BIGINT)) AS RowNum
                FROM users
            ) AS users
            WHERE users.RowNum BETWEEN 0 AND 5 ;

When I run this query only with SELECT id , ROW_NUMBER() ... everything works.

My DB looks like this:

Image of database

This query run well with other table where id column is NVARCHAR

ID column is number only and if i cast it as : CAST(id as NVARCHAR) i get same error.

EDIT:

I Found problem with column ID values

ID 46903836
ID 9100000004

Small ids dont have leading zeros

asked Dec 21, 2016 at 14:05

Lukáš Irsák's user avatar

Lukáš IrsákLukáš Irsák

1,0921 gold badge14 silver badges23 bronze badges

5

Usually when I get this error it is because there is whitespace on the front or end of the column. Here is how I fix it.

SELECT * FROM (
            SELECT * , ROW_NUMBER() OVER (ORDER BY CAST(LTRIM(RTRIM(id)) as BIGINT)) AS RowNum
            FROM users
        ) AS users
        WHERE users.RowNum BETWEEN 0 AND 5 ;

This will ensure ID is just the number only I am also assuming that there aren’t any alpha characters with the ID.

answered Dec 21, 2016 at 14:10

Wes Palmer's user avatar

Wes PalmerWes Palmer

8804 silver badges15 bronze badges

6

You Don’t need to cast your id column as it is already in bigint datatype

SQL server database]

S3S's user avatar

S3S

24.8k5 gold badges26 silver badges45 bronze badges

answered Dec 21, 2016 at 14:13

Satyam Kundula's user avatar

1

Your ID field is BIGINT (you have posted your table structure), this don’t cause the error in your question.

But, because is unuseful the CAST you can rewrite your query as follow:

SELECT * FROM (
    SELECT * , ROW_NUMBER() OVER (ORDER BY id) AS RowNum
    FROM users
) AS users
WHERE users.RowNum BETWEEN 0 AND 5 ;

answered Dec 21, 2016 at 14:12

Joe Taras's user avatar

Joe TarasJoe Taras

15.2k7 gold badges42 silver badges55 bronze badges

3

strees

0 / 0 / 0

Регистрация: 20.12.2013

Сообщений: 2

1

20.12.2013, 18:33. Показов 11836. Ответов 2

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

таблица

T-SQL
1
2
3
4
5
6
7
create table поставщик
(код_поставщика int not null primary key identity(1,1),
телефон varchar(50) not null,
адрес varchar(50) not null,
наименование_поставщика varchar(50) not null,
к_кому_обращаться varchar(50) not null,
unique (код_поставщика))

процедура

T-SQL
1
2
3
4
5
6
7
8
9
create procedure poisk1 
@Ведите_товар bigint
as 
begin 
set nocount on;
select к_кому_обращаться = наименование_поставщика
from поставщик
where наименование_поставщика  = @Ведите_товар
END

ошибка:
Ошибка при преобразовании типа данных nvarchar к bigint.

(строк обработано: 1)



0



1627 / 1129 / 169

Регистрация: 23.07.2010

Сообщений: 6,665

20.12.2013, 20:30

2

Цитата
Сообщение от strees
Посмотреть сообщение

where наименование_поставщика = @Ведите_товар

ужос
varchar(50) и bigint?

Добавлено через 58 секунд

Цитата
Сообщение от strees
Посмотреть сообщение

Ошибка при преобразовании типа данных nvarchar к bigint.

рвет на квадраты



0



StudentMichael

20 / 20 / 1

Регистрация: 03.01.2013

Сообщений: 184

23.12.2013, 08:23

3

Цитата
Сообщение от pincet
Посмотреть сообщение

рвет на квадраты

Ой хорош)))))

Во-первых, зачем тебе bigint? инфа сотка хватит int
Во-вторых, ужасные русские имена колонок… trystory пиши на англ.
В-третьих, для преобразования nvarchar и bigint использую cast

SQL
1
CAST(yourColumn AS data_type)



0



Понравилась статья? Поделить с друзьями:
  • Ошибка при преобразовании типа данных nvarchar к numeric
  • Ошибка при преобразовании типа данных nvarchar к int
  • Ошибка при присоединении базы данных sql
  • Ошибка при преобразовании типа данных nvarchar к float
  • Ошибка при присвоении кадастрового номера