从数据库中选择最后一个值 [英] select the last value from the database

查看:100
本文介绍了从数据库中选择最后一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的所有人,



如何从sql数据库中选择最后一个值。



i有userId的表是主键,我想在文本框中显示最后一个值。

和下一个生成的主键(在当前表单中使用)显示在其他文本框中。

Dear All,

How to Select the last value from the sql database.

i have a table with customerId is a Primary key and i want last value show in a textbox.
and next generated primary key(Which is the use in current form) show in other textbox.

推荐答案

不要。甚至不要考虑它。

你不能显示下一个生成的主键,因为在多用户系统中(这是使用SQL的唯一原因)你不知道是什么下一个的价值将是:它取决于其他人正在做什么,以及他们做什么的顺序。想想看:如果你有两个用户都输入数据,那么他们都会看到下一个值 - 它将是相同的值。但是当他们尝试提交数据时,如果没有SQL正确地抛出错误,他们就不能使用相同的主键。您只有在使用后才会显示新值,或者至少分配一个新值(如果他们因任何原因无法完成操作,您将获得解除分配的乐趣)。



最后一个值也很难显示,除非对键有一些顺序,或者某个字段记录了分配它的日期和时间。然后,你所要做的就是

Don't. Don't even think about it.
You cannot show "the next generated primary key" because in a multi-user system (and that is the only reason to use SQL) you do not know what the "next" value will be: it depends on what everybody else is doing, and the order in which they do it. Think about it: if you have two users both entering data, then they both will see the "next" value - and it will be the same value. But when they try to submit the data, they can't both use the same primary key without SQL correctly throwing an error. You only ever show a new value after it is used, or allocated at the very least (and then you have the fun of deallocation if they don't complete the operation for whatever reason).

The "last value" is also difficult to show, unless there is some order to the keys, or some field which records the date and time at which it was allocated. Then, all you have to do is
SELECT TOP 1 customerID FROM MyTable ORDER BY ... DESC

并填写您的排序条件。如果你没有指定ORDER子句,那么SQL可以按照它认为合适的任何顺序返回行 - 它可以返回最后输入的行,但它不必:它可以高兴地每次以不同的顺序返回行运行相同的查询,如果它更有效。

And fill in your sort criteria. If you do not specify an ORDER clause, then SQL is at liberty to return rows in any order it sees fit - it may return the last entered, but it doesn't have to: it can happily return rows in a different order every time you run the same query, if that is more efficient for it.


您可以拥有Identity列并根据该列获取记录。

You can have Identity column and get the record based on that column.
SELECT TOP 1 Id FROM table ORDER BY Id DESC



SQL SERVER - @@ IDENTITY vs SCOPE_IDENTITY()与IDENT_CURRENT - 检索上次插入的记录标识 [ ^ ]


你可以使用这个



you can use this

Select isnull(max(customerID),0) from mytable


这篇关于从数据库中选择最后一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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