如何通过查询到变量从数据库中获取最后一个插入的id? [英] How do I get last inserted id from database through query to a variable?
本文介绍了如何通过查询到变量从数据库中获取最后一个插入的id?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试使用此代码将最大ID存储在maxid var中,但它没有在maxid中获取ID
我尝试过: < br $>
int maxId;
SqlCommand dataCommand = new SqlCommand(从Quant_Parent中选择最大值(Id),con);
con.Open();
maxId = Convert.ToInt32(dataCommand.ExecuteScalar());
con.Close();
i tried this code to store max id in maxid var but it didnt get id in maxid
What I have tried:
int maxId;
SqlCommand dataCommand = new SqlCommand("Select max(Id) from Quant_Parent", con);
con.Open();
maxId = Convert.ToInt32(dataCommand.ExecuteScalar());
con.Close();
推荐答案
不要使用MAX(ID):改用@@ IDENTITY - 它返回连接上产生的最后一个IDENTITY值。
Don;t use MAX(ID): use @@IDENTITY instead - it returns the last IDENTITY value produced on a connection.
SELECT @@IDENTITY
这意味着它返回您创建的最后一个值,而不是下一个桌面的人!
Which means it returns the last value you created, rather than the guy at the next desk!
这篇关于如何通过查询到变量从数据库中获取最后一个插入的id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文