如何在c#中获取SQL Server存储过程的返回值?

时间:2015-10-13 07:34:47

标签: c# sql-server stored-procedures

我是C#和SQL Server的初学者,我编写了这个查询,用于在SQL Server中创建存储过程:

create procedure newBehzad 
    @id bigint
as
    DECLARE @ResultValue int

    select *
    from TABLEA
    where id > @id

    SET  @ResultValue = -5
go

一切正常,我编写了这个C#代码来调用该存储过程并返回一个值:

using (var conn = new SqlConnection(connectionString))
using (var command = new SqlCommand("newBehzad", conn)
{
    CommandType = CommandType.StoredProcedure
})
{
    conn.Open();

    command.Parameters.Add("@id", SqlDbType.BigInt).Value = 2;
    command.Parameters.Add("@ResultValue", SqlDbType.Int);

    SqlParameter retval = command.Parameters.Add("@ResultValue", SqlDbType.Int);
    retval.Direction = ParameterDirection.ReturnValue;

    retunvalue = (string)command.Parameters["@ResultValue"].Value;

    //SqlParameter retval = sqlcomm.Parameters.Add("@b", SqlDbType.VarChar);
    command.ExecuteNonQuery();
    conn.Close();
}

MessageBox.Show(returnValue);

但是当我运行C#windows应用程序时,我收到此错误:

  

过程或函数newBehzad指定了太多参数。

我该如何解决?感谢。

3 个答案:

答案 0 :(得分:1)

PRICE

答案 1 :(得分:1)

将您的程序更改为:

create procedure newBehzad @id bigint, @ResultValue int OUT
as
SET  @ResultValue = 0
BEGIN
    select *from TABLEA
    where id>@id
    SET  @ResultValue = -5
END
go

请尝试这样的想法:

object returnValue = null;
            using (var conn = new System.Data.SqlClient.SqlConnection(AbaseDB.DBFactory.GetInstance().GetConnectionString()))
            {
                using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand("newBehzad", conn) { CommandType = CommandType.StoredProcedure })
                {
                    conn.Open();
                    command.Parameters.Add("@id", SqlDbType.BigInt).Value = 2;
                    command.Parameters.Add("@ResultValue", SqlDbType.Int).Direction  = ParameterDirection.Output;

                    command.ExecuteNonQuery();

                    returnValue = command.Parameters["@ResultValue"].Value;

                    conn.Close();
                }
                if (returnValue != null)
                    MessageBox.Show(returnValue.ToString());
            }

答案 2 :(得分:1)

首先,您需要更改存储过程以返回值:

create procedure newBehzad @id bigint
as
    DECLARE @ResultValue int
    select *from TABLEA
    where id>@id
    SET  @ResultValue = -5

    Return @ResultValue
go

然后抓住它:

using (var conn = new SqlConnection(connectionString))
{
    conn.Open();        

    using (var cmd = new SqlCommand("newBehzad", conn)
    {
        cmd.CommandType = CommandType.StoredProcedure;

        SqlParameter retval = new SqlParameter();
        retval.Direction = ParameterDirection.ReturnValue;

        cmd.Parameters.Add("@id", SqlDbType.BigInt).Value = 2;  
        cmd.Parameters.Add(retval);

        cmd.ExecuteNonQuery();

        returnValue = (int)retval.Value;
    }
}

但我真的不明白为什么你在存储过程中选择数据...