0

I am keep getting

Conversion failed when converting the varchar value '46434,15864' to data type int.

I have this texbox which accepts numeric and commas. I need to create query with emp_num in (46434,15864) like syntax.

enter image description here

The query generated from codebehind is this, which runs fine manually in sql server:

SELECT   *  -- column names
FROM [DBO].[tablename] LPR 
WHERE LPR.[EMPLOYEE_NUMBER] in (46434,15864) 

code:

  if (txtEmpNum.Text.Trim() != "")
        {
            ////sb.Append("  and LPR.[EMPLOYEE_NUMBER] like '%'+ @empnumber + '%' ");  
            sb.Append("  and LPR.[EMPLOYEE_NUMBER] in (@empnumber) ");  
            cmd.Parameters.Add("@empnumber", SqlDbType.VarChar).Value = txtEmpNum.Text.Trim(); //.Replace("," ,  "','");
        }

        cmd.CommandText = sb.ToString();

        DataTable dt = GetData(cmd);
        gvdetails.DataSource = dt;
        gvdetails.DataBind();

Table: enter image description here

3
  • you have to remove ',' Commented Apr 18, 2017 at 8:31
  • but from where, the input field ? Commented Apr 18, 2017 at 8:32
  • Your in statement is wrong with dynamic Commented Apr 18, 2017 at 8:35

3 Answers 3

2

You will have to parametrize every value. This way you'll have dynamically created query, but NOT prone to SQL Inject Here's code:

//where IN part of your query
string inClause = "and LPR.[EMPLOYEE_NUMBER] in ({0})";
// string arrays for values and variables of your query
string[] paramValues = txtEmpNum.Text.Trim().Split(',');
string[] paramVars = paramValues.Select((s, i) => "@empNo" + i.ToString()).ToArray();

//create query, ie. and LPR.[EMPLOYEE_NUMBER] in (@empNo0, @empNo1...)
inClause = string.Format(inClause, string.Join(", ", paramVars));

//add vars and values to command
for (int i = 0; i < paramVars.Length; i++)
{
    cmd.Parameters.Add(paramVars[i], SqlDbType.Int).Value = paramValues[i];
}
Sign up to request clarification or add additional context in comments.

3 Comments

Perfect solution! Thanks a lot Nino.
Just curious why it was not working. Reason I am asking because the query generated in stringbuilder runs fine on sql server editor window but not here ?
by adding parameter with Parameters.Add, because of it's type (VarChar), your parameter gets enclosed with single qoutes and it becomes LPR.[EMPLOYEE_NUMBER] in ('46434,15864')
2

You need a split function to create a list from an string. You can create that function running this script once :

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION [dbo].[fnSplitString] 
( 
    @string NVARCHAR(MAX), 
    @delimiter CHAR(1) 
) 
RETURNS @output TABLE(splitdata NVARCHAR(MAX) 
) 
BEGIN 
    set @delimiter = coalesce(@delimiter, dbo.cSeparador());

    DECLARE @start INT, @end INT 
    SELECT @start = 1, @end = CHARINDEX(@delimiter, @string) 
    WHILE @start < LEN(@string) + 1 BEGIN 
        IF @end = 0  
            SET @end = LEN(@string) + 1

        INSERT INTO @output (splitdata)  
        VALUES(SUBSTRING(@string, @start, @end - @start)) 
        SET @start = @end + 1 
        SET @end = CHARINDEX(@delimiter, @string, @start)

    END 
    RETURN 
END

Now your query will be :

SELECT *
FROM [DBO].[tablename] LPR 
WHERE LPR.[EMPLOYEE_NUMBER] in (select * from fnSplitString(@empnumber, ',')) 

You can call it from C# exactly the same way you called your original code.

4 Comments

Wouldn't it be possible to split the input of the textbox and then add it as two separate int parameters? That way it is not vulnerable to SQL Injection.
Yes, but would two parameters be enough ?. Aren't there cases when the users will try to check three or four codes ?.
Well then split it, then iterate through all the parts. A bit more complicated but at least it leads to safer code.
Yes, you can use a split function, and use it on your select. I will edit my answer to show it.
0

Basically the error is saying that your variable @empnumber is varchar and LPR.[EMPLOYEE_NUMBER] is integer

You can just append the value of your textbox to your query.

Edit: As others have suggested, this would be prone to SQL Injection. Marc Guillot and Nino solutions are better.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.