【问题标题】:Converting data type nvarchar to int将数据类型 nvarchar 转换为 int
【发布时间】:2013-08-19 21:41:12
【问题描述】:

我有这个存储过程:

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))

【问题讨论】:

    标签: c# sql-server stored-procedures sql-server-2008-r2


    【解决方案1】:

    您的设计有问题。如何使用来自 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);
    

    这应该可以解决你的问题

    【讨论】:

    • 因为我将只使用一个可以在每个字段上找到的 searchTextBox。非常感谢:)
    【解决方案2】:

    我建议改为:

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

    希望它对你有用。

    【讨论】:

      【解决方案3】:

      改变

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

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

      【讨论】:

        猜你喜欢
        • 2015-03-14
        • 2015-12-24
        • 1970-01-01
        • 1970-01-01
        • 2020-04-17
        • 2011-08-29
        • 2015-06-20
        • 2016-02-02
        • 1970-01-01
        相关资源
        最近更新 更多