简体   繁体   English

从存储过程中获取默认的返回值?

[英]Get the Default RETURN VALUE from a stored procedure?

public int Test()
        {
            int result = 1;

            SqlCommand cmd = new SqlCommand("spTest", conn);
            cmd.CommandType = CommandType.StoredProcedure;

            var returnParameter = cmd.Parameters.Add("@RETURN_VALUE", SqlDbType.Int);
            returnParameter.Direction = ParameterDirection.ReturnValue;

            try
            {
                conn.Open();
                cmd.ExecuteNonQuery();
                result = Convert.ToInt32(returnParameter.Value);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message.ToString());
            }
            finally
            {
                conn.Close();
            }

            return result;
        }

The method starts out with result = 1 so I can see it changing to a 0 if the query is successful. 该方法以result = 1开始,因此如果查询成功,我可以看到它变为0。 I tested this and it does change from 1 to a 0. My question is, is this the correct way to get the default RETURN_VALUE from a stored procedure? 我对此进行了测试,它的确从1变为0。我的问题是,这是从存储过程中获取默认RETURN_VALUE的正确方法吗?

This also changed the value of result from 1 to 0. Why? 这也将结果的值从1更改为0。为什么? The query hasn't run yet. 该查询尚未运行。

public int Test()
        {
            int result = 1;

            SqlCommand cmd = new SqlCommand("spTest", conn);
            cmd.CommandType = CommandType.StoredProcedure;

            var returnParameter = cmd.Parameters.Add("@RETURN_VALUE", SqlDbType.Int);
            returnParameter.Direction = ParameterDirection.ReturnValue;

            result = Convert.ToInt32(returnParameter.Value);

            try
            {
                conn.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message.ToString());
            }
            finally
            {
                conn.Close();
            }

            return result;
        }

Yes. 是。 Although if your connection fails to open, you'll get an error in your finally 虽然如果您的连接无法打开,但finally会出现错误

And if this is SQL Server, don't start your stored procedure names with sp 如果这是SQL Server,请不要使用sp开头存储过程名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM