c# – 如何向/从SQL Server存储过程发送和接收参数

在最后一部分我WROTE工作解决方案:我在SQL Server中有这个存储过程:alter PROCEDURE [dbo].[ProcedureName]@v nvarchar(10),@L NVarChar(2)ASBEGINSET NOCOUNT ON;SELECT B,M,VFROM XXXXWHERE V = @v and L = @L...

在最后一部分我WROTE工作解决方案:
我在SQL Server中有这个存储过程:

alter PROCEDURE [dbo].[ProcedureName]
    @v nvarchar(10),
    @L NVarChar(2)
AS
BEGIN
    SET NOCOUNT ON;

    SELECT B,M,V
    FROM XXXX
    WHERE V = @v and L = @L
END

我传递参数,但我无法检索我需要检索选择B,M,V的B,M,V的SELECT部分

SqlCommand Cmd = new SqlCommand("ProcedureName", cnn);
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Parameters.Add("@v", SqlDbType.NVarChar, 10).Value = v;
Cmd.Parameters.Add("@L", SqlDbType.NVarChar, 2).Value = lo;

if (Cmd.Connection.State == ConnectionState.Closed)
{
   Cmd.Connection.Open();
}

Cmd.ExecuteNonQuery();

这是我在这里给予帮助的解决方案:

SqlCommand Cmd = new SqlCommand("ProcedureName", cnn);
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Parameters.Add("@v", SqlDbType.NVarChar, 10).Value = v;
Cmd.Parameters.Add("@L", SqlDbType.NVarChar, 2).Value = lo;

if (Cmd.Connection.State == ConnectionState.Closed)
{
   Cmd.Connection.Open();
}

using (SqlDataReader reader = Cmd.ExecuteReader())
{
   if (reader.HasRows)
   {
      while (reader.Read())
      {
         ret = new MYCLASS();
            ret.B = reader.GetString(0);
            ret.M = reader.GetString(1);
            ret.V = reader.GetString(2);
       }
    }
 }

解决方法:

您需要使用SqlDataReader才能实现此目的.还可以使用块来确保连接对象已正确关闭和处理.

从MSDN开始

To ensure that connections are always closed, open the connection inside of a using block, as shown in the following code fragment. Doing so ensures that the connection is automatically closed when the code exits the block.

您可以将代码更改为:

using(var con = new SqlConnection("ConnectionString")) {
using(var cmd = new SqlCommand("ProcedureName", con)) {

//Params here

con.Open();

using(var reader = cmd.ExecuteReader()) {
    while (reader.Read()) {
        var bValue = reader.GetString(0);
        //Same for the next two values
        }
     }
   }
}

本文标题为:c# – 如何向/从SQL Server存储过程发送和接收参数

基础教程推荐