我是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指定的参数过多。


我该如何解决?谢谢。

最佳答案

将您的过程更改为:

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());
            }

关于c# - 如何在C#中获取SQL Server存储过程的返回值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33096726/

10-11 23:07
查看更多