Retrieving SQL Server output variables in c#

后端 未结 5 1428
醉梦人生
醉梦人生 2020-12-18 04:25

I have a stored procedure:

ALTER PROCEDURE [dbo].[pr_Tbl_Test_Insert]
    @guidid uniqueidentifier output,
    @sname nvarchar(50)
AS
-- INSERT a new row in          


        
5条回答
  •  情书的邮戳
    2020-12-18 04:54

    I also found this very frustrating and I could not understand the issue. Although many answers are correct, there was one simple line that was often overlooked by me and others, namely the command needs to be store procedure not just any sql with parameters, so I hope this helps:

               cmd.CommandType = CommandType.StoredProcedure;
    

    cmd.Txt should look like this:

               @"my_stored_proct "
    

    NOT

               @"my_stored_proct @p1, @p2, @p3 out"
    

    So putting it all together. You might want to separate it into several methods. and add TimeOuts etc. However these are what I think are the critical parts that differ from other commands witout output Parameters.

          using (SqlCommand cmd= new SqlCommand())
          {
               cmd.Text= ...;
               cmd.CommandType = CommandType.StoredProcedure;
               SqlParameter outParam = cmd.Parameters.Add("@guidid", SqlDbType.Uniqueidentifier);
               outParam.Direction = ParameterDirection.Output;
    
               using (var connection = new SqlConnection(this.myConnectionString))
               {
                connection.Open();
                cmd.Connection = connection;
    
                try
                {
                    cmd.ExecuteNonQuery();
                }
                catch
                {
                 //    put your sql catches etc. here..
                  throw;
                }  
              }  
           var outValue = outParam.Value; 
           //query outValue e.g. ToString()   
           }
    

提交回复
热议问题