今天沒事簡單的練習了下存儲過程,感受老是作些前端的事情把數據庫的事情都忘得差很少了!前端
今天是個簡單的案例!電話號碼的歸屬地查詢的一個小的demo!sql
廢話很少說現上項目!數據庫
————————————————————————————C#代碼———————————————————————————————————————————————ide
private void Button_Click(object sender, RoutedEventArgs e) { string num = txtNum.Text.Trim(); if (num.Length < 7) { MessageBox.Show("你輸入的電話號碼位數太少!","系統提示",MessageBoxButton.OK,MessageBoxImage.Information); txtNum.Focus(); return; } else { string nums = num.Substring(0, 1); if (nums == "1") { List<PhoneMsg> list = new List<PhoneMsg>(); num = num.Substring(0, 7); SqlParameter[] parms = new SqlParameter[2]; parms[0] = new SqlParameter("@NumPiece", num); parms[1] = new SqlParameter("@Count",SqlDbType.Int); parms[1].Direction = ParameterDirection.Output; DataTable table = SqlHelper.ExecuteQuery("Get_tbPhone_pro",parms); PhoneMsg pm = new PhoneMsg(); pm.Id = Convert.ToInt32(table.Rows[0]["Id"]); pm.NumPiece = table.Rows[0]["NumPiece"].ToString(); pm.NumAddress = table.Rows[0]["NumAddress"].ToString(); pm.NumClass = table.Rows[0]["NumClass"].ToString(); pm.NumCode = table.Rows[0]["NumCode"].ToString(); list.Add(pm); dgMsg.DataContext = list; MessageBox.Show("查詢完成!"); MessageBox.Show("條目數:" + parms[1].Value.ToString()); } else { MessageBox.Show("電話號碼必須得以數字-: 1 開頭!", "系統提示", MessageBoxButton.OK, MessageBoxImage.Error); txtNum.Focus(); return; } } }
——————————————————————————————————存儲過程代碼————————---————————————————————————————spa
create procedure Get_tbPhone_pro ( @NumPiece NVARCHAR(20), @Count int output ) as begin select @Count= COUNT(*) from tb_Phone select * from tb_Phone where NumPiece = @NumPiece end drop procedure Get_tbPhone_pro declare @cc int execute Get_tbPhone_pro @NumPiece='1352636',@Count=@cc output select @cc
———————————————————————————————————————————————————————————————————————————————重點是輸出參數是怎麼帶入和輸出的!以前覺得是這樣3d
int count = 0;
if (nums == "1")
{
List<PhoneMsg> list = new List<PhoneMsg>();code
num = num.Substring(0, 7);
SqlParameter[] parms = new SqlParameter[2];
parms[0] = new SqlParameter("@NumPiece", num);
parms[1] = new SqlParameter("@Count",count);orm
parms[1].Direction = ParameterDirection.Output;server
DataTable table = SqlHelper.ExecuteQuery("Get_tbPhone_pro",parms);blog
而後把count打印出來就是輸出參數,可是嘗試屢次無效,就是不明白什麼道理,後臺原來是要這樣子!
parms[1] = new SqlParameter("@Count",SqlDbType.Int);
MessageBox.Show("條目數:" + parms[1].Value.ToString());
——————————————————————————————————————————————————————————————————————————————
雖然問題很小,可是仍是引起我深思知識仍是要溫故而知新! DEMO下載
存儲過程多參數問題
[csharp] view plaincopyprint?在CODE上查看代碼片派生到個人代碼片 CREATE PROCEDURE [dbo].[GetNameById] @studentid varchar(8), @studentname nvarchar(50) OUTPUT AS BEGIN SELECT @studentname=studentname FROM student WHERE studentid=@studentid if @@Error<>0 RETURN -1 else RETURN 0 END using (SqlConnection conn = new SqlConnection(connStr)) { try { SqlCommand cmd = new SqlCommand("GetNameById", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@studentid", "09888888"); //給輸入參數賦值 SqlParameter parOutput =cmd.Parameters.Add("@studentname", SqlDbType.NVarChar, 50); //定義輸出參數 parOutput.Direction = ParameterDirection.Output; //參數類型爲Output SqlParameter parReturn = new SqlParameter("@return", SqlDbType.Int); parReturn.Direction = ParameterDirection.ReturnValue; //參數類型爲ReturnValue cmd.Parameters.Add(parReturn); conn.Open(); cmd.ExecuteNonQuery(); MessageBox.Show(parOutput.Value.ToString()); //顯示輸出參數的值 MessageBox.Show(parReturn.Value.ToString()); //顯示返回值 } catch (System.Exception ex) { MessageBox.Show(ex.Message); } } Create PROCEDURE AddOrderTran @country nvarchar(100), @adds nvarchar(100), @ynames nvarchar(100), @pids nvarchar(100), @cellp nvarchar(100), @cphone nvarchar(100), @amounts nvarchar(100), @cartnumber nvarchar(100) as Declare @id int BEGIN TRANSACTION insert into Orders(Order_Country,Order_Adress,Order_UserName,Order_PostID,Cells,Order_Phone,Total_pay,CartNumber,IsPay) values (@country,@adds,@ynames,@pids,@cellp,@cphone,@amounts,@cartnumber,'0') Select @id=@@identity insert into Orders_Item (OrderNumber,ProductsID,Products_Color,Products_Price,Order_Qty,Item_Total) select @id,Carts_Item.ProductsID,Carts_Item.Products_Color,Carts_Item.Products_Price,Carts_Item.Item_Qty,Carts_Item.Total_Pay from Carts_Item where Carts_Item.CartNumber=@cartnumber delete Carts_Item where CartNumber=@cartnumber IF @@error <> 0 --發生錯誤 BEGIN ROLLBACK TRANSACTION RETURN 0 END ELSE BEGIN COMMIT TRANSACTION RETURN @id --執行成功 END #region 執行存儲過程 SqlParameter[] param = new SqlParameter[] { new SqlParameter("@country",country), new SqlParameter("@adds",adds), new SqlParameter("@ynames",ynames), new SqlParameter("@pids", pids), new SqlParameter("@cellp",cellp), new SqlParameter("@cphone", cphone), new SqlParameter("@amounts",amounts), new SqlParameter("@cartnumber",cartnumber), new SqlParameter("@return",SqlDbType.Int) }; param[8].Direction = ParameterDirection.ReturnValue; MSCL.SqlHelper.RunProcedure("AddOrderTran", param); object obj = param[8].Value; //接受返回值 //string connStr = System.Configuration.ConfigurationManager.AppSettings["ConStr"].ToString(); //using (SqlConnection conn = new SqlConnection(connStr)) //{ // conn.Open(); // SqlCommand cmd = new SqlCommand("AddOrderTran", conn); // cmd.CommandType = CommandType.StoredProcedure; // SqlParameter para1 = new SqlParameter("@country", country); // para1.Direction = ParameterDirection.Input; //參數方向 爲輸入參數 // cmd.Parameters.Add(para1); // SqlParameter para2 = new SqlParameter("@adds", adds); // para2.Direction = ParameterDirection.Input; // cmd.Parameters.Add(para2); // SqlParameter para3 = new SqlParameter("@ynames", ynames); // para3.Direction = ParameterDirection.Input; // cmd.Parameters.Add(para3); // SqlParameter para4 = new SqlParameter("@pids", pids); // para4.Direction = ParameterDirection.Input; // cmd.Parameters.Add(para4); // SqlParameter para5 = new SqlParameter("@cellp", cellp); // para5.Direction = ParameterDirection.Input; // cmd.Parameters.Add(para5); // SqlParameter para6 = new SqlParameter("@cphone", cphone); // para6.Direction = ParameterDirection.Input; // cmd.Parameters.Add(para6); // SqlParameter para7 = new SqlParameter("@amounts", amounts); // para7.Direction = ParameterDirection.Input; // cmd.Parameters.Add(para7); // SqlParameter para8 = new SqlParameter("@cartnumber", cartnumber); // para8.Direction = ParameterDirection.Input; // cmd.Parameters.Add(para8); // SqlParameter paraReturn = new SqlParameter("@return", SqlDbType.Int); // paraReturn.Direction = ParameterDirection.ReturnValue; //參數方向 爲返回參數 // cmd.Parameters.Add(paraReturn); // cmd.ExecuteNonQuery(); // object obj = paraReturn; // if (obj.ToString() == "0") // { // //存儲過程執行失敗 // } // else // { // //成功 // } //} //#endregion 本文的數據庫用的是sql server自帶數據Northwind 1.只返回單一記錄集的存儲過程 SqlConnection sqlconn = new SqlConnection(conn); SqlCommand cmd = new SqlCommand(); // 設置sql鏈接 cmd.Connection = sqlconn; // 若是執行語句 cmd.CommandText = "Categoriestest1"; // 指定執行語句爲存儲過程 cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter dp = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); // 填充dataset dp.Fill(ds); // 如下是顯示效果 GridView1.DataSource = ds; GridView1.DataBind(); 存儲過程Categoriestest1 CREATE PROCEDURE Categoriestest1 AS select * from Categories GO 2. 沒有輸入輸出的存儲過程 SqlConnection sqlconn = new SqlConnection(conn); SqlCommand cmd = new SqlCommand(); cmd.Connection = sqlconn; cmd.CommandText = "Categoriestest2"; cmd.CommandType = CommandType.StoredProcedure; sqlconn.Open(); // 執行並顯示影響行數 Label1.Text = cmd.ExecuteNonQuery().ToString(); sqlconn.Close(); 存儲過程Categoriestest2 CREATE PROCEDURE Categoriestest2 AS insert into dbo.Categories (CategoryName,[Description],[Picture]) values ('test1','test1',null) GO 3. 有返回值的存儲過程 SqlConnection sqlconn = new SqlConnection(conn); SqlCommand cmd = new SqlCommand(); cmd.Connection = sqlconn; cmd.CommandText = "Categoriestest3"; cmd.CommandType = CommandType.StoredProcedure; // 建立參數 IDataParameter[] parameters = { new SqlParameter("rval", SqlDbType.Int,4) }; // 將參數類型設置爲 返回值類型 parameters[0].Direction = ParameterDirection.ReturnValue; // 添加參數 cmd.Parameters.Add(parameters[0]); sqlconn.Open(); // 執行存儲過程並返回影響的行數 Label1.Text = cmd.ExecuteNonQuery().ToString(); sqlconn.Close(); // 顯示影響的行數和返回值 Label1.Text += "-" + parameters[0].Value.ToString() ; 存儲過程Categoriestest3 CREATE PROCEDURE Categoriestest3 AS insert into dbo.Categories (CategoryName,[Description],[Picture]) values ('test1','test1',null) return @@rowcount GO 4. 有輸入參數和輸出參數的存儲過程 SqlConnection sqlconn = new SqlConnection(conn); SqlCommand cmd = new SqlCommand(); cmd.Connection = sqlconn; cmd.CommandText = "Categoriestest4"; cmd.CommandType = CommandType.StoredProcedure; // 建立參數 IDataParameter[] parameters = { new SqlParameter("@Id", SqlDbType.Int,4) , new SqlParameter("@CategoryName", SqlDbType.NVarChar,15) , }; // 設置參數類型 parameters[0].Direction = ParameterDirection.Output; // 設置爲輸出參數 parameters[1].Value = "testCategoryName"; // 添加參數 cmd.Parameters.Add(parameters[0]); cmd.Parameters.Add(parameters[1]); sqlconn.Open(); // 執行存儲過程並返回影響的行數 Label1.Text = cmd.ExecuteNonQuery().ToString(); sqlconn.Close(); // 顯示影響的行數和輸出參數 Label1.Text += "-" + parameters[0].Value.ToString() ; 存儲過程Categoriestest4 CREATE PROCEDURE Categoriestest4 @id int output, @CategoryName nvarchar(15) AS insert into dbo.Categories (CategoryName,[Description],[Picture]) values (@CategoryName,'test1',null) set @id = @@IDENTITY GO 5. 同時具備返回值、輸入參數、輸出參數的存儲過程 SqlConnection sqlconn = new SqlConnection(conn); SqlCommand cmd = new SqlCommand(); cmd.Connection = sqlconn; cmd.CommandText = "Categoriestest5"; cmd.CommandType = CommandType.StoredProcedure; // 建立參數 IDataParameter[] parameters = { new SqlParameter("@Id", SqlDbType.Int,4) , new SqlParameter("@CategoryName", SqlDbType.NVarChar,15) , new SqlParameter("rval", SqlDbType.Int,4) }; // 設置參數類型 parameters[0].Direction = ParameterDirection.Output; // 設置爲輸出參數 parameters[1].Value = "testCategoryName"; // 給輸入參數賦值 parameters[2].Direction = ParameterDirection.ReturnValue; // 設置爲返回值 // 添加參數 cmd.Parameters.Add(parameters[0]); cmd.Parameters.Add(parameters[1]); cmd.Parameters.Add(parameters[2]); sqlconn.Open(); // 執行存儲過程並返回影響的行數 Label1.Text = cmd.ExecuteNonQuery().ToString(); sqlconn.Close(); // 顯示影響的行數,輸出參數和返回值 Label1.Text += "-" + parameters[0].Value.ToString() + "-" + parameters[2].Value.ToString(); 存儲過程Categoriestest5 CREATE PROCEDURE Categoriestest5 @id int output, @CategoryName nvarchar(15) AS insert into dbo.Categories (CategoryName,[Description],[Picture]) values (@CategoryName,'test1',null) set @id = @@IDENTITY return @@rowcount GO 6. 同時返回參數和記錄集的存儲過程 SqlConnection sqlconn = new SqlConnection(conn); SqlCommand cmd = new SqlCommand(); cmd.Connection = sqlconn; cmd.CommandText = "Categoriestest6"; cmd.CommandType = CommandType.StoredProcedure; // 建立參數 IDataParameter[] parameters = { new SqlParameter("@Id", SqlDbType.Int,4) , new SqlParameter("@CategoryName", SqlDbType.NVarChar,15) , new SqlParameter("rval", SqlDbType.Int,4) // 返回值 }; // 設置參數類型 parameters[0].Direction = ParameterDirection.Output; // 設置爲輸出參數 parameters[1].Value = "testCategoryName"; // 給輸入參數賦值 parameters[2].Direction = ParameterDirection.ReturnValue; // 設置爲返回值 // 添加參數 cmd.Parameters.Add(parameters[0]); cmd.Parameters.Add(parameters[1]); cmd.Parameters.Add(parameters[2]); SqlDataAdapter dp = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); // 填充dataset dp.Fill(ds); // 顯示結果集 GridView1.DataSource = ds.Tables[0]; GridView1.DataBind(); Label1.Text = ""; // 顯示輸出參數和返回值 Label1.Text += parameters[0].Value.ToString() + "-" + parameters[2].Value.ToString(); 存儲過程Categoriestest6 CREATE PROCEDURE Categoriestest6 @id int output, @CategoryName nvarchar(15) AS insert into dbo.Categories (CategoryName,[Description],[Picture]) values (@CategoryName,'test1',null) set @id = @@IDENTITY select * from Categories return @@rowcount GO 7. 返回多個記錄集的存儲過程 SqlConnection sqlconn = new SqlConnection(conn); SqlCommand cmd = new SqlCommand(); cmd.Connection = sqlconn; cmd.CommandText = "Categoriestest7"; cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter dp = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); // 填充dataset dp.Fill(ds); // 顯示結果集1 GridView1.DataSource = ds.Tables[0]; GridView1.DataBind(); // 顯示結果集2 GridView2.DataSource = ds.Tables[1]; GridView2.DataBind(); 存儲過程Categoriestest7 CREATE PROCEDURE Categoriestest7 AS select * from Categories select * from Categories GO