建表 創建儲存過程 調用 調用具有輸出參數的存儲過程 創建儲存過程 調用儲存過程 摘取至—————— 春華秋實 如侵自刪 ...
建表
CREATE TABLE [tab_cJ] ( [id] [int] IDENTITY (1, 1) NOT NULL PRIMARY KEY, [name] [varchar] (50) , [age] [int] NULL , [info] [varchar] (200) )
創建儲存過程
CREATE PROCEDURE QueryInfoByName @name varchar(50), @age int AS select info from tab_cj where [name]=@name and age=@age GO
調用
using (SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=test;Integrated Security=True")) { SqlCommand cmd = conn.CreateCommand(); cmd.CommandType = CommandType.StoredProcedure; //指定執行存儲過程操作 cmd.CommandText = "QueryInfoByName"; //存儲過程名稱 //對應存儲過程QueryInfoByName的第一個參數@name SqlParameter parName = new SqlParameter("@name", SqlDbType.VarChar, 50); //指定參數@name要轉入的值 parName.Value = "aa"; //對應存儲過程QueryInfoByName的第二個參數@age SqlParameter parAge = new SqlParameter("@age", SqlDbType.Int); //指定參數@age要轉入的值 parAge.Value = 12; //這一步非常重要,一定將設置好的兩個參數類型添加到Command對象的參數集合里 cmd.Parameters.Add(parName); cmd.Parameters.Add(parAge); //方式一,查詢回來的結果需要顯示在DataGrid之類的控制項上 DataSet ds = new DataSet(); SqlDataAdapter adapter = new SqlDataAdapter(cmd); adapter.Fill(ds); //方式二,按單個值讀取 conn.Open(); SqlDataReader reader = cmd.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { Response.Write(reader.GetString(0)); } } }
調用具有輸出參數的存儲過程
創建儲存過程
create procedure getAge ( @name varchar(50), @age int output ) as select @age=age from tab_cJ where [name]=@name
調用儲存過程
using (SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=test;Integrated Security=True")) { SqlCommand cmd = conn.CreateCommand(); cmd.CommandType = CommandType.StoredProcedure; //指定執行存儲過程操作 cmd.CommandText = "getAge"; //存儲過程名稱 SqlParameter parName = new SqlParameter("@name", SqlDbType.VarChar, 50); parName.Value = "aa"; //對應存儲過程getAge的輸出參數@age SqlParameter parAge = new SqlParameter("@age", SqlDbType.Int); parAge.Direction = ParameterDirection.Output; cmd.Parameters.Add(parName); cmd.Parameters.Add(parAge); try { conn.Open(); cmd.ExecuteNonQuery(); int i = int.Parse(parAge.Value.ToString()); Response.Write(i.ToString()); conn.Close(); } catch(Exception ex) { Response.Write(ex.ToString()); } }
摘取至——————
春華秋實
如侵自刪