数据库操作--获取存储过程的返回值

用SQL Server数据库写了个存储过程,代码如下

<span style="font-family:KaiTi_GB2312;font-size:18px;">create procedure proc_select 
@id int
as
begin
if exists(select * from news where id=@id)
	return 1
else
	return 2
end
</span>

在C#中通过执行存储过程来获取返回值,但是返回的结果总是-1,纠结啊。在数据库中查询,是没有问题的。存储过程也正确。在数据库中测试改存储过程,也是没有问题的。


那到底是哪里错了呢?为什么会返回-1?

我的代码是这样的

数据库操作--获取存储过程的返回值_第1张图片

<span style="font-family:KaiTi_GB2312;font-size:18px;">private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string conStr = "server=192.168.24.235;database=newssystem;uid=sa;pwd=1";
                SqlConnection conn = new SqlConnection(conStr);
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "proc_select";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Connection = conn;
                conn.Open();
                SqlParameter sp = new SqlParameter("@id", "5");
                cmd.Parameters.Add(sp);
  textBox1.Text = cmd.ExecuteNonQuery().ToString ();
</span>

这样的话就相当于在SQL中是这样执行的

数据库操作--获取存储过程的返回值_第2张图片

后来经过上网查询,如果数据库执行返回的是“命令已成功完成”,则返回的是-1,好吧。。。但是还有一种情况就是如果发生回滚,返回值也为 -1。这就不好玩了,那我怎么判断我的存储过程到底是不是执行成功了?到底怎样获取存储过程正确的返回值呢?

经过上网查询,原来加几行代码就可以了。

<span style="font-family:KaiTi_GB2312;font-size:18px;"> private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string conStr = "server=192.168.24.235;database=newssystem;uid=sa;pwd=1";
                SqlConnection conn = new SqlConnection(conStr);
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "proc_select";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Connection = conn;
                conn.Open();
                SqlParameter sp = new SqlParameter("@id", "5");
                cmd.Parameters.Add(sp);
                SqlParameter returnValue = new SqlParameter("@returnValue", SqlDbType.Int);
               returnValue.Direction = ParameterDirection.ReturnValue;
                cmd.Parameters.Add(returnValue);
                cmd.ExecuteNonQuery();
                textBox1.Text = returnValue.Value.ToString();
                conn.Close();
            }
            catch (Exception ex)
            {
                
                throw ex;
            }
            
        }
</span>

代码中加了一个返回参数,就成功解决了返回值的问题。哈哈~又进步了!


你可能感兴趣的:(sql,server,存储)