資料庫操作--擷取預存程序的傳回值,預存程序傳回值
用SQL Server資料庫寫了個預存程序,代碼如下
<span style="font-family:KaiTi_GB2312;font-size:18px;">create procedure proc_select @id intasbeginif exists(select * from news where id=@id)return 1elsereturn 2end</span>
在C#中通過執行預存程序來擷取返回值,但是返回的結果總是-1,糾結啊。在資料庫中查詢,是沒有問題的。預存程序也正確。在資料庫中測試改預存程序,也是沒有問題的。
那到底是哪裡錯了呢?為什麼會返回-1?
My Code是這樣的
<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中是這樣執行的
後來經過上網查詢,如果資料庫執行返回的是“命令已成功完成”,則返回的是-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>
代碼中加了一個返回參數,就成功解決了返回值的問題。哈哈~又進步了!