Home Forums Programming General How to pull a return value from Stored procedure into Winows Form using c# RE: How to pull a return value from Stored procedure into Winows Form using c#

  • rayh 98086 (4/25/2013)


    Hi,

    I am trying to pull a return a single value from a stored procedure, but cannot seem to find the correct logic.

    Can someone share with me help me with my code and tell me where I would put the return value?

    conn = new SqlConnection(Test_Utility.Properties.Settings.Default.ConnectionString);

    conn.Open();

    SqlCommand cmd = new SqlCommand("sp_UploadFile", conn);

    cmd.CommandType = CommandType.StoredProcedure;

    cmd.Parameters.Add(new SqlParameter("@RunNo", theRunNo));

    cmd.Parameters.Add(new SqlParameter("@getFileName", txtFileToProcess.Text));

    rdr = cmd.ExecuteReader();

    rdr.Close();

    rdr.Dispose();

    The best way to do this is to use an OUTPUT parameter from your stored proc. You need to make sure that the parameter is defined as OUTPUT in your proc. And then instead of calling ExecuteReader() you would you would call ExecuteNonQuery();

    SqlParameter myParm = new SqlParameter() { ParameterName = "@MyParameter", Direction = ParameterDirection.Output };

    cmd.Parameters.Add(myParm);

    cmd.ExecuteNonQuery();

    Now you can access myParm.Value.

    Hope that helps.

    _______________________________________________________________

    Need help? Help us help you.

    Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

    Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
    Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
    Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/