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

标签 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 应用程序时,我得到这个错误:

Procedure or function newBehzad has too many arguments specified.

我该如何解决?谢谢。

最佳答案

将您的程序更改为:

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/

相关文章:

c# - 要实现什么 Web 服务以便从 iphone 应用程序中轻松读取?

C# WinForms RichTextBox 鼠标中键滚动 : prevent the arrow cursor

C# - 在 ListBox 中选择多个项目并在 Windows 窗体中转换为逗号分隔的字符串

sql-server - 使用性能监视器来监视池连接

mysql - 如何将对象(从 MySQL 临时表)返回到 Coldfusion 存储过程中?

t-sql - 我是否必须在 T-SQL 中的 catch block 中回滚事务之前对事务进行计数?

c# - 如果值已更改 C#,则将参数从文本框发送到存储过程

c# - 属性访问器

sql-server - 如何从 SQL 中的 xml 列中获取元素的所有值

sql-server - 如何使用变量的值作为表名创建永久表