sql实现获取刚获得的插入ID

本文介绍了一种在SQL中插入新记录并返回该记录ID的方法。通过构建SQL语句并利用存储过程或特定函数,可以实现在插入数据后立即获取新生成记录的ID。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 类代码:

#region "增加表的记录"
        /// <summary>
        /// 增加一条数据
        /// </summary>
        public  int Insert(M_ProductType model,out int count)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("insert into ProductType(");
            strSql.Append("ParentID,boolid,QueryID,typename");
            strSql.Append(")");
            strSql.Append(" values (");
            strSql.Append("" + model.ParentID + ",");
            strSql.Append("" + model.BoolID + ",");
            strSql.Append("'" + model.QueryID + "',");
            strSql.Append("'" + model.Typename + "'");
            strSql.Append(")");
            strSql.Append(";select @@IDENTITY");
            int result = DBAction.Count(strSql.ToString(),out count);
            return result;
        }
        #endregion

红色那行是重点,还有就是参数里(蓝色那个)是用来接收刚插入值的ID。然后方法里的Count的方法是这样写的:

public static int Count(string sql,out int count)
        {
            SqlConnection cn = null;
            try
            {
                cn = new SqlConnection(con);
                cn.Open();
                SqlCommand cmd = new SqlCommand(sql, cn);
                object obj = cmd.ExecuteScalar();
                if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                {
                    count = 0;
                    return 0;
                }
                else
                {
                    int rows = Int32.Parse(obj.ToString());
                    count = rows;
                    return rows;
                }
            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                if (cn != null)
                {
                    cn.Close();
                    cn.Dispose();
                }
            }
        }

在页面上调用 的方法是:

int count;

int result = dal.Add(model,out count);

这个count就是刚插入值的ID号了,还有就是千万不要给count赋初值不然会报错,

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值