簡體   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