How to overcome limitation of ISNUMERIC column "ERROR : overflowed an int column" - sql-server

I have a requirement wherein I have to check whether value entered in VARCHAR(200) column is numeric or not, and if so a relevant error message should be passed.
I am validating the same with ISNUMERIC function since my column value is varchar so user can enter more than 10 characters as well due to which I am getting this error:
overflowed an int column
Because of the other business support, I can not change the data type of the column to int.
As of now I have implemented LEN() < 10 condition before checking ISNUMERIC but seeking if any alternate and better option available.

If you work on Sql server 2012 Than its better to Use TRY_Convert() Function.it will give NULL as output rather than impose error
declare #d varchar(200)='940852774565564'
if ((select ISNUMERIC(#d))=1)
select Try_Convert(#d as bigint)
else
Convert the value to bigint rather than INT
declare #d varchar(200)='940852774565564'
if ((select ISNUMERIC(#d))=1)
select cast(#d as bigint)

Related

How to cast a text column into integer column in MS SQL Express?

I am using Microsoft SQL Express and SQL Server Management Studio.
I am following a tutorial to create a small table from scratch and enter some values as per the below code. The tutorial is teaching how to correctly cast a column if by mistake it is incorrectly declared in the first place.
CREATE TABLE transactions(
transaction_date date,
amount integer,
fee text
);
SELECT * FROM transactions;
INSERT INTO transactions (transaction_date, amount, fee)
VALUES ('2018-09-24', 5454, '30');
The 'fee' column wrongly created as text. I am trying to typecast this column into integer while using the below code. But this is giving following error. Any suggestions?
SELECT transaction_date, amount + CAST (fee AS integer) AS net_amount
FROM transactions;
Explicit conversion from data type text to int is not allowed.
The error is telling you the problem here; you can't explicitly (or implicitly) convert/cast a text value to an int. text has been deprecated for 16 years, so you should not be using it. It was replaced by varchar(MAX) way back in 2005 (along with nvarchar(MAX) for ntext and varbinary(MAX) for image).
Instead, you'll need to convert the value to a varchar first, and then an int. I also recommend using TRY_CONVERT for the latter, as a value like '3.0' will fail to convert:
SELECT TRY_CONVERT(int,CONVERT(varchar(MAX),fee))
FROM dbo.transactions;
Of course, what you should really be doing is fixing the table:
ALTER TABLE dbo.transactions ADD TextFee varchar(MAX) NULL; --To retain any data that couldn't be converted
GO
UPDATE dbo.transactions
SET fee = TRY_CONVERT(int,CONVERT(varchar(MAX),fee)),
TextFee = fee;
GO
ALTER TABLE dbo.transactions ALTER COLUMN fee int;

SQL CAST with ISNULL results in conversionfailure

I've got a nullable column of numbers, which is unfortunately declared as a varchar in the database, and so I want to convert the NULL to 0. Doing this accomplishes that.
select ISNULL(col, '0') from table;
So now there are no null possibilities, and then I want to convert the column to an actual int value, so I tried to wrap that.
select CAST(ISNULL(col, '0') AS INT) from table
When that runs I get a conversion error, as shown below. I don't understand why, or how to get around this:
Conversion failed when converting the varchar value 'NULL' to data type int.
Try like this: Take your ISNULL statement outside
SELECT ISNULL(TRY_CAST(col AS INT),0) AS [col]
FROM SAMPLE_TAB;
If this does not help, then please comment your SQL version.

Conversion failed when using nvarchar, but not varchar

I've run into a situation where I'm getting an error if I run the same query on the same table, the difference being the column type. The query used is:
SELECT [name] FROM [demo] WHERE [name] = 1111111
If the name column is varchar(7) then it runs no problem.
If the name column is nvarchar(7) then it gives an error:
Conversion failed when converting the nvarchar value 'BBBBBBB' to data type int.
The error makes sense - I can see why the integer value can't be directly compared to the string value. I also realise that I can resolve it with a cast to a string for the condition.
However, what I'm not getting is why the behaviour is different for nvarchar and varchar. This chart appears to suggest that they should have the same behaviour for type conversion.
Does anyone know why this is happening?
If you using nvarchar column your query should look like:
SELECT [name] FROM [demo] WHERE [name] = N'1111111'
N at the begin of string to make sure that your string is unicode string (nvarchar)

Conversion failed when converting the nvarchar value to data type int

I have a table of data with a primary key which generally takes the format of $$$$#####$$, although there a couple of exceptions to this where there is no number. I want to extract the number part of the key and then use it so I can generate unique primary keys.
I therefore created a view which contained a column showing only the numeric value and ignored any items which could not convert to numbers.
When I wrote a query to select a specific item from the view I get
Conversion failed when converting the nvarchar value to data type
int.
and it would appear that although I specifically ignored the exceptions in the view they are still being references some how.
Any help would greatly be appreciated.
Matt
I want to extract the number part of the key and then use it so I can
generate unique primary keys.
Use this Fastest way to remove non-numeric characters from a VARCHAR in SQL Server :
CREATE Function [fnRemoveNonNumericCharacters](#strText VARCHAR(1000))
RETURNS VARCHAR(1000)
AS
BEGIN
WHILE PATINDEX('%[^0-9]%', #strText) > 0
BEGIN
SET #strText = STUFF(#strText, PATINDEX('%[^0-9]%', #strText), 1, '')
END
RETURN #strText
END
Pass your column value to the function and then cast it to the integer. You can create another function that convert this checking that whether column value contain any numeric value after applying the above function.
Another Reference.
Hope this help

Problem convert column values from VARCHAR(n) to DECIMAL

I have a SQL Server 2000 database with a column of type VARCHAR(255). All the data is either NULL, or numeric data with up to two points of precision (e.g. '11.85'). I tried to run the following T-SQL query but received the error 'Error converting data type varchar to numeric'
SELECT CAST([MyColumn] AS DECIMAL)
FROM [MyTable];
I tried a more specific cast, which also failed.
SELECT CAST([MyColumn] AS DECIMAL(6,2))
FROM [MyTable];
I also tried the following to see if any data is non-numeric, and the only values returned were NULL.
SELECT ISNUMERIC([MyColumn]), [MyColumn]
FROM [MyTable]
WHERE ISNUMERIC([MyColumn]) = 0;
I tried to convert to other data types, such as FLOAT and MONEY, but only MONEY was successful. So I tried the following:
SELECT CAST(CAST([MyColumn] AS MONEY) AS DECIMAL)
FROM [MyTable];
...which worked just fine. Any ideas why the original query failed? Will there be a problem if I first convert to MONEY and then to DECIMAL?
Thanks!
It's likely that this depends on whether the decimal symbol is a comma or a dot. Here are some test queries and their results:
select CAST('3.6' as decimal) -- 3.60
select CAST('3,6' as decimal) -- Error converting data type varchar to numeric.
select CAST('3.6' as money) -- 3.60
select CAST('3,6' as money) -- 36.00 (!)
select ISNUMERIC('3.6') -- 1
select ISNUMERIC('3,6') -- 1
The documentation for ISNUMERIC says :
ISNUMERIC returns 1 when the input
expression evaluates to a valid
integer, floating point number, money
or decimal type; otherwise it returns
0
Both 3.6 and 3,6 can be cast to money, so that's why isnumeric('3,6') returns 1.
To resolve this issue, replace the comma's with dots (or vice versa, if your system uses comma as the decimal symbol):
select cast(replace('3,6',',','.') as decimal)
Another option is to change the "decimal symbol" in Windows. It's in Config Panel -> Regional and Language -> Formats -> Additional Settings -> Numbers.
Another cause is empty strings. For example, if you use the import wizard to import a CSV file, empty fields will become empty strings, not nulls.
This is a common idiom for fixing this:
CAST(NULLIF([number_as_a_string],'') AS decimal(13,2))
Select CAST(isnull(MyColumn,0) as Decimal(4,2))
FROM [MyTable];

Resources