How to convert nvarchar to numeric?
I got this error:
Error converting data type nvarchar to numeric.
This is my query
SELECT
strIpay88Amt,
CONVERT(NUMERIC(18, 2), strIpay88Amt) AS iPay
FROM
tblCurrTrxMaster
Assuming that there are string values in strIpay88Amt column. You can use following to convert only numeric values.
select cast(strIpay88Amt as numeric) from tblCurrTrxMaster
where ISNUMERIC(strIpay88Amt) = 1
And following to fetch string values.
select strIpay88Amt from tblCurrTrxMaster where ISNUMERIC(strIpay88Amt) = 0
ISNUMERIC is notoriously bad and returns a lot of "false positives" - I'd much rather use the try_cast function that handles this much more reliably ....There must be some entry in your table that is NOT a valid number and thus your conversion fails - and rightfully so.
So in order to find these entries, you can try this:
SELECT
strIpay88Amt,
TRY_CONVERT(NUMERIC(18, 2), strIpay88Amt) AS iPay
FROM
dbo.tblCurrTrxMaster
WHERE
TRY_CONVERT(NUMERIC(18, 2), strIpay88Amt) IS NULL
This will use the TRY_CONVERT function to attempt the conversion - and with this WHERE clause, you'll only get back all those entries that could not be converted to a valid NUMERIC.
While NULL will "convert" properly to a numeric, an empty string ('') for instance will already cause an error......
try cast syntax:
SELECT strIpay88Amt, CAST(strIpay88Amt AS NUMERIC) AS iPay FROM tblCurrTrxMaster
strIpay88Amtcolumn? And why - if it's a amount - is this anvarchartype to begin with?? You should always use the most appropriate datatype - and if you have an Amount, that's certainly NOTnvarchar!numericjust fine - there must be other values that you're trying to convert that cause this error to be thrown..... the only reason could be that your "locale" uses the comma,as decimal separator, while the strings send you a dot (.). Can you try this:SELECT CAST(N'1.0' AS NUMERIC(18,2))does that work on your server, or throw an error? Next replace the1.0with a1,0and try again,) error is happened.