【问题标题】:SQL Server stored procedure return value to string [duplicate]SQL Server存储过程将值返回到字符串[重复]
【发布时间】:2018-12-15 02:18:57
【问题描述】:

我有一个存储过程,它将返回 SCOPE_IDENTITY(),这是刚刚添加的行的 ID。

我已从我的 C# 应用程序运行该过程并将正确的数据添加到数据库中。我需要的是将此返回值存储为 C~ 中的字符串,以便我可以在 UI 中填充文本框。

SqlConnection con = new SqlConnection(connectionString);
con.Open();

SqlDataAdapter aa = new SqlDataAdapter("sp_insert_order", con);
aa.SelectCommand.CommandType = CommandType.StoredProcedure;
aa.SelectCommand.Parameters.Add("@customer_id", SqlDbType.VarChar, (50)).Value = comboBox1.SelectedItem;

aa.SelectCommand.ExecuteNonQuery();

con.Close();

改为

SqlConnection con = new SqlConnection(connectionString);
con.Open();

SqlDataAdapter aa = new SqlDataAdapter("sp_insert_order", con);
aa.SelectCommand.CommandType = CommandType.StoredProcedure;
aa.SelectCommand.Parameters.Add("@customer_id", SqlDbType.VarChar, (50)).Value = comboBox1.SelectedItem;

object oString = aa.SelectCommand.ExecuteScalar();

string myString = "";

if (oString != null)
{
    myString = oString.ToString();
    textBox1.Text = myString;
}

Textbox1 仍为空白。 :(

【问题讨论】:

  • 存储过程是否真的返回了值?如果不是,则将其作为值返回,就像任何数据元素一样。
  • 存储过程的实现是您问题的关键,但您还没有展示出来。你的意思是RETURN id 还是SELECT 呢?对于RETURN,您需要一个方向为ReturnValueSqlParameter。但是,返回值只能用于传达状态,而不是数据。
  • 无关提示:这里不需要数据适配器:只需使用 SqlCommand。顺便说一句,SqlConnection、SqlCommand 和 SqlDataReader 都是 IDisposable 的,所以每个都应该在 using 块中。完成此操作后,您无需关闭连接,因为它会在退出块时被隐式 Dispose 关闭。
  • 感谢大家的建议和进一步的建议。我会看看以后的工作。我的存储过程插入数据并返回范围标识。我已经对此进行了测试,它可以在 sql management studio 中找到

标签: c# sql-server


【解决方案1】:

好的,我们假设您的 SProc 正在正常返回。尝试按如下方式分配输出参数:

SqlConnection cnx = new SqlConnection(WebConfigurationManager.ConnectionStrings["yourConnName"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = cnx;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "testSProc";
cmd.Parameters.AddWithValue("name", "test Name");
SqlParameter outputParam = cmd.Parameters.Add("outID", SqlDbType.Int);
outputParam.Direction = ParameterDirection.Output;

object oString;

cnx.Open();
cmd.ExecuteNonQuery();
cnx.Close();

TextBox1.Text = outputParam.Value.ToString();

【讨论】:

  • 文本框 1 仍为空白。如上所述更改了我的代码
猜你喜欢
  • 1970-01-01
  • 2010-11-23
  • 1970-01-01
  • 1970-01-01
  • 2020-10-10
  • 1970-01-01
  • 1970-01-01
  • 2011-10-19
  • 1970-01-01
相关资源
最近更新 更多