使用返回值调用存储过程。

时间:2021-11-19 21:38:46

I am trying to call a stored procedure from my C# windows application. The stored procedure is running on a local instance of SQL Server 2008. I am able to call the stored procedure but I am not able to retrieve the value back from the stored procedure. This stored procedure is supposed to return the next number in the sequence. I have done research online and all the sites I've seen have pointed to this solution working.

我正在尝试从我的c# windows应用程序调用一个存储过程。存储过程在SQL Server 2008的本地实例上运行。我可以调用存储过程,但是不能从存储过程中检索值。这个存储过程应该返回序列中的下一个数字。我在网上做了调查,我看到的所有网站都指出这个解决方案是有效的。

Stored procedure code:

存储过程代码:

ALTER procedure [dbo].[usp_GetNewSeqVal]
      @SeqName nvarchar(255)
as
begin
      declare @NewSeqVal int
      set NOCOUNT ON
      update AllSequences
      set @NewSeqVal = CurrVal = CurrVal+Incr
      where SeqName = @SeqName

      if @@rowcount = 0 begin
print 'Sequence does not exist'
            return
      end

      return @NewSeqVal
end

Code calling the stored procedure:

调用存储过程的代码:

SqlConnection conn = new SqlConnection(getConnectionString());
conn.Open();

SqlCommand cmd = new SqlCommand(parameterStatement.getQuery(), conn);
cmd.CommandType = CommandType.StoredProcedure;

SqlParameter param = new SqlParameter();

param = cmd.Parameters.Add("@SeqName", SqlDbType.NVarChar);
param.Direction = ParameterDirection.Input;
param.Value = "SeqName";

SqlDataReader reader = cmd.ExecuteReader();

I have also tried using a DataSet to retrieve the return value with the same result. What am I missing to get the return value from my stored procedure? If more information is needed, please let me know.

我还尝试使用一个数据集来检索具有相同结果的返回值。从存储过程中得到的返回值是什么?如果需要更多的信息,请告诉我。

8 个解决方案

#1


104  

You need to add return parameter to the command:

您需要向命令添加返回参数:

using (SqlConnection conn = new SqlConnection(getConnectionString()))
using (SqlCommand cmd = conn.CreateCommand())
{
    cmd.CommandText = parameterStatement.getQuery();
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("SeqName", "SeqNameValue");

    var returnParameter = cmd.Parameters.Add("@ReturnVal", SqlDbType.Int);
    returnParameter.Direction = ParameterDirection.ReturnValue;

    conn.Open();
    cmd.ExecuteNonQuery();
    var result = returnParameter.Value;
}

#2


4  

I know this is old, but i stumbled on it with Google.

我知道这是旧的,但我偶然发现了谷歌。

If you have a return value in your stored procedure say "Return 1" - not using output parameters.

如果您的存储过程中有一个返回值,请输入“return 1”—不要使用输出参数。

You can do the following - "@RETURN_VALUE" is silently added to every command object. NO NEED TO EXPLICITLY ADD

您可以执行以下操作——将“@RETURN_VALUE”悄悄地添加到每个命令对象中。不需要显式添加

    cmd.ExecuteNonQuery();
    rtn = (int)cmd.Parameters["@RETURN_VALUE"].Value;

#3


3  

ExecuteScalar() will work, but an output parameter would be a superior solution.

ExecuteScalar()可以工作,但是输出参数是一个更好的解决方案。

#4


3  

The version of EnterpriseLibrary on my machine had other parameters. This was working:

我机器上的EnterpriseLibrary版本有其他参数。这是工作:

        SqlParameter retval = new SqlParameter("@ReturnValue", System.Data.SqlDbType.Int);
        retval.Direction = System.Data.ParameterDirection.ReturnValue;
        cmd.Parameters.Add(retval);
        db.ExecuteNonQuery(cmd);
        object o = cmd.Parameters["@ReturnValue"].Value;

#5


2  

You can try using an output parameter. http://msdn.microsoft.com/en-us/library/ms378108.aspx

您可以尝试使用输出参数。http://msdn.microsoft.com/en-us/library/ms378108.aspx

#6


2  

I had a similar problem with the SP call returning an error that an expected parameter was not included. My code was as follows.
Stored Procedure:

在SP调用返回一个未包含预期参数的错误时,我遇到了类似的问题。我的代码如下。存储过程:

@Result int OUTPUT

@Result int输出

And C#:

和c#:

            SqlParameter result = cmd.Parameters.Add(new SqlParameter("@Result", DbType.Int32));
            result.Direction = ParameterDirection.ReturnValue;

In troubleshooting, I realized that the stored procedure was ACTUALLY looking for a direction of "InputOutput" so the following change fixed the problem.

在故障排除过程中,我意识到存储过程实际上是在寻找“InputOutput”的方向,因此下面的更改解决了这个问题。

            r

Result.Direction = ParameterDirection.InputOutput;

结果。方向= ParameterDirection.InputOutput;

#7


0  

Or if you're using EnterpriseLibrary rather than standard ADO.NET...

或者如果您使用的是EnterpriseLibrary而不是标准的ADO.NET…

Database db = DatabaseFactory.CreateDatabase();
using (DbCommand cmd = db.GetStoredProcCommand("usp_GetNewSeqVal"))
{
    db.AddInParameter(cmd, "SeqName", DbType.String, "SeqNameValue");
    db.AddParameter(cmd, "RetVal", DbType.Int32, ParameterDirection.ReturnValue, null, DataRowVersion.Default, null);

    db.ExecuteNonQuery(cmd);

    var result = (int)cmd.Parameters["RetVal"].Value;
}

#8


-6  

I see the other one is closed. So basically here's the rough of my code. I think you are missing the string cmd comment. For example if my store procedure is call:DBO.Test. I would need to write cmd="DBO.test". Then do command type equal to store procedure, and blah blah blah

我看到另一个关闭了。这就是我的代码的大致内容。我认为你漏掉了字符串cmd注释。例如,如果我的存储过程是调用:DBO.Test。我需要写cmd="DBO.test"然后执行命令类型等于存储过程,等等

Connection.open();
String cmd="DBO.test"; //the command
Sqlcommand mycommand;

#1


104  

You need to add return parameter to the command:

您需要向命令添加返回参数:

using (SqlConnection conn = new SqlConnection(getConnectionString()))
using (SqlCommand cmd = conn.CreateCommand())
{
    cmd.CommandText = parameterStatement.getQuery();
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("SeqName", "SeqNameValue");

    var returnParameter = cmd.Parameters.Add("@ReturnVal", SqlDbType.Int);
    returnParameter.Direction = ParameterDirection.ReturnValue;

    conn.Open();
    cmd.ExecuteNonQuery();
    var result = returnParameter.Value;
}

#2


4  

I know this is old, but i stumbled on it with Google.

我知道这是旧的,但我偶然发现了谷歌。

If you have a return value in your stored procedure say "Return 1" - not using output parameters.

如果您的存储过程中有一个返回值,请输入“return 1”—不要使用输出参数。

You can do the following - "@RETURN_VALUE" is silently added to every command object. NO NEED TO EXPLICITLY ADD

您可以执行以下操作——将“@RETURN_VALUE”悄悄地添加到每个命令对象中。不需要显式添加

    cmd.ExecuteNonQuery();
    rtn = (int)cmd.Parameters["@RETURN_VALUE"].Value;

#3


3  

ExecuteScalar() will work, but an output parameter would be a superior solution.

ExecuteScalar()可以工作,但是输出参数是一个更好的解决方案。

#4


3  

The version of EnterpriseLibrary on my machine had other parameters. This was working:

我机器上的EnterpriseLibrary版本有其他参数。这是工作:

        SqlParameter retval = new SqlParameter("@ReturnValue", System.Data.SqlDbType.Int);
        retval.Direction = System.Data.ParameterDirection.ReturnValue;
        cmd.Parameters.Add(retval);
        db.ExecuteNonQuery(cmd);
        object o = cmd.Parameters["@ReturnValue"].Value;

#5


2  

You can try using an output parameter. http://msdn.microsoft.com/en-us/library/ms378108.aspx

您可以尝试使用输出参数。http://msdn.microsoft.com/en-us/library/ms378108.aspx

#6


2  

I had a similar problem with the SP call returning an error that an expected parameter was not included. My code was as follows.
Stored Procedure:

在SP调用返回一个未包含预期参数的错误时,我遇到了类似的问题。我的代码如下。存储过程:

@Result int OUTPUT

@Result int输出

And C#:

和c#:

            SqlParameter result = cmd.Parameters.Add(new SqlParameter("@Result", DbType.Int32));
            result.Direction = ParameterDirection.ReturnValue;

In troubleshooting, I realized that the stored procedure was ACTUALLY looking for a direction of "InputOutput" so the following change fixed the problem.

在故障排除过程中,我意识到存储过程实际上是在寻找“InputOutput”的方向,因此下面的更改解决了这个问题。

            r

Result.Direction = ParameterDirection.InputOutput;

结果。方向= ParameterDirection.InputOutput;

#7


0  

Or if you're using EnterpriseLibrary rather than standard ADO.NET...

或者如果您使用的是EnterpriseLibrary而不是标准的ADO.NET…

Database db = DatabaseFactory.CreateDatabase();
using (DbCommand cmd = db.GetStoredProcCommand("usp_GetNewSeqVal"))
{
    db.AddInParameter(cmd, "SeqName", DbType.String, "SeqNameValue");
    db.AddParameter(cmd, "RetVal", DbType.Int32, ParameterDirection.ReturnValue, null, DataRowVersion.Default, null);

    db.ExecuteNonQuery(cmd);

    var result = (int)cmd.Parameters["RetVal"].Value;
}

#8


-6  

I see the other one is closed. So basically here's the rough of my code. I think you are missing the string cmd comment. For example if my store procedure is call:DBO.Test. I would need to write cmd="DBO.test". Then do command type equal to store procedure, and blah blah blah

我看到另一个关闭了。这就是我的代码的大致内容。我认为你漏掉了字符串cmd注释。例如,如果我的存储过程是调用:DBO.Test。我需要写cmd="DBO.test"然后执行命令类型等于存储过程,等等

Connection.open();
String cmd="DBO.test"; //the command
Sqlcommand mycommand;