Receive data from a stored procedure in c #

1

I would like to know how I can obtain a data from the stored procedure in sql server and then insert it into a variable type int in c #.

Already I wrote a code that has to return me the ID greater than I have in my table, but the code that I wrote receives in response "1"

This is my stored procedure:

create procedure NumId  
AS
BEGIN
    SELECT  MAX(id) AS id  FROM dbo.ProductsData 
END
go
execute numID  

This is code in c #:

 string spq = "NumId";                                                                            
            SqlCommand cmd = new SqlCommand(spq, con);
            cmd.CommandType = CommandType.StoredProcedure;
            tblData[5, i].Value = Convert.ToInt32(cmd.ExecuteScalar());
    
asked by Julio Mizrahi 28.06.2018 в 11:26
source

1 answer

-1

I recommend that every time you want to obtain data from a SELECT in an SP you do it through the ExecuteReader () method and then you iterate over the returned recordset

try
{
    cnn.Open();
    string spq = "NumId";                                                                            
    SqlCommand cmd = new SqlCommand(spq, con);
    cmd.CommandType = CommandType.StoredProcedure;
    reader = cmd.ExecuteReader();
    if (reader.HasRows)
    {
        while (reader.Read())
        {
             tblData[5, i].Value = Convert.ToInt32(String.Format("{0}", reader['id']));
        }
    }
    reader.Close();
    cmd.Dispose();
    cnn.Close();
}
catch (Exception ex)
{
     MessageBox.Show("Can not open connection ! ");
}
    
answered by 28.06.2018 в 14:25