What are all values ISNUMERIC function finds as TRUE in sql server? - sql-server

Below part of my query was failing initially:
WHEN ISNUMERIC(npx.nvcAnswer) = 1
THEN CASE
WHEN ABS(CONVERT(DECIMAL(38,2),npx.nvcAnswer)) < 1
THEN CONVERT(VARCHAR,CONVERT(DECIMAL(38,2),npx.nvcAnswer))
ELSE npx.nvcAnswer
END
Below was the error we were getting:
com.microsoft.sqlserver.jdbc.SQLServerException: Error converting data type nvarchar to numeric.
rootCause=SQLException #1: errorCode: 8114 sqlState: S0005 message: Error converting data type nvarchar to numeric.
I realized that it considers '.' & '-' as NUMERIC too.
So I added "NOT npx.nvcAnswer in( '.' , '-')" to it and it worked.
WHEN ISNUMERIC(npx.nvcAnswer) = 1 AND NOT npx.nvcAnswer in( '.' , '-')
THEN CASE
WHEN ABS(CONVERT(DECIMAL(38,2),npx.nvcAnswer)) < 1
THEN CONVERT(VARCHAR,CONVERT(DECIMAL(38,2),npx.nvcAnswer))
ELSE npx.nvcAnswer
END
After some day it started failing again with below error.
com.microsoft.sqlserver.jdbc.SQLServerException: Error converting data type nvarchar to numeric.
rootCause=SQLException #1: errorCode: 8114 sqlState: S0005 message: Error converting data type nvarchar to numeric.
Then I changed below block and it worked: (But I failed to find what values were causing this issue)
OLD:
WHEN ABS(CONVERT(DECIMAL(38,2),npx.nvcAnswer)) < 1
THEN CONVERT(VARCHAR,CONVERT(DECIMAL(38,2),npx.nvcAnswer))
NEW:
WHEN ABS(CONVERT(DECIMAL(38,2),PATINDEX('%[^0-9]%', npx.nvcAnswer))) < 1
THEN CONVERT(VARCHAR,CONVERT(DECIMAL(38,2),PATINDEX('%[^0-9]%', npx.nvcAnswer)))
Ask :
What are all values ISNUMERIC function finds as TRUE in sql server?

I will suggest you should your Try_Cast() function instead of using complex logic to check numeric values.
ISNUMERIC returns 1 for some characters that are not numbers, such as plus (+), minus (-), and valid currency symbols such as the dollar sign ($). Please refer below links for further detail -
https://learn.microsoft.com/en-us/sql/t-sql/functions/isnumeric-transact-sql

Related

Conversion failed when converting the varchar value 'YTLQVLBK' to data type int.; nested exception is com.microsoft.sqlserver.jdbc.SQLServerException:

I am calling a karate DButil to execute one of the database query in the karate script:
* def test = db.readValue('SELECT * FROM CLIENT C WHERE C.ClientCode = ' + globalAccountID)
Here i', unable to convert the globalAccountID to string.
Please help on this.
My error trace is below:
javascript evaluation failed: db.readRows('SELECT * FROM CLIENT C
WHERE C.ClientCode = ' + globalAccountID), StatementCallback;
uncategorized SQLException for SQL [SELECT * FROM CLIENT C WHERE
C.ClientCode = 707]; SQL state [S0001]; error code [245]; Conversion
failed when converting the varchar value 'YTLQVLBK' to data type int.;
nested exception is com.microsoft.sqlserver.jdbc.SQLServerException:
Conversion failed when converting the varchar value 'YTLQVLBK' to data
type int.
The issue is in this code:
C.ClientCode = 707
More specifically, you are comparing an integer to a string. Based on SQL Server Data type precedence rules, it means that column C.ClientCode is converted to integer before comparison can take place.
The solution is to convert 707 to string (varchar) type. You can do something like this:
'SELECT * FROM CLIENT C WHERE C.ClientCode = ''' + globalAccountID + ''''

error converting datatype conversion on single vendoritemnumber in duplicate rows

Sql server query shows error :
Msg 8114, Level 16, State 5, Line 1
Error converting data type varchar to numeric.
Here is the query:
WITH employee AS (
SELECT distinct vendoritemnumber,VendorItemId,
VendorItemDescription,
VendorItemDescriptionAlias,VendorId,BrgItemId,itemconversionFactor,
orderbyuomid,pricebyuomid,vendorcasedescription,manufacturernumber,skunumber,[weight],
averageweight,currentprice,taxable,[status],createddate,inactivedate,lastpurchaseddate,
lastupdatedby,lastupdateddate,vendorpercent,vendorfreight,brandid,pack,size,inventorycategoryid,
binlocation,inventorylocation,inventorystatus,physicalinventoryconversionfactor,stateswhereused,
conceptwhereused,priceupdatedate,size_uom,pack_uom,isdeleted,'' as id,'' itemid,'' as oldprice,
'' as newprice,'' as dateupdated,'' as weekenddate,'' as lastpurdate
FROM VendorItems WHERE BrgItemId=6056)
SELECT * FROM employee
UNION ALL
SELECT '' as ven,v.VendorItemId,
v.VendorItemDescription,v.VendorItemDescriptionAlias,v.VendorId,v.BrgItemId,v.itemconversionFactor,
v.orderbyuomid,v.pricebyuomid,v.vendorcasedescription,v.manufacturernumber,v.skunumber,v.[weight],
v.averageweight,v.currentprice,v.taxable,v.[status],v.createddate,v.inactivedate,v.lastpurchaseddate,
v.lastupdatedby,v.lastupdateddate,v.vendorpercent,v.vendorfreight,v.brandid,v.pack,v.size,v.inventorycategoryid,
v.binlocation,v.inventorylocation,v.inventorystatus,v.physicalinventoryconversionfactor,v.stateswhereused,
v.conceptwhereused,v.priceupdatedate,v.size_uom,v.pack_uom,v.isdeleted,ph.id,ph.itemid,ph.oldprice,
ph.newprice,ph.dateupdated,ph.weekenddate,brg.lastpurchasedate
from [dbo].[VendorItems] v join PriceHistory ph
on ph.ItemId=v.VendorItemId join brgitems brg on
brg.brgitemid=v.BrgItemId
WHERE v.BrgItemId=6056
group by vendoritemnumber,v.VendorItemId,v.VendorItemDescription,v.VendorItemDescriptionAlias,v.VendorId,v.BrgItemId,v.itemconversionFactor,
v.orderbyuomid,v.pricebyuomid,v.vendorcasedescription,v.manufacturernumber,v.skunumber,v.[weight],
v.averageweight,v.currentprice,v.taxable,v.[status],v.createddate,v.inactivedate,v.lastpurchaseddate,
v.lastupdatedby,v.lastupdateddate,v.vendorpercent,v.vendorfreight,v.brandid,v.pack,v.size,v.inventorycategoryid,
v.binlocation,v.inventorylocation,v.inventorystatus,v.physicalinventoryconversionfactor,v.stateswhereused,
v.conceptwhereused,v.priceupdatedate,v.size_uom,v.pack_uom,v.isdeleted,ph.id,ph.itemid,ph.oldprice,
ph.newprice,ph.dateupdated,ph.weekenddate,brg.lastpurchasedate
I want to show single vendoritemnumber in duplicate rows..Any suggestion??
Where is the error??
SQL Server cannot convert an empty string to NUMERIC data type. For example, the following will yield the same error:
SELECT CONVERT(NUMERIC, '')
Replace empty strings ('') with 0 or NULL.
#manoj .Just FYI to know exact error point , double click on the error in message window .It shows the exact line of code on error, Also try to check if any empty values are there for that column and as mentioned by #Serge SQL throws error while any data type is converted to numeric and if its value is empty. Best solution is to add WHERE clause and filter those cases.

Why is my CASE statement requiring the THEN part to be of data type INT?

I am trying to run a query where the below CASE statement is one of the lines. I'm using Report Builder 3.0.
However, I get an error that says :
Conversion failed when converting the varchar value 'Case 1' to data type int; Microsoft SQL Server, Error: 245".
Why is the CASE statement requiring the THEN part to be an INT data type ?
(CASE
WHEN jobs.Uf_Production_Line = 'LN BM6'
THEN 'Case 1'
ELSE
99999
END
) AS line
When using CASE statement, all result expressions must have the same data type. If not, the result will be converted to the data type with a higher precedence. According to BOL
Returns the highest precedence type from the set of types in
result_expressions and the optional else_result_expression.
And since INT has a higher data type precedence than VARCHAR, your query produces an error:
Conversion failed when converting the varchar value 'Case 1' to data
type int; Microsoft SQL Server, Error: 245".
To fix this, you should convert your ELSE part to VARCHAR.
ELSE '99999'
Because your else uses a value with data type int:
ELSE 99999
You use data types (varchar and int) that can't be exchanged automatically.
An option is to use:
ELSE '99999'
You should use '99999' instead of 99999. All values should be the same datatype in CASE, for now in your ELSE part values is of INT datatype.
Full code should be like:
(CASE WHEN jobs.Uf_Production_Line = 'LN BM6' THEN 'Case 1'
ELSE '99999'
END
) AS line
A case statement can only return one data type. So use the number as varchar:
(CASE WHEN jobs.Uf_Production_Line = 'LN BM6'
THEN 'Case 1'
ELSE '99999'
END
) AS line
OR you can return NULL instead of 9999 if you want to represent it as an invalid value for Line:
(CASE WHEN jobs.Uf_Production_Line = 'LN BM6'
THEN 'Case 1'
ELSE NULL
END
) AS line
Because 99999 is an int. Both cases must return the same data type.

SQL Server Cast varchar column value '1218300.00' as int

A large value in a column has caused my SQL to throw error msg:
Error converting data type varchar to numeric
I have isolated this to a particular row. Here is a simplified script that "works":
SELECT
MtgeLoanAmount
, CAST(convert(numeric(15,2),'1218300.00') as int) as TrialValue
FROM dbo.Processed_VA_From_Excel
where FipsStateCode='06'
and FipsCountyCode='013'
and GuarantyAmount = '304575'
which returns results as pasted here:
So when I try to "generalize" my test by adding a 3rd column as follows it fails to convert:
SELECT
MtgeLoanAmount
, CAST(convert(numeric(15,2),'1218300.00') as int) as TrialValue
, CAST(convert(numeric(15,2),MtgeLoanAmount) as int)
FROM dbo.Processed_VA_From_Excel
where
FipsStateCode='06'
and FipsCountyCode='013'
and GuarantyAmount = '304575'
returns this:
Msg 8114, Level 16, State 5, Line 1
Error converting data type varchar to numeric.
This may work for you:
SELECT
MtgeLoanAmount,
CONVERT(INT, ROUND(MtgeLoanAmount, 0)) AS MtgeLoanAmountNoCents
FROM
dbo.Processed_VA_From_Excel
WHERE
FipsStateCode = '06' AND
FipsCountyCode = '013' AND
GuarantyAmount = '304575'

Updating an array and converting from varchar to integer

I'm updating an array by adding a varchar to an int4 array. The 'varchar' field is all numbers so I tried casting it to ::integer but it isn't working
update dwh.attr_lookup set kli_tree = array[target_909_kli::integer] || kli_tree
is giving me this error
ERROR: ERROR: invalid input syntax for integer: ""
Query = update
dwh.attr_lookup set kli_tree = array[target_909_kli::integer]
|| kli_tree
What is the proper way to do this?
You're trying to cast an empty string to an integer and that doesn't work:
=> select ''::int;
ERROR: invalid input syntax for integer: ""
LINE 1: select ''::int;
^
You'll have to decide what you want to do with empty strings. If you want to convert them to zeros, then something like this should work:
array[case when target_909_kli = '' then 0 else target_909_kli::integer end]
Obviously your varchar field is not all numbers. There would not be any double quotes in this case - as the error message informs us.
Try giving a full example if the error has not clear by now. Including table definition and sample values.

Resources