You would think that your code would work. However, SQL Server does not guarantee that the WHERE
clause filters the database before the conversion for the SELECT
takes place. In my opinion this is a bug. In Microsoft’s opinion, this is an optimization feature.
Hence, your WHERE
is not guaranteed to work. Even using a CTE doesn’t fix the problem.
The best solution is TRY_CONVERT()
available in SQL Server 2012+:
SELECT AVG(TRY_CONVERT(DECIMAL(18,2), Reimbursement)) AS Amount
FROM Database
WHERE ISNUMERIC(Reimbursement) = 1 AND Reimbursement IS NOT NULL;
In earlier versions, you can use CASE
. The CASE
does guarantee the sequential ordering of the clauses, so:
SELECT AVG(CASE WHEN ISNUMERIC(Reimbursement) = 1 AND Reimbursement IS NOT NULL
THEN CONVERT(DECIMAL(18,2), Reimbursement))
END)
FROM Database;
Because AVG()
ignores NULL
values, the WHERE
is not necessary, but you can include it if you like.
Finally, you could simplify your code by using a computed column:
alter database add Reimbursement_Value as
(CASE WHEN ISNUMERIC(Reimbursement) = 1 AND Reimbursement IS NOT NULL
THEN CONVERT(DECIMAL(18,2), Reimbursement))
END);
Then you could write the code as:
select avg(Reimbursement_Value)
from database
where Reimbursement_Value is not null;
If I run the SQL query below; I get the following error:
Error converting data type nvarchar to numeric.
COLUMNA
contains only numbers (negative and positive) including fields with maximal up to two digits after the decimal and is stored as dot decimal.
IF OBJECT_ID('st00_TABLEA','U') IS NOT NULL DROP TABLE [st00_TABLEA]
SELECT
COLUMNA AS COLUMNA_s
,CASE WHEN [COLUMNA] = '' THEN 0 ELSE CONVERT(NUMERIC(18,2),REPLACE([COLUMNA],',','.')) END AS COLUMNA
INTO st00_TABLEA
FROM dbosu.TABLEA;
I also tried the following, but still same problem:
IF OBJECT_ID('st00_TABLEA','U') IS NOT NULL DROP TABLE [st00_TABLEA]
SELECT
COLUMNA AS COLUMNA_s
,CONVERT(DECIMAL(18,2),COLUMNA) AS COLUMNA
INTO st00_TABLEA
FROM dbosu.TABLEA;
marc_s
734k176 gold badges1332 silver badges1460 bronze badges
asked Oct 21, 2015 at 8:22
0
You might need to revise the data in the column, but anyway you can do one of the following:-
1- check if it is numeric then convert it else put another value like 0
Select COLUMNA AS COLUMNA_s, CASE WHEN Isnumeric(COLUMNA) = 1
THEN CONVERT(DECIMAL(18,2),COLUMNA)
ELSE 0 END AS COLUMNA
2- select only numeric values from the column
SELECT COLUMNA AS COLUMNA_s ,CONVERT(DECIMAL(18,2),COLUMNA) AS COLUMNA
where Isnumeric(COLUMNA) = 1
answered Oct 21, 2015 at 8:55
Emad KhalilEmad Khalil
8031 gold badge8 silver badges14 bronze badges
3
In case of float values with characters ‘e’ ‘+’ it errors out if we try to convert in decimal. (‘2.81104e+006’). It still pass ISNUMERIC test.
SELECT ISNUMERIC('2.81104e+006')
returns 1
.
SELECT convert(decimal(15,2), '2.81104e+006')
returns
error: Error converting data type varchar to numeric.
And
SELECT try_convert(decimal(15,2), '2.81104e+006')
returns NULL
.
SELECT convert(float, '2.81104e+006')
returns the correct value 2811040
.
zx485
28.5k28 gold badges50 silver badges59 bronze badges
answered Oct 18, 2018 at 20:01
ChandrikaChandrika
1771 silver badge4 bronze badges
1
I was running into this error while converting from nvarchar to float.
What I had to do was to use the LEFT
function on the nvarchar field.
Example: Left(Field,4)
Basically, the query will look like:
Select convert(float,left(Field,4)) from TABLE
Just ridiculous that SQL would complicate it to this extent, while with C# it’s a breeze!
Hope it helps someone out there.
סטנלי גרונן
2,92723 gold badges46 silver badges68 bronze badges
answered Jun 22, 2020 at 23:14
1
If your compatibility level is SQL Server 2012 (110) or higher, you can just use TRY_CONVERT
instead of CONVERT
.
SELECT
TRY_CONVERT(DECIMAL(18, 2), COLUMNA) AS COLUMNA
FROM
dbosu.TABLEA;
TRY_CONVERT
returns a value cast to the specified data type if the cast succeeds; otherwise, returns null.
answered Jun 29 at 17:05
BedirBedir
4761 gold badge6 silver badges17 bronze badges
In this guide, we will walk you through the process of troubleshooting and fixing the Error converting data type NVARCHAR to Numeric
issue. This error usually occurs when you attempt to convert an NVARCHAR column to a numeric data type in SQL Server. The error occurs when the NVARCHAR column contains a value that cannot be converted to a numeric data type.
Table of Contents
- Understanding the Error
- Common Causes
- Step-by-Step Solution
- FAQ
- Related Links
Understanding the Error
The Error converting data type NVARCHAR to Numeric
issue occurs when SQL Server tries to convert a non-numeric value in an NVARCHAR column to a numeric data type. For instance, when you attempt to update or insert data into a table that contains an NVARCHAR column with a non-numeric value, and a constraint or trigger exists that requires the column to have a numeric value, the error occurs.
SQL Server supports various data types for storing different types of data. NVARCHAR is a variable-length Unicode character data type, while numeric is a data type that can store exact numeric values with a fixed number of decimal places.
Common Causes
- Non-numeric characters in the NVARCHAR column
- Incorrect data type conversion function
- Implicit data type conversion
Step-by-Step Solution
Step 1: Identify the Non-Numeric Values
The first step in fixing the error is identifying the non-numeric values in the NVARCHAR column. You can use the ISNUMERIC
function to filter out non-numeric values in the column. Here’s an example query to find non-numeric values in the YourColumnName
column of the YourTableName
table:
SELECT *
FROM YourTableName
WHERE ISNUMERIC(YourColumnName) = 0
Step 2: Update or Remove Non-Numeric Values
Once you have identified the non-numeric values, you can either update them with numeric values or remove them altogether. To update a specific row, you can use the following query:
UPDATE YourTableName
SET YourColumnName = 'YourNewNumericValue'
WHERE YourPrimaryKeyColumn = 'PrimaryKeyValue'
To remove a specific row, you can use the following query:
DELETE FROM YourTableName
WHERE YourPrimaryKeyColumn = 'PrimaryKeyValue'
Step 3: Use the Correct Data Type Conversion Function
When converting an NVARCHAR column to a numeric data type, make sure you are using the correct data type conversion function. For instance, use the CAST
or CONVERT
function to explicitly convert the column to a numeric data type:
SELECT CAST(YourColumnName AS NUMERIC(18, 2))
FROM YourTableName
Or
SELECT CONVERT(NUMERIC(18, 2), YourColumnName)
FROM YourTableName
FAQ
What is the difference between NVARCHAR and VARCHAR data types?
- NVARCHAR is a Unicode variable-length character data type that can store both Unicode and non-Unicode characters.
- VARCHAR is a non-Unicode variable-length character data type that can store only non-Unicode characters.
How can I avoid implicit data type conversion?
To avoid implicit data type conversion, always use the correct data type for your columns when creating or altering tables. Also, use the CAST
or CONVERT
functions when you need to explicitly convert one data type to another.
What is the difference between CAST and CONVERT functions?
Both CAST and CONVERT functions are used to convert one data type to another. The main difference between the two is the syntax. The CAST function uses the ANSI SQL-92 syntax, while the CONVERT function uses the SQL Server-specific syntax.
Can I convert an NVARCHAR column to an INT data type?
Yes, you can convert an NVARCHAR column to an INT data type using the CAST
or CONVERT
functions. However, before converting, make sure that the NVARCHAR column contains only integer values, otherwise, an error will occur.
Can I use the TRY_CONVERT function to avoid the error?
Yes, you can use the TRY_CONVERT function to avoid the error. The TRY_CONVERT function returns a NULL value if the conversion fails, instead of raising an error. Here’s an example:
SELECT TRY_CONVERT(NUMERIC(18, 2), YourColumnName)
FROM YourTableName
- Data Types (Transact-SQL)
- CAST and CONVERT (Transact-SQL)
- ISNUMERIC (Transact-SQL)
- TRY_CONVERT (Transact-SQL)
i m making a registration form… where i want the should go in data table according to choice selected by user…
but when i click the «submit» button. it shows me an error like this…
Server Error in '/project@water_billing_system' Application. Error converting data type nvarchar to numeric. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: Error converting data type nvarchar to numeric. Source Error: Line 521: cmd.Parameters.Add(prm_ac_code_password); Line 522: Line 523: cmd.ExecuteNonQuery(); Line 524: conn.Close(); Line 525: } Source File: f:\water billing system\project@water_billing_system\online_redistration.aspx.cs Line: 523
i m using stored procedure for this…
and the store procedure is like below.
Quote:
@registration_datetime datetime,
@ac_code_id varchar(8),
@ac_password varchar(max),
@owner_surname varchar(30),
@owner_first_name varchar(30),
@owner_middle_name varchar(30),
@owner_DOB date,
@add_of_c_industry varchar(MAX),
@handler1_name varchar(50),
@handler1_mobile numeric(14,0),
@handler1_landline numeric(18,0),
@handler1_email varchar(50),
@handler2_name varchar(50),
@handler2_mobile numeric(14,0),
@handler2_landline numeric(18,0),
@handler2_email varchar(50),
@handler3_name varchar(50),
@handler3_mobile numeric(14,0),
@handler3_landline numeric(18,0),
@handler3_email varchar(50),
@connection_type_id int,
@connection_size_id int,
@connection_plan_id int,
@connection_start_wish date
all the data type is same in sqltable as above…
and this is my «aspx.cs» code…
protected void btn_submit_Click(object sender, EventArgs e) { string owner_birthdate,wish_start_from,ac_code_id; owner_birthdate = ddl_owner_dob_mm.Text + '/' + ddl_owner_dob_dd.Text + '/' + ddl_owner_dob_yyyy.Text; wish_start_from=ddl_conn_wish_mm.Text+'/'+ddl_conn_wish_dd.Text+'/'+ddl_conn_wish_yyyy.Text; if (rbl_conn_for.SelectedValue == "1") { string hp="HP"; conn.Open(); SqlCommand cmd = new SqlCommand("insert_into_reg_housing_plot",conn); cmd.CommandType = CommandType.StoredProcedure; SqlParameter prm_datetime = new SqlParameter(lbl_date_time.Text, "@registration_datetime"); cmd.Parameters.Add(prm_datetime); SqlParameter prm_owner_surname = new SqlParameter("@owner_surname", txt_owner_surname.Text); cmd.Parameters.Add(prm_owner_surname); SqlParameter prm_owner_first_name = new SqlParameter("@owner_first_name", txt_owner_first_name.Text); cmd.Parameters.Add(prm_owner_first_name); SqlParameter prm_owner_middle_name = new SqlParameter("@owner_middle_name", txt_owner_middle_name.Text); cmd.Parameters.Add(prm_owner_middle_name); SqlParameter prm_owner_DOB = new SqlParameter("@owner_DOB", owner_birthdate); cmd.Parameters.Add(prm_owner_DOB); SqlParameter prm_add_housing_plot = new SqlParameter("@add_of_housing_plot", txt_address_housing_plot.Text); cmd.Parameters.Add(prm_add_housing_plot); SqlParameter prm_handler1_name = new SqlParameter("@handler1_name", txt_handler1_name.Text); cmd.Parameters.Add(prm_handler1_name); SqlParameter prm_handler1_mobile = new SqlParameter("@handler1_mobile", txt_handler1_mobile.Text); cmd.Parameters.Add(prm_handler1_mobile); SqlParameter prm_handler1_landline = new SqlParameter("@handler1_landline", txt_handler1_landline.Text); cmd.Parameters.Add(prm_handler1_landline); SqlParameter prm_handler1_email = new SqlParameter("@handler1_email", txt_handler1_email.Text); cmd.Parameters.Add(prm_handler1_email); SqlParameter prm_handler2_name = new SqlParameter("@handler2_name", txt_handler2_name.Text); cmd.Parameters.Add(prm_handler2_name); SqlParameter prm_handler2_mobile = new SqlParameter("@handler2_mobile", txt_handler2_mobile.Text); cmd.Parameters.Add(prm_handler2_mobile); SqlParameter prm_handler2_landline = new SqlParameter("@handler2_landline", txt_handler2_landline.Text); cmd.Parameters.Add(prm_handler2_landline); SqlParameter prm_handler2_email = new SqlParameter("@handler2_email", txt_handler2_email.Text); cmd.Parameters.Add(prm_handler2_email); SqlParameter prm_handler3_name = new SqlParameter("@handler3_name", txt_handler3_name.Text); cmd.Parameters.Add(prm_handler3_name); SqlParameter prm_handler3_mobile = new SqlParameter("@handler3_mobile", txt_handler3_mobile.Text); cmd.Parameters.Add(prm_handler3_mobile); SqlParameter prm_handler3_landline = new SqlParameter("@handler3_landline", txt_handler3_landline.Text); cmd.Parameters.Add(prm_handler3_landline); SqlParameter prm_handler3_email = new SqlParameter("@handler3_email", txt_handler3_email.Text); cmd.Parameters.Add(prm_handler3_email); if (rbl_connection_type.SelectedValue == "3") { SqlParameter prm_yearly_conn_type = new SqlParameter("@connection_type_id",rbl_connection_type.SelectedValue); cmd.Parameters.Add(prm_yearly_conn_type); SqlParameter prm_fix_yearly_size = new SqlParameter("@connection_size_id",ddl_conn_size_selection_for_fixed_yearly_plan.SelectedValue); cmd.Parameters.Add(prm_fix_yearly_size); SqlParameter prm_fix_yearly_plan = new SqlParameter("@connection_plan_id", ddl_plan_selection_for_fixed_yearly_conn.SelectedValue); cmd.Parameters.Add(prm_fix_yearly_plan); } else if (rbl_connection_type.SelectedValue == "1") { SqlParameter prm_monthly_conn_type = new SqlParameter("@connection_type_id", rbl_connection_type.SelectedValue); cmd.Parameters.Add(prm_monthly_conn_type); SqlParameter prm_fix_monthly_size = new SqlParameter("@connection_size_id", ddl_conn_size_selection_for_fixed_plant.SelectedValue); cmd.Parameters.Add(prm_fix_monthly_size); SqlParameter prm_fix_monthly_plan = new SqlParameter("@connection_plan_id", ddl_plan_selection_for_fixed_conn.SelectedValue); cmd.Parameters.Add(prm_fix_monthly_plan); } else if (rbl_connection_type.SelectedValue == "2") { SqlParameter prm_monthly_conn_type = new SqlParameter("@connection_type_id", rbl_connection_type.SelectedValue); cmd.Parameters.Add(prm_monthly_conn_type); SqlParameter prm_fix_monthly_plan = new SqlParameter("@connection_plan_id", ddl_conn_size_for_meter_plan.SelectedValue); cmd.Parameters.Add(prm_fix_monthly_plan); } SqlParameter prm_start_wish = new SqlParameter("@connection_start_wish",wish_start_from); cmd.Parameters.Add(prm_start_wish); SqlCommand ac = new SqlCommand("select max(ac_code_int) from registration_for_housing_plot",conn); object a; a=ac.ExecuteScalar(); if (a.ToString() == "") { a="1001"; ac_code_id= hp + a; } else { Int64 v; v = (Int64.Parse(a.ToString())) + 1; ac_code_id = hp + v.ToString(); } SqlParameter prm_ac_code_id = new SqlParameter("@ac_code_id", ac_code_id); cmd.Parameters.Add(prm_ac_code_id); ac.ExecuteNonQuery(); SqlParameter prm_ac_code_password = new SqlParameter("@ac_password",txt_confirm_password.Text); cmd.Parameters.Add(prm_ac_code_password); cmd.ExecuteNonQuery(); conn.Close(); } else if (rbl_conn_for.SelectedValue == "2") { string ci = "CI"; conn.Open(); SqlCommand cmd = new SqlCommand("insert_into_reg_c_industry", conn); cmd.CommandType = CommandType.StoredProcedure; SqlParameter prm_datetime = new SqlParameter("@registration_datetime", lbl_date_time.Text); cmd.Parameters.Add(prm_datetime); SqlParameter prm_owner_surname = new SqlParameter("@owner_surname", txt_owner_surname.Text); cmd.Parameters.Add(prm_owner_surname); SqlParameter prm_owner_first_name = new SqlParameter("@owner_first_name", txt_owner_first_name.Text); cmd.Parameters.Add(prm_owner_first_name); SqlParameter prm_owner_middle_name = new SqlParameter("@owner_middle_name", txt_owner_middle_name.Text); cmd.Parameters.Add(prm_owner_middle_name); SqlParameter prm_owner_DOB = new SqlParameter("@owner_DOB", owner_birthdate); cmd.Parameters.Add(prm_owner_DOB); SqlParameter prm_add_c_industry = new SqlParameter("@add_of_c_industry", txt_address_commercial_industry.Text); cmd.Parameters.Add(prm_add_c_industry); SqlParameter prm_handler1_name = new SqlParameter("@handler1_name", txt_handler1_name.Text); cmd.Parameters.Add(prm_handler1_name); SqlParameter prm_handler1_mobile = new SqlParameter("@handler1_mobile", txt_handler1_mobile.Text); cmd.Parameters.Add(prm_handler1_mobile); SqlParameter prm_handler1_landline = new SqlParameter("@handler1_landline", txt_handler1_landline.Text); cmd.Parameters.Add(prm_handler1_landline); SqlParameter prm_handler1_email = new SqlParameter("@handler1_email", txt_handler1_email.Text); cmd.Parameters.Add(prm_handler1_email); SqlParameter prm_handler2_name = new SqlParameter("@handler2_name", txt_handler2_name.Text); cmd.Parameters.Add(prm_handler2_name); SqlParameter prm_handler2_mobile = new SqlParameter("@handler2_mobile", txt_handler2_mobile.Text); cmd.Parameters.Add(prm_handler2_mobile); SqlParameter prm_handler2_landline = new SqlParameter("@handler2_landline", txt_handler2_landline.Text); cmd.Parameters.Add(prm_handler2_landline); SqlParameter prm_handler2_email = new SqlParameter("@handler2_email", txt_handler2_email.Text); cmd.Parameters.Add(prm_handler2_email); SqlParameter prm_handler3_name = new SqlParameter("@handler3_name", txt_handler3_name.Text); cmd.Parameters.Add(prm_handler3_name); SqlParameter prm_handler3_mobile = new SqlParameter("@handler3_mobile", txt_handler3_mobile.Text); cmd.Parameters.Add(prm_handler3_mobile); SqlParameter prm_handler3_landline = new SqlParameter("@handler3_landline", txt_handler3_landline.Text); cmd.Parameters.Add(prm_handler3_landline); SqlParameter prm_handler3_email = new SqlParameter("@handler3_email", txt_handler3_email.Text); cmd.Parameters.Add(prm_handler3_email); if (rbl_connection_type.SelectedValue == "3") { SqlParameter prm_yearly_conn_type = new SqlParameter("@connection_type_id", rbl_connection_type.SelectedValue); cmd.Parameters.Add(prm_yearly_conn_type); SqlParameter prm_fix_yearly_size = new SqlParameter("@connection_size_id", ddl_conn_size_selection_for_fixed_yearly_plan.SelectedValue); cmd.Parameters.Add(prm_fix_yearly_size); SqlParameter prm_fix_yearly_plan = new SqlParameter("@connection_plan_id", ddl_plan_selection_for_fixed_yearly_conn.SelectedValue); cmd.Parameters.Add(prm_fix_yearly_plan); } else if (rbl_connection_type.SelectedValue == "1") { SqlParameter prm_monthly_conn_type = new SqlParameter("@connection_type_id", rbl_connection_type.SelectedValue); cmd.Parameters.Add(prm_monthly_conn_type); SqlParameter prm_fix_monthly_size = new SqlParameter("@connection_size_id", ddl_conn_size_selection_for_fixed_plant.SelectedValue); cmd.Parameters.Add(prm_fix_monthly_size); SqlParameter prm_fix_monthly_plan = new SqlParameter("@connection_plan_id", ddl_plan_selection_for_fixed_conn.SelectedValue); cmd.Parameters.Add(prm_fix_monthly_plan); } else if (rbl_connection_type.SelectedValue == "2") { SqlParameter prm_monthly_conn_type = new SqlParameter("@connection_type_id", rbl_connection_type.SelectedValue); cmd.Parameters.Add(prm_monthly_conn_type); SqlParameter prm_fix_monthly_plan = new SqlParameter("@connection_plan_id", ddl_conn_size_for_meter_plan.SelectedValue); cmd.Parameters.Add(prm_fix_monthly_plan); } SqlParameter prm_start_wish = new SqlParameter("@connection_start_wish", wish_start_from); cmd.Parameters.Add(prm_start_wish); SqlCommand ac = new SqlCommand("select max(ac_code_int) from registration_for_comercial_industry",conn); object a; a = ac.ExecuteScalar(); if (a.ToString() == "") { a = "1001"; ac_code_id = ci + a; } else { Int64 v; v = (Int64.Parse(a.ToString())) + 1; ac_code_id = ci + v.ToString(); } SqlParameter prm_ac_code_id = new SqlParameter("@ac_code_id", ac_code_id); cmd.Parameters.Add(prm_ac_code_id); ac.ExecuteNonQuery(); SqlParameter prm_ac_code_password = new SqlParameter("@ac_password", txt_confirm_password.Text); cmd.Parameters.Add(prm_ac_code_password); cmd.ExecuteNonQuery(); conn.Close(); } }
plzz help me solve this…
thanks a lot in advance…
Пытаюсь редактировать данные в таблице но вылезает «Ошибка при преобразовании типа данных nvarchar к numeric.»
C# | ||
|