1、存储过程中不使用外部参数。
存储过程:
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: HF_Ultrastrong -- Create date: 2015年7月20日12:42:02 -- Description: 插入一条数据,并返回所得表示列(自动增加的字段) -- ============================================= Alter PROCEDURE GetIdentityvalue @ID int output AS BEGIN insert into tb_Admin ([Admin],[Password]) values ('admin_2', 123456) select @ID = @@IDENTITY END GO
代码:
/// <summary> /// 点击显示数据 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Button1_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection("server=HUANGFU-PC;database=db_NetShop;integrated security = true;"); SqlCommand cmd = new SqlCommand("GetIdentityvalue", con); cmd.CommandType = CommandType.StoredProcedure; //添加参数 //使用OutPut参数,返回新纪录的ID(ID:子增长字段) SqlParameter ID = cmd.Parameters.Add("@ID", SqlDbType.Int, 8); ID.Direction = ParameterDirection.Output; con.Open(); cmd.ExecuteNonQuery(); con.Close(); this.Label1.Text = Convert.ToString(ID.Value); }
*在插入这一条记录之前,前面的子增长字段是16,所以执行新的插入,这一条记录的子增长ID是17.
最终效果:
1、存储过程中不使用外部参数。
存储过程:
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: HF_Ultrastrong -- Create date: 2015年7月20日12:42:02 -- Description: 插入一条数据,并返回所得表示列(自动增加的字段) -- ============================================= Alter PROCEDURE GetIdentityvalue @AdminName varchar(20), @PassWord varchar(20), @ID int output AS BEGIN insert into tb_Admin ([Admin],[Password]) values (@AdminName, @PassWord) select @ID = @@IDENTITY END GO
代码:
/// <summary> /// 点击显示数据 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Button1_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection("server=HUANGFU-PC;database=db_NetShop;integrated security = true;"); SqlCommand cmd = new SqlCommand("GetIdentityvalue", con); cmd.CommandType = CommandType.StoredProcedure; //添加参数 //使用OutPut参数,返回新纪录的ID(ID:子增长字段) SqlParameter[] para = new SqlParameter[] { new SqlParameter("@AdminName", "admin_2"), new SqlParameter("@PassWord", 123456), new SqlParameter("@ID", SqlDbType.Int, 8) }; cmd.Parameters.AddRange(para); para[para.Length - 1].Direction = ParameterDirection.Output; con.Open(); cmd.ExecuteNonQuery(); con.Close(); this.Label1.Text = Convert.ToString(para[para.Length - 1].Value); }
最终效果: