繁体   English   中英

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

[英]Error converting nvarchar to data type int

当我尝试在我的网站中调用我的存储过程表单代码时,我收到此错误。 我已经被困了很长一段时间,因为我不知道我在哪里转换或声明一个整数值。 这是我的SQL语句:

create procedure GetRepPhoneID
@Rep        nvarchar(100),
@phoneID    nvarchar(100) output
as
set @phoneID = (select concat(CustomerRepPh, '~', cast(RepID as nvarchar(100))) as 'PhoneAndID'
from Reps
where CustomerRep=@Rep)
return @phoneID
go

然后从我的c#代码后面我试图调用存储过程:

public static string GetRepPhone(string Rep){string Connection = WebConfigurationManager.ConnectionStrings [“JDC_DatabaseConnectionString”]。ConnectionString; SqlConnection sqlConnection = new SqlConnection(Connection);

    //This funciton will take all of the values and create them.
    try
    {
        sqlConnection.Open();
    }
    catch (Exception err)
    {
        Console.WriteLine(err.Message);
    }

    SqlCommand cmd = new SqlCommand();
    cmd.Connection = sqlConnection;
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandText = "GetRepPhoneID";           //getting the  procedure created in SQL.

    SqlParameter CustomerParam = new SqlParameter();
    CustomerParam.ParameterName = "Rep";
    CustomerParam.SqlDbType = SqlDbType.NVarChar;
    CustomerParam.Value = Rep;
    CustomerParam.Direction = ParameterDirection.Input;

    //We are using an output parameter not a return one because it is a string.
    SqlParameter ReturnParam = new SqlParameter("phoneID", SqlDbType.NVarChar, 100);
    ReturnParam.Direction = ParameterDirection.Output;

    cmd.Parameters.Add(CustomerParam);
    cmd.Parameters.Add(ReturnParam);

    cmd.ExecuteNonQuery();

    sqlConnection.Close();
    return ReturnParam.Value.ToString();
}

我在我的代码中多次执行相同的操作,但它们都返回整数,因此没有抛出错误,所以我知道它应该工作。 cmd.ExecuteNonQuery()行引发了错误。 确切的错误是:

Conversion failed when converting the nvarchar value '(111)222-6666~29' to data type int.

我知道我不能将该字符串转换为整数,但我没有看到我的代码中的任何地方我声明一个整数,或者我正在尝试转换。

任何帮助将不胜感激。 谢谢。

您正在混淆OUTPUT参数的RETURN值。 RETURN是INT类型的可选状态代码。 将另一个参数声明为OUTPUT。

意思是,这在存储过程中无效:

return @phoneID

而是将@phoneID nvarchar(100) OUTPUT添加到参数列表并删除DECLARE @PhoneID

CREATE PROCEDURE GetRepPhoneID
(
  @Rep        NVARCHAR(100),
  @phoneID    NVARCHAR(100) OUTPUT
)
AS
SET NOCOUNT ON;

SELECT @phoneID = concat(CustomerRepPh, '~', RepID)
FROM Reps
WHERE CustomerRep = @Rep;

以上代表整个过程 您不需要RETURNSET

然后在C#代码中,您需要更改指定参数的方式:

SqlParameter ReturnParam = new SqlParameter("phoneID", SqlDbType.NVarChar, 100);
ReturnParam.Direction = ParameterDirection.Output;

然后删除此行,因为在连接关闭后参数的值将保留,因此不需要此行:

string PhoneAndID = cmd.Parameters[1].Value.ToString();

并将return改为:

return ReturnParam.Value.ToString();

最后,您可能需要更新输入参数的声明,如下所示:

SqlParameter CustomerParam = new SqlParameter("Rep", SqlDbType.NVarChar, 100);
CustomerParam.Value = Rep;
CustomerParam.Direction = ParameterDirection.Input;

暂无
暂无

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

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