[英]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.