1、存储过程中不使用外部参数。
存储过程:
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: HF_Ultrastrong -- Create date: 2015年7月19日22:09:24 -- Description: 判断是否有数据,并使用Return返回值 -- ============================================= CREATE PROCEDURE ReturnValue AS BEGIN if exists(select * from Tb_Category) return 100 else return -100 END
代码:
/// <summary> /// 点击显示参数 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Button1_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"].ToString()); SqlCommand cmd = new SqlCommand("ReturnValue", con); cmd.CommandType = CommandType.StoredProcedure; //声明参数接收存储过程返回值 SqlParameter returnValue = cmd.Parameters.Add("returnValue", SqlDbType.Int, 4); returnValue.Direction = ParameterDirection.ReturnValue; con.Open(); cmd.ExecuteNonQuery(); con.Close(); this.Label1.Text = Convert.ToString(returnValue.Value); }
最终效果:
2、存储过程中使用外部参数。
存储过程:
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: HF_Ultrastrong -- Create date: 2015年7月19日22:09:24 -- Description: 判断是否有数据,并使用Return返回值 -- ============================================= CREATE PROCEDURE ReturnValue @10 int, @20 int, @30 int AS BEGIN if exists(select * from Tb_Category) return 100 else return -100 END
代码:
/// <summary> /// 点击显示参数 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Button1_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"].ToString()); SqlCommand cmd = new SqlCommand("ReturnValue", con); cmd.CommandType = CommandType.StoredProcedure; //参数数组 SqlParameter[] para = new SqlParameter[] { new SqlParameter("@10", 10), new SqlParameter("@20", 20), new SqlParameter("@30", 30), new SqlParameter("@Return", SqlDbType.Int) }; cmd.Parameters.AddRange(para); para[para.Length - 1].Direction = ParameterDirection.ReturnValue; con.Open(); cmd.ExecuteNonQuery(); con.Close(); object obj = para[para.Length - 1].Value; this.Label1.Text = Convert.ToString(obj); }
最终效果:
详细讲解:http://www.cnblogs.com/zhangweijia/archive/2013/02/04/2892054.html
时间: 2024-12-23 19:41:41