通过存储过程插入记录之后如何获得新纪录的id(自动增长)

coverallwangp coverallwangp 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
比如,记录中有四个字段,其中gi_id是自动增长的

CREATE PROCEDURE pro_addgoods
@u_name nvarchar(50),
@gi_click int,
@gi_title nvarchar(50)
As
insert into t_goods_info(u_name,gi_click,gi_title) values(@u_name,@gi_click,@gi_title)

我想获得添加成功后的gi_id,是否可以在上述存储过程中加一个输出参数,输出gi_id?
该如何添加这个输出参数?同时添加后如何赋值,如何在后台代码中执行存储过程的时候获得该参数?

下面是执行存储过程的代码:

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ershouConnectionString"].ToString());
//声明执行存储过程的SqlCommand
SqlCommand scd_sel = new SqlCommand("pro_addgoods", conn);
scd_sel.CommandType = CommandType.StoredProcedure;
//给存储过程的参数赋值
SqlParameter spa;
spa = scd_sel.Parameters.Add("@u_name", SqlDbType.NVarChar, 50);
spa.Direction = ParameterDirection.Input;
spa.Value = Session["account"].ToString();
spa = scd_sel.Parameters.Add("@gi_click", SqlDbType.Int, 4);
spa.Direction = ParameterDirection.Input;
spa.Value = 0;
spa = scd_sel.Parameters.Add("@gi_title", SqlDbType.NVarChar, 50);
spa.Direction = ParameterDirection.Input;
spa.Value = txttitle.Text;
//执行存储过程
if (conn.State == ConnectionState.Closed)
conn.Open();
try
{
scd_sel.ExecuteNonQuery();
scd_sel.Dispose(); //释放资源
}
catch (SqlException ae)
{
throw (ae);
}
conn.Dispose();
...全文

相关推荐

评论 9
收藏 已收藏
分享
返回顶部
coverallwangp
.NET社区 62,273 成员 668,968 内容