Reputation: 329
SELECT acctcode
FROM oact
WHERE acctcode
BETWEEN 42100000 AND 42100001;
when I run the above query I get an error :
The conversion of the nvarchar value '100000000000000' overflowed an int column.
acctcode is nvarchar type. I have tried:
SELECT convert(bigint,Acctcode) as id
FROM OACT
WHERE acctcode
BETWEEN 42100000 and 42100001;
It gives error :
The conversion of the nvarchar value '100000000000000' overflowed an int column.
Please help!!
Upvotes: 0
Views: 657
Reputation: 95590
Considering the data choice, and that you have a very small range of values (BETWEEN 42100000 AND 42100001
) you would be better off simply using an IN
, and passing the correct data type, so that it's SARGable:
SELECT acctcode
FROM oact
WHERE acctcode IN (N'42100000',N'42100001');
If you are parametrising this, I suggest using a user-defined table type, and using that.
I strongly recommend against using BETWEEN
with nvarchar
values here, as if you had something like WHERE acctcode BETWEEN N'499997' AND N'500001'
then a value like N'5'
would be returned.
Using something like CONVERT
(or TRY_CONVERT
) wrapped around the column (acctcode
) would cause SARGability problems, as a full scan would be required. Considering you have values like N'100000000000000'
, this suggests a large number of rows, which would be some awful performance.
Upvotes: 0
Reputation: 29667
It's caused by the implicit conversion of the VARCHAR column in the WHERE clause.
The string '100000000000000' is to big for a normal INT.
So look for the strings.
select convert(bigint,Acctcode) as id
from OACT
where acctcode between '42100000' and '42100001'
and len(acctcode) = 8;
This will look for acctcode's that are alphabetically in that range.
But it'll work fine for numbers.
(assuming that the acctcode's don't have leading spaces)
Another way is to use TRY_CONVERT, if your Sql Server version supports it.
select Acctcode as id
from OACT
where TRY_CONVERT(INT, acctcode) between 42100000 and 42100001;
A TRY_CONVERT
returns NULL when the conversion fails, instead of error.
So this wouldn't even raise errors on acctcode's that contain letters.
But such function is often non-Sargable.
So this method could be slower if acctcode is indexed, and the query would ignore that index.
Upvotes: 1
Reputation: 13161
In your second query convert to bigint would happen only after the values are selected, but before that they are implicitly converted to int by where clause giving you the error. Try this instead:
select Acctcode from OACT where cast(acctcode as bigint) between 42100000 and 42100001;
Upvotes: 0