【问题标题】:Saving a result from stored procedure in code behind将存储过程的结果保存在代码后面
【发布时间】:2014-03-15 10:00:21
【问题描述】:

我想从 SQL Server 中的项目表中检索项目 ID。

我创建了一个这样的存储过程:

create proc spFindProjectID
   (@customerid int)
as
begin 
    select Project.pID
    from Project
    where Project.cID=@customerid
end

现在在我的 C# 中,我像这样执行该过程:

 public int findid(int id)
 {
        con = connect("igroup9_test1ConnectionString");
        using (SqlCommand sqlComm = new SqlCommand("[spFindProjectID]", con))
        {
            if (con.State != ConnectionState.Open)
            {
                con.Open();
            }

            try
            {
                sqlComm.CommandType = CommandType.StoredProcedure;
                sqlComm.Parameters.AddWithValue("@customerid", id);

                sqlComm.CommandTimeout = 600;
                sqlComm.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw (ex);
            }
            return
        }
    }

我想保存过程中的结果并返回它。

我该怎么做?

【问题讨论】:

    标签: c# asp.net sql-server stored-procedures save


    【解决方案1】:

    让我们看一下ExecuteNonQuery文档

    对于 UPDATE、INSERT 和 DELETE 语句,返回值是受命令影响的行数。 ... 对于所有其他类型的语句,返回值为-1。

    您正在调用一个存储过程,这不是列出的 3 个语句。

    我假设你的

    select Project.pID
    from Project
    where Project.cID=@customerid
    

    查询只返回一个单元格,您可以使用SqlCommand.ExecuteScalar method,它将第一行的第一列返回为object

    例如;

    sqlComm.CommandType = CommandType.StoredProcedure;
    sqlComm.Parameters.AddWithValue("@customerid", id);
    int value = (int)sqlComm.ExecuteScalar();
    return value;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-11
      • 2011-06-03
      • 1970-01-01
      • 2014-08-02
      • 1970-01-01
      • 2017-11-04
      相关资源
      最近更新 更多