保存变量上次插入的ID [英] Save on variable last inserted ID

查看:84
本文介绍了保存变量上次插入的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我很感激那里有一些亮点...

所以我在数据库中插入了一些数据,比如姓名,电话等。这个表还有一个自动数字ID号每次插入都会增加,但我真的不知道如何从上次插入中获得完全ID,我打算将它存储在变量上。我正在考虑使用SELECT MAX(id)来获取它,但它看起来并不那么优雅,我也不知道如何将从SELECT返回的值存储到变量中。我很想知道这一点。非常感谢!

解决方案

你可以用两种方式做到这一点



1)选择< b> max(id)



 选择最大值(id)来自 tableName 订单  id  DESC  





2)使用@

  @@ IDENTITY  





插入查询后你必须返回< pre lang =SQL> @@ IDENTITY

返回最后一个colimn的插入ID



  插入 tableName ...... ... 

SET @ id = SCOPE_IDENTITY()
选择 @ id







您可以根据需要使用执行标量,数据表或数据集,datareader对其进行检索



欲了解更多信息.....



SCOPE_IDENTITY(Transact-SQL) [ ^ ]



identity-and-scope_identity-in-sql-server [ ^ ]


完整文章 - < a href =http://www.aspsnippets.com/Articles/Getting-ID-of-the-newly-inserted-record-in-SQL-Server-Database-using-ADO.Net.aspx>获取ID使用ADO.Net在SQL Server数据库中新插入的记录 [ ^ ]。

Hello, I would appreciate some light in there...
So I'm inserting some data in a database, such as name, phone etc. The table has also an autonumeric ID number that increases on every insert, but I don't really know how to get that exactly ID from the last insertion, I plan to store it on a variable. I was thinking of making a SELECT MAX(id) to get it, but it does not look much ellegant, also I don't know how I would store that value returned from the SELECT into a variable. I would love to know that aswell. Thanks so much beforehand!

解决方案

You can do it in two ways

1) By select max(id)

Select max(id) from tableName order by id DESC



2)By use of @

@@IDENTITY



After insert query you have to return

@@IDENTITY

Which returns last Inserted ID of a colimn

Insert into tableName.........

SET @id=SCOPE_IDENTITY()
select @id




You can retrive it using execute scalar, datatable or dataset, datareader as you wish

For more info.....

SCOPE_IDENTITY (Transact-SQL)[^]

identity-and-scope_identity-in-sql-server[^]


Complete article - Getting ID of the newly inserted record in SQL Server Database using ADO.Net[^].


这篇关于保存变量上次插入的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆