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 OverflowYou 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
Make following changes in your code
com.Parameters.AddWithValue("@phoneno", Convert.ToDouble(contactnumberTB.Text.ToString()));
com.Parameters.AddWithValue("@@fax", Convert.ToDouble(faxTB..Text.ToString()));
You need to make changes because your trying to insert string value in numeric field. By defining this you you are declaring in db that following fields are are numeric and hence application will fail with string value. And is why above change is required to make numeric value to double.
[cPhoneNo] NUMERIC (18) NOT NULL,
[cFax] NUMERIC (18) NOT NULL,
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...
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. :)
@Gwashoppa, thx for taking time to answer my question. To my understanding return values are not to be mixed with OUTPUT parameters. But in any case I found the solution - data type and length needs to be set explicitly:
cmd.Parameters["@mobile"].SqlDbType = SqlDbType.NVarChar;
cmd.Parameters["@mobile"].Size = 50;
I thought that happened in the AddWithValue function, but apparently not.
Your C# code looks fine... The fact that the line cmd.ExecuteNonQuery(); throws an exception, signifies that the error must lie with some parameter used by the SP.
You will need to isolate your SP in steps to identify the problem area...
For instance, in this statement does the ResetHistory table have the same column types used in your select?
INSERT INTO ResetHistory ([User_ID], MobilePhone, Company_ID, [System], [Status], ResetIP)
SELECT rq.[User_ID], u.MobilePhone, u.Company_ID, rq.[System], '3', rq.ResetIP
FROM ResetQueue rq
...
In this statement, does the mobilephone column return a Varchar value?
SELECT u.[MobilePhone]
FROM [user] u
WHERE u.ObjectGuid = @user
In this statement, does the system column return a Varchar value?
SELECT rq.[system]
FROM ResetQueue rq
WHERE rq.[User_ID] = @user
Setup a try...catch and then iterate over each column so you can identify the culprit. For example:
while ( reader.HasRows )
{
for( int index = 0; index < reader.FieldCount; index ++ )
{
fields[ reader.GetName( index ) ] = reader.GetString( index );
}
}
Is this for a package?
I would Ctrl+F for items that are Int64 in your code and see where they are being sent to. There is an error in which the input is not the same datatype as the output or vis-versa. Check the DataSource to make sure that the datatypes line up as well.
Conversion failed when converting the nvarchar value '%' to data type int
Is pretty clear that you have a datatype issue. And the wildcard of '%' is certainly not a integer. You are probably having the issue because the column in where [column] LIKE @param is probably an integer. So even though you identify the parameter as string it is still trying to do an integer to string comparison.
So you are comparing like WHERE Integer LIKE String and that throws a datatype conversion error because SQL will automatically try to convert your string to an integer.
To solve if you want to search for a number as a string which doesn't seem like a good idea you would do something like:
WHERE CAST([column] AS VARCHAR(10)) LIKE @param.
Instead of using LIKE if the parameter is NULL, try this instead.
SELECT [columns] from [table] where @param is null or [column] = @param
If you pass in a NULL parameter everything is returned. If it isn't null, then only where the column matches the parameter will be returned.
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:
- Change your SQL statement to allow optional parameters like
WHERE RAUMKLASSE_ID = ISNULL(@Raumklasse_ID, RAUMKLASSE_ID). - Do not add the
@Raumklasse_IDparameter if it should be optional or add the valueDBNull.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);
...
}
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
I advice you to use the SqlDbType and put for each parameter to the corresponding type in the database like this :
cmd.Parameters.Add (new SqlParameter("@unitPrice", SqlDbType.Float).Value = txtUnitPrice.Text ;
or
cmd.Parameters.AddWithValue("@unitPrice", SqlDbType.Float).Value = txtUnitPrice.Text;
did you changed the datatype of the field in your DB and it doesnt accept the value? if you dont then you have to....because the datatypes are different
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.
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.