繁体   English   中英

将数据类型nvarchar转换为int

[英]Converting data type nvarchar to int

我有这个存储过程:

CREATE PROCEDURE SearchEmployee
        @EmployeeID int,
        @EmployeeName nvarchar(256),
        @Address nvarchar(256),
AS
    Select 
        EmployeeId, EmployeeName, Address 
    From 
        Employee
    Where
        EmployeeID = @EmployeeID OR
        EmployeeName LIKE '%' + @EmployeeName+ '%' OR
        Address LIKE '%' + @Address+ '%' 

然后在我的Winforms中我称之为:

using (SqlCommand mySqlCommand1 = new SqlCommand("dbo.SearchEmployee", myDatabaseConnection))
{
            mySqlCommand1.CommandType = CommandType.StoredProcedure;
            {
                mySqlCommand1.Parameters.AddWithValue("@EmployeeID", textBox1.Text);
                mySqlCommand1.Parameters.AddWithValue("@EmployeeName", textBox1.Text);
                mySqlCommand1.Parameters.AddWithValue("@Address", textBox1.Text);
            }
        }

我将如何避免错误

将数据类型nvarchar转换为int时出错。

当用户键入员工姓名而不是EmployeeID

我在我的存储过程中试过这个:

EmployeeID = cast(@EmployeeID as varchar(10))

您的设计存在问题。 如何使用NameId相同字段? Name可以包含Id不能的任何字符! 如果用户键入非数字,则最快的解决方法是传递Id无效值。

int empId = 0;
if(!int.TryParse(textbox1.Text, out empId))
{
    empId = -1;// or some invalid Id which won't appear in DB
}
mySqlCommand1.Parameters.AddWithValue("@EmployeeID", empId);

这应该可以解决你的问题

我会建议这个实现:

  • 创建两个不同的存储过程 - 一个用于数字ID,另一个用于字母数字查询;
  • 在Winforms应用程序中检测用户输入的内容是否为数字 - 您可以检查TryParse来实现此功能;
  • 根据输入类型使用其中一个。

希望对你有效。

更改

mySqlCommand1.Parameters.AddWithValue("@EmployeeID", textBox1.Text);

mySqlCommand1.Parameters.AddWithValue("@EmployeeID",Convert.ToInt32( textBox1.Text));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM