【问题标题】:I've tried different ways but still it's throwing an error that cannot convert varchar to int我尝试了不同的方法,但仍然抛出无法将 varchar 转换为 int 的错误
【发布时间】:2018-02-27 17:56:10
【问题描述】:
private void button_submit_Click(object sender, EventArgs e)
        {

            con = new OleDbConnection("Provider=SQLNCLI11;Data Source=.;Integrated Security=SSPI;Initial Catalog=AdventureWorks2012");
            cmd = new OleDbCommand();
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "usp_empinfo";
            cmd.Connection = con;
            cmd.Parameters.AddWithValue("@bid",textBox_BID.Text);
            cmd.Parameters.AddWithValue("@job",SqlDbType.VarChar).Direction = ParameterDirection.Output;
            cmd.Parameters.AddWithValue("@gender",SqlDbType.VarChar).Direction = ParameterDirection.Output;
            cmd.Parameters.AddWithValue("@maritalstatus",SqlDbType.VarChar).Direction = ParameterDirection.Output;
            con.Open();
            cmd.ExecuteNonQuery();
            label_Job.Text =label_Job.Text + "" + cmd.Parameters["@job"].Value.ToString();
            label_gender.Text=label_gender.Text + "" + cmd.Parameters["@gender"].Value.ToString();
            label_MStatus.Text=label_MStatus.Text + "" + cmd.Parameters["@maritalstatus"].Value.ToString();

        }

我的带有输入输出参数的存储过程:

alter PROC USP_EMPINFO
@bid AS varchar(20),
@job as varchar(20) output,
@gender as varchar(20) output,
@maritalstatus as varchar(20) output
as
begin
select @Job=JobTitle,@Gender=Gender,@maritalstatus=MaritalStatus  from humanresources.employee
where BusinessEntityID = @bid
end

【问题讨论】:

  • select @Job=JobTitle,@Gender=Gender,@maritalstatus=MaritalStatus from humanresources.employee where BusinessEntityID = @bid 你觉得这有什么作用?你想查询这些东西在哪里匹配吗?因为这不是你的做法。另外,humanresources 表是如何定义的?
  • humanresources.employee,BusinessEntityID 可能是一个 int。
  • PS 在同一个代码块中看到“button_click”和“sqlcommand”,很难看。如果你只是在学习..那么很好。但在某些时候,请阅读此内容。 msdn.microsoft.com/en-us/library/…
  • 我猜你的数据库中有一个 int 列。也许婚姻状况?或者您的 BusinessEntityID 可能是数据库中的一个 int,而您只是盲目地将其作为字符串传递,因此有人可以在文本框中将“asdf”传递给您。
  • @Joe 他们对每个值都使用 OUTPUT 参数,而不是获取结果集。不是我会怎么做,但它会起作用。

标签: sql .net sql-server


【解决方案1】:

我只能假设 BusinessEntityID 是一个 int(甚至可能是一个标识符)。在这种情况下,我会将 sproc 参数 @bid 定义为相同的字段类型(int,如果是这样的话)。因此,sproc 定义不允许传入非 int 值。

然后,将 c# 代码更改为 cmd.Parameters.Add("@bid",SqlDbType.Int).Value=int.Parse(textBox_BID.Text.Trim()); //trim 因为你传入了一个可能被填充的字符串

如果它在该行发生故障,您就会知道即使是 c# 也无法将值转换为 int,因此您需要进行额外的字段验证工作。

【讨论】:

  • 非常感谢你们......我在我的存储过程中将数据类型更改为 int 并修改了我的 c# 代码......它现在工作正常......我分享修改后的代码
猜你喜欢
  • 2020-06-21
  • 2016-10-30
  • 2018-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-06
  • 1970-01-01
  • 2019-07-22
相关资源
最近更新 更多