Accessing SQL Server stored procedure output parameter in C#

前端 未结 5 663
没有蜡笔的小新
没有蜡笔的小新 2020-12-19 18:08

I have a simple SQL Server stored procedure:

ALTER PROCEDURE GetRowCount

(
@count int=0 OUTPUT
)

AS
Select * from Emp where age>30;
SET @count=@@ROWCOUN         


        
相关标签:
5条回答
  • 2020-12-19 18:45

    you have to specify that it is a stored procedure not a query

    cmd.CommandType = CommandType.StoredProcedure;
    
    0 讨论(0)
  • 2020-12-19 18:46

    I find the problem, its the connection string. But now, in the code:

     usuary = (string)cmd.Parameters["@USUARIO"].Value;
    password = (string)cmd.Parameters["@CLAVE"].Value;
    

    the compiler infomrs thats values are null...

    0 讨论(0)
  • 2020-12-19 18:48

    I'd suggest you put your SqlConnection and SqlCommand into using blocks so that their proper disposal is guaranteed.

    Also, if I'm not mistaken, the output parameters are only available after you've completely read the resulting data set that's being returned.

    Since you don't seem to need that at all - why not just use .ExecuteNonQuery() instead? Does that fix the problem?

    using (SqlConnection con = new SqlConnection("Data Source=localhost\\SQLEXPRESS;Initial Catalog=answers;Integrated Security=True"))
    using (SqlCommand cmd = new SqlCommand("dbo.GetRowCount", con))
    {
        cmd.CommandType = CommandType.StoredProcedure;
    
        cmd.Parameters.Add(new SqlParameter("@count", SqlDbType.Int));
        cmd.Parameters["@count"].Direction = ParameterDirection.Output;
    
        con.Open();
        cmd.ExecuteNonQuery();  // *** since you don't need the returned data - just call ExecuteNonQuery
        int ans = (int)cmd.Parameters["@count"].Value;
        con.Close();
    
        Console.WriteLine(ans);
    }
    

    Also : since it seems you're only really interested in the row count - why not simplify your stored procedure to something like this:

    ALTER PROCEDURE GetRowCount
    AS
       SELECT COUNT(*) FROM Emp WHERE age > 30;
    

    and then use this snippet in your C# code:

        con.Open();
    
        object result = cmd.ExecuteScalar();
    
        if(result != null)
        {
            int ans = Convert.ToInt32(result);
        }
    
        con.Close();
    
    0 讨论(0)
  • 2020-12-19 18:52

    Just use ExecuteNonQuery , you can't use ExecuteReader with out parameter in this case

    cmd.ExecuteNonQuery(); 
    

    Or if you want try with ExecuteScalar and ReturnValue

    0 讨论(0)
  • 2020-12-19 18:56

    You should add

    cmd.CommandType = CommandType.StoredProcedure 
    

    before calling it

    0 讨论(0)
提交回复
热议问题