You Declare Phone No as Numeric Field So You need to Convert Your Text into Integer

 [cPhoneNo] NUMERIC (18)   NOT NULL
 [cFax]     NUMERIC (18)   NOT NULL

Use like this:

com.Parameters.AddWithValue("@phoneno", Convert.ToInt32(contactnumberTB.Text));
com.Parameters.AddWithValue("@fax", Convert.ToInt32(faxTB.Text));

STOP USING ADD WITH VALUES

Answer from Dgan on Stack Overflow
Top answer
1 of 4
6

My best guess would be that your problem is in this line:

dm.AddParameters(4, "@boxtype", Convert.ToString(BoxType(lines.GetValue(I).ToString())));

in the procedure @boxtype is declared as an int but I believe this overload of AddParameters will make your parameter of type varchar. I don't know what your data is but one or other seems wrong. I suspect the above line probably should be

dm.AddParameters(4, "@boxtype", Convert.ToInt32(BoxType(lines.GetValue(I).ToString())));

It depends on exactly what BoxType(lines.GetValue(I).ToString())) returns. If it is a string representation of an int then use the above. If it is an int then you don't need the convert at all:

dm.AddParameters(4, "@boxtype", BoxType(lines.GetValue(I).ToString()));

Why I came to this conclusion

I thought I'd add a note on how I debugged this error so that you can understand for future use.

The error message "Error converting data type nvarchar to int" tells us that somewhere is expecting an int but receiving an nvarchar. Nvarchars are only a type in sql so we know that there must be either something in the sql or something in the call to the database.

If it was a problem in the procedure itself you would have noticed it when you were testing the procedure away from the rest of the app. This means it must have been down to the way the procedure is being called.

At this point we look at the parameter list and find that there is one parameter that is an int. We then check that against the code and hey presto, there's our suspicious looking line...

2 of 4
0

It looks to me like your stored procedure expects Boxtype to be an int. You are, however, setting up the SqlCommand with a @BoxType parameter that will be a string - ADO.NET will interpret that the @BoxType parameter is type string. When it runs the query, it will convert @BoxType to an nvarchar. SQL Server will in turn attempt to convert that nvarchar to an int when executing the stored procedure. Since SQL server can't do this, that's causing your error.

Basically, change this line:

dm.AddParameters(4, "@boxtype",
       Convert.ToString(BoxType(lines.GetValue(I).ToString())));

to

dm.AddParameters(4, "@boxtype", 
       Convert.ToInt32(BoxType(lines.GetValue(I).ToString())));

Being sure, of course, that the value in question is always convertible to an int. :)

🌐
GitHub
github.com › HangfireIO › Hangfire › issues › 1880
SqlException (0x80131904): Error converting data type nvarchar to bigint. · Issue #1880 · HangfireIO/Hangfire
June 15, 2021 - Content root path: E:\vsproject\net5\WebApplication1 fail: Microsoft.AspNetCore.Server.Kestrel[13] Connection id "0HM9FPPD1S4MM", Request id "0HM9FPPD1S4MM:0000000D": An unhandled exception was thrown by the application. System.Data.SqlClient.SqlException (0x80131904): Error converting data type nvarchar to bigint.
Author   gitlsl
🌐
Stack Overflow
stackoverflow.com › questions › 29391703 › errorsystem-data-sqlclient-sqlexception-0x80131904-conversion-failed-when-co
c# - Error:System.Data.SqlClient.SqlException (0x80131904): Conversion failed when converting the nvarchar value - Stack Overflow
Error:System.Data.SqlClient.SqlException (0x80131904): Conversion failed when converting the nvarchar value 'ff' to data type int. at System.Data.SqlClient.SqlConnection.OnError(SqlException except...
🌐
Stack Overflow
stackoverflow.com › questions › 36958263 › error-converting-data-type-nvarchar-to-int-using-stored-procedure
c# - Error converting data type nvarchar to int using stored procedure - Stack Overflow
CREATE PROCEDURE AddStudent @password nvarchar(50), @email nvarchar(50), @role_id int, @reset_hash nvarchar(50), @student_id int, @f_name nvarchar(50), @l_name nvarchar(50), @course_id int, @year int, @dob datetime, @parttime_fulltime nvarchar(50), @personal_tutor_id int, @advisor int, @status_id int, @academic_year int, @profile_image nvarchar(max) AS INSERT INTO users (password, email, role_id, reset_hash) VALUES (@password, @email, @role_id, @reset_hash); SET @student_id = SCOPE_IDENTITY() INSERT INTO student_records (user_id, f_name, l_name, course_id, year, dob, parttime_fulltime, personal_tutor_id, advisor, status_id, academic_year, profile_image) VALUES (@student_id, @f_name, @l_name, @course_id, @year, @dob, @parttime_fulltime, @personal_tutor_id, @advisor, @status_id, @academic_year, @profile_image)
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 56044213 › error-system-data-sqlclient-sqlexception-error-converting-data-type-nvarchar-t
sql - Error System.Data.SqlClient.SqlException: 'Error converting data type nvarchar to numeric.' in c# - Stack Overflow
I'm inserting data from one database table to another with a buttonclick and this error shows up System.Data.SqlClient.SqlException: 'Error converting data type nvarchar to numeric.' in both tables the data types matches. The data types are id = int, Druh = varchar(50), Nazov = varchar(50), Cena = numeric(18,2).
🌐
GitHub
github.com › zzzprojects › EntityFramework-Plus › issues › 664
Microsoft.Data.SqlClient.SqlException: 'Conversion failed when converting the nvarchar value 'Value1' to data type int.' · Issue #664 · zzzprojects/EntityFramework-Plus
December 24, 2020 - If you are seeing an exception, include the full exceptions details (message and stack trace). Microsoft.Data.SqlClient.SqlException HResult=0x80131904 Message=Conversion failed when converting the nvarchar value 'Value1' to data type int.
Author   t11omas
Top answer
1 of 1
1

error converting data type nvarchar to int.

Msg 8114 Level 16 State 5 Line 1 Error converting data ...

Created the following cursor to cause the query to execute one row at a time which allowed me to identify the problem data row SET ARITHABORT OFF SET ARITHIGNORE ON SET ANSI_WARNINGS OFF DECLARE @msg VARCHAR(4096) BEGIN TRY DECLARE @itemid AS NVARCHAR(255); DECLARE C CURSOR FAST_FORWARD FOR SELECT ItemID AS itemid FROM dbo.qryOtherFieldDataVerifySource; OPEN C; FETCH NEXT FROM C INTO @itemid ...

Error converting varchar value to data type int - Stack Overflow

SQL is trying to convert your phrase to int probably because its part of CASE statement. It uses the first route to determine the output type. In your case- you put NULL as the first route option in your CASE so it is determined as int. try putting instead of it this CAST(NULL AS VARCHAR(10))

c# - ErrorSystem.Data.SqlClient.SqlException (0x80131904 ...

System.Data.SqlClient.SqlException Conversion failed when converting the nvarchar value to data type int. Hot Network Questions Why are there two mechanisms to remove/hide disks in Linux?

Getting Error Error converting data type nvarchar to ...

The problem might be that youre not giving anything to infer the data type from as youre not setting the value of the parameter. Try setting the parameters using the Add method as follows cmd.Parameters.Add (@Raumklasse_ID SqlDbType.Int).Value = RAUMKLASSE_ID; That way if you dont want to set the value you can still define the parameter.

Error converting data type varchar to int (stored procedure ...

One possible reason Your MBID parameter is varchar (20) but the MBID column in Members is int. Change the parameter to be int and see if it fixes the problem. Youll also need to change this line in C# cmd.Parameters.Add (@MBID SqlDbType.VarChar).Value = (txtSearch.Text.Trim ()); to.

SQL Error (245) Conversion failed when converting the ...

Firstly check if any values are bad (which I dont doubt there will be because youre storing numerical data as a nvarchar) SELECT YourIdColumn Pro_PCT FROM dbo.YourTable WHERE TRY_CONVERT(intPro_PCT) IS NULL AND Pro_PCT IS NOT NULL; That will give you a dataset back of all the bad data. Youll need to fix all of those values.

type conversion - Why does SQL Server say it cant convert ...

Query 1 worked because when you removed the N (which is used to convert a string to nvarchar) SQL Server didnt need to perform an implicit convertion of sales.type from varchar to nvarchar. In this case sales.pid has an implicit convertion on both queries since its being compared to products.idn which has a different data type.

Top answer
1 of 4
8

Usually it's not a problem to pass a string to a parameter that's numeric, as long as the SQL Server is able to convert the content of the string to a numeric value itself. If that doesn't work, you get this error.

For example: Passing "Hello" to a parameter that's numeric, you get an error. Passing "1234" you don't. Please note that an empty string or a string containing whitespace can not be converted to a numeric value!

However, it should be said that it is not good style to do that. You should make sure that the types you use in your application match the types in the database to avoid problems. Maybe some further detail on why you need to have string types in your application could help.

EDIT 1
To make a parameter optional for the query, the way to go would be the following:

  1. Change your SQL statement to allow optional parameters like WHERE RAUMKLASSE_ID = ISNULL(@Raumklasse_ID, RAUMKLASSE_ID).
  2. Do not add the @Raumklasse_ID parameter if it should be optional or add the value DBNull.Value

You should really consider changing your string properties to nullable types like int?.

EDIT 2
This is how your code could look implementing the changes I suggested in Edit 1:

using (SqlCommand cmd = new SqlCommand(@"SELECT r.BEZEICHNUNG AS BEZEICHNUNG, r.ID AS ID FROM RAUM r WHERE RAUMKLASSE_ID = ISNULL(@Raumklasse_ID, RAUMKLASSE_ID) OR STADT_ID = ISNULL(@Stadt_ID, STADT_ID) OR GEBAEUDE_ID = ISNULL(@Gebaeude_ID, GEBAEUDE_ID) OR REGION_ID = ISNULL(@Region_ID, REGION_ID)", con)) 
{
    con.Open();
    if (!String.IsNullOrWhitespace(RAUMKLASSE_ID))
        cmd.Parameters.AddWithValue("@Raumklasse_ID", RAUMKLASSE_ID);
    else
        cmd.Parameters.AddWithValue("@Raumklasse_ID", DBNull.Value);
    if (!String.IsNullOrWhitespace(STADT_ID))
        cmd.Parameters.AddWithValue("@Stadt_ID", STADT_ID);
    else
        cmd.Parameters.AddWithValue("@Stadt_ID", DBNull.Value);
    if (!String.IsNullOrWhitespace(GEBAEUDE_ID))
        cmd.Parameters.AddWithValue("@Gebaeude_ID", GEBAEUDE_ID);
    else
        cmd.Parameters.AddWithValue("@Gebaeude_ID", DBNull.Value);
    if (!String.IsNullOrWhitespace(REGION_ID))
        cmd.Parameters.AddWithValue("@Region_ID", REGION_ID);
    else
        cmd.Parameters.AddWithValue("@Region_ID", DBNull.Value);
    ...
}
2 of 4
0

The problem might be that you're not giving anything to infer the data type from as you're not setting the value of the parameter.

Try setting the parameters using the Add method as follows:

cmd.Parameters.Add("@Raumklasse_ID", SqlDbType.Int).Value = RAUMKLASSE_ID;

That way if you don't want to set the value, you can still define the parameter.

See here for more: http://msdn.microsoft.com/en-us/library/wbys3e9s

🌐
GitHub
github.com › sqlalchemy › sqlalchemy › discussions › 11543
Error converting data type nvarchar to int · sqlalchemy/sqlalchemy · Discussion #11543
June 28, 2024 - import sqlalchemy as sa engine = sa.create_engine("mssql+pyodbc://scott:tiger^5HHH@msodbcsql18_199") with engine.begin() as conn: conn.exec_driver_sql("DROP PROCEDURE IF EXISTS sproc1") conn.exec_driver_sql("""\ CREATE PROCEDURE sproc1 @some_text nvarchar(50), @importance_id int AS BEGIN SET NOCOUNT ON; -- this sp doesn't actually do anything END """) with engine.begin() as conn: stmt = sa.text("EXEC sproc1 :some_text, :importance_id") conn.execute(stmt, {"some_text": "val1", "importance_id": 123}) # no error conn.execute(stmt, {"some_text": "val1", "importance_id": "123"}) # also no error conn.execute(stmt, {"some_text": "val1", "importance_id": "1,000"}) # Error converting data type nvarchar to int.
Author   sqlalchemy
Top answer
1 of 2
2

Write your query this way. It includes a better test for integers and dumps ISNUMERIC that returns 1 for '-.', for example.

SELECT
    zip,
    coordinates
FROM (
    SELECT
        CASE WHEN ZIP5>'' AND NOT ZIP5 LIKE '%[^0-9]%' THEN
            CONVERT(int, [ZIP5]) END zip,
        CONVERT(varchar(max), geom) AS coordinates
    FROM 
        [SpatialData].[dbo].[zip5]
    WHERE
        ZIP5>'' AND NOT ZIP5 LIKE '%[^0-9]%'
) AS t1
WHERE
    zip >= 85000 AND
    zip < 86000

See this Connect item

SQL Server is free to evaluate the WHERE/SELECT clause in the order that it decides is optimized. A view or derived table is not materialized can easily be expanded into, from the outer query.

What SQL Server is compiling is really a query that looks like this

SELECT
    CONVERT(int, [ZIP5]) AS zip,
    CONVERT(varchar(max), geom) AS coordinates
FROM 
    [SpatialData].[dbo].[zip5]
WHERE
    ISNUMERIC([ZIP5]) = 1
    AND CONVERT(int, [ZIP5]) >= 85000
    AND CONVERT(int, [ZIP5]) < 86000

You can inspect the query plan of your original, but my guess from looking at the structure is that the WHERE clause uses the expression CONVERT(int, [ZIP5]) twice, so it makes sense to streamline the resolution (calculation to a result) of the expression in the process of retrieving data from the table. This puts the processing of the SELECT clause before the WHERE, so your ISNUMERIC() = 1 never got a chance to filter the bad eggs.

It is by-design.

2 of 2
2

This isn't strictly an answer to your question but I would take a step back from your question and think about what you are trying to solve.

Why do you want your zip code stored as an integer? In my experience there is no good reason to store your zip codes as anything but a string.

You say you are ok with ignoring values with letters in them but even strictly numeric zips won't always work. For example 02345 will become 2345. On top of that if you ever decide to add in foreign data integers will not work at all and you will have a great deal of work to fix it. Canadian postal codes for example look like this K1A 0B1. Obviously that will not fit in anything but a string data type. Not to mention it won't fit in a CHAR(5) which is another common data type mistake for zip codes.

Lastly you gain no benefit to storing them as an integer. You aren't going to total them, average them or perform a standard deviation, right? So why bother storing them as a number? An int will take up less space than a char(5) (or better yet varchar(10)) but it's a pretty small savings and doesn't make up for the bad data.