call a stored procedure and receive an integer result from column "output_col" in csharp

You can call a stored procedure and receive an integer result from column "output_col" in C# as follows:

main.cs
// Create a SqlConnection object
using (SqlConnection conn = new SqlConnection("<connection_string>"))
{
    // Open the connection
    conn.Open();

    // Create a SqlCommand object to call the stored procedure
    using (SqlCommand cmd = new SqlCommand("<stored_procedure_name>", conn))
    {
        // Set the command type to stored procedure
        cmd.CommandType = CommandType.StoredProcedure;

        // Add any required parameters to the stored procedure
        // For example:
        // cmd.Parameters.AddWithValue("@param1", <param1_value>);
        // cmd.Parameters.AddWithValue("@param2", <param2_value>);

        // Add the output parameter
        SqlParameter outputParam = new SqlParameter("@output_col", SqlDbType.Int);
        outputParam.Direction = ParameterDirection.Output;
        cmd.Parameters.Add(outputParam);

        // Execute the stored procedure
        cmd.ExecuteNonQuery();

        // Retrieve the integer output value from the output parameter
        int outputValue = Convert.ToInt32(cmd.Parameters["@output_col"].Value);

        // Do something with the output value
    }
}
1124 chars
32 lines

Replace <connection_string> with the actual connection string to your SQL Server instance and <stored_procedure_name> with the name of your stored procedure. Also, add any required input parameters to the stored procedure by calling cmd.Parameters.AddWithValue for each parameter before adding the output parameter. Finally, retrieve the integer output value from the output parameter by calling cmd.Parameters["@output_col"].Value.

gistlibby LogSnag