同题。
比如create table tst
(
tID int primary key identity(1,1),
tstr varchar(40) not null
)insert into tst(tstr) values('测试')有这样一个tst表,tID字段为自增的,对于刚插入的记录,如何在asp.net中直接获得刚插入记录的ID值。。纠结

我有一种恶心的办法,也不太安全,勉强可以实现,就是select top 1 tID from tst where tstr='刚刚插入的记录' order by tID desc)
但是这种方法在很多人连接数据库操作的时候很有可能返回的ID是错误的,请介绍其他可行实用的方法~
谢谢!!

解决方案 »

  1.   

    insert into tst(tstr) values('测试') SELECT @@IDENTITY
      

  2.   

    cmd.CommandText = "INSERT INTO table (name) VALUES ('tes,)";
    cmd.ExecuteNonQuery();
    cmd.CommandText = "SELECT @@IDENTITY";
    int newId = (int)cmd.ExecuteScalar();
    通过存储过程参数获取output 值
    SCOPE_IDENTITY 返回为当前会话和当前作用域中的任何表最后生成的标识值。
      

  3.   

    mssql有个系统参数 返回最后更新影响的行ID @@IDENTITY 查询这个就好了
      

  4.   

    这种方法有一定的可行性,但是如果在web中多用户并发操作,返回的id可能是其他用户更新(操作)的数据记录ID,这种情况有办法避免吗?
      

  5.   

    下面的示例创建一个 SqlCommand,然后使用 ExecuteScalar 执行它。向该示例传递两个字符串,一个字符串表示要插入到表中的新值,另一个字符串用于连接至数据源。如果已插入新行,则此函数会返回新的“Identity”列值,如果失败,则返回 0。
    static public int AddProductCategory(string newName, string connString)
    {
        Int32 newProdID = 0;
        string sql =
            "INSERT INTO Production.ProductCategory (Name) VALUES (@Name); "
            + "SELECT CAST(scope_identity() AS int)";
        using (SqlConnection conn = new SqlConnection(connString))
        {
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.Parameters.Add("@Name", SqlDbType.VarChar);
            cmd.Parameters["@name"].Value = newName;
            try
            {
                conn.Open();
                newProdID = (Int32)cmd.ExecuteScalar();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        return (int)newProdID;
    }
      

  6.   

    其实最好还是用scope_identity(), 这里有个连接,说明了@@identity, scope_identity(), IDENT_CURRENT的异同:SCOPE_IDENTITY, IDENT_CURRENT, and @@IDENTITY 
      

  7.   

    因为只自增,所以最后插入进去的记录的ID值就应该是最大的啊,如果你要获取刚刚插入的直接找ID最大的那个就可以了吧。(不过这样做,单用户到还可以,如果并发大了,就不行了,可能你刚刚插入的已经不是最后插入的了)
      

  8.   

    最后加上:SELECT @ID = @@IDENTITY即可,插入数据建议最好使用存储过程