[英]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))
您的设计存在问题。 如何使用Name
和Id
相同字段? 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);
这应该可以解决你的问题
我会建议这个实现:
希望对你有效。
更改
mySqlCommand1.Parameters.AddWithValue("@EmployeeID", textBox1.Text);
至
mySqlCommand1.Parameters.AddWithValue("@EmployeeID",Convert.ToInt32( textBox1.Text));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.