简体   繁体   English

检索SQL Server表的最后一条记录

[英]Retrieve last record of SQL Server table

Here is the my problem: I have a SQL Server database called emp . 这是我的问题:我有一个名为emp的SQL Server数据库。 It has an employee table (with userid int column). 它有一个employee表(带有userid int列)。 I need to retrieve the last record of the userid in employee table with increment userid value + 1. At the moment I did it on the my GUI. 我需要使用递增的userid值+ 1来检索employee表中userid的最后一条记录。此时我在我的GUI上执行了此操作。 So how do I write a sql query for it? 那么我该如何为它编写一个sql查询呢?

To return the the record with the highest userid, you can do: 要返回具有最高用户标识的记录,您可以执行以下操作:

SELECT TOP 1 userid
FROM employee
ORDER BY userid DESC

or... 要么...

SELECT MAX(userid)
FROM employee

If your plan is to then increment the userid manually and insert a new record with that new ID, I'd recommend against doing that - what if 2 processes try to do it at the same time? 如果您的计划是手动增加用户ID并插入带有该新ID的新记录,我建议不要这样做 - 如果2个进程同时尝试这样做会怎么样? Instead, use an IDENTITY column as userid and let the incrementing be handled for you automatically 而是使用IDENTITY列作为用户ID,并自动为您处理递增

You shouldn't be manually incrementing the userid column, use an IDENTITY column instead. 您不应手动增加userid列,而是使用IDENTITY列。 That will automatically add 1 for you for every new row. 这将为每个新行自动添加1。

CREATE TABLE Employees (
    UserId INT IDENTITY PRIMARY KEY NOT NULL,
    UserName NVARCHAR(255) NOT NULL,
    // etc add other columns here
)

If you really really have to select the highest userid it is a very simple query: 如果你真的必须选择最高的用户ID,那么这是一个非常简单的查询:

SELECT MAX(UserId) + 1
FROM Employees

[Edit] [编辑]

Based on your comments, you should use the SELECT MAX(UserId) + 1 FROM Employees query. 根据您的注释,您应该使用SELECT MAX(UserId) + 1 FROM Employees查询。 But be aware that this does not guarantee the number will be the ID. 但请注意,这并不能保证数字将是ID。 Normally you would not show an Id value until after the record has been saved to the database. 通常,在将记录保存到数据库之前,您不会显示Id值。

This will give you last inserted record, If you don't have Identity column. 这将为您提供最后插入的记录,如果您没有Identity列。

EXECUTE ('DECLARE GETLAST CURSOR DYNAMIC FOR SELECT * FROM [User]')
OPEN GETLAST
FETCH LAST FROM GETLAST
CLOSE GETLAST
DEALLOCATE GETLAST

If you have set identity than you can use following. 如果您设置了身份,则可以使用以下内容。

SELECT top(1) ID from [YourTable] order by ID desc

To have the new userid before saving, create a NextId table. 要在保存之前拥有新的用户标识,请创建一个NextId表。

Before inserting the user, get the new value from NextId: 在插入用户之前,从NextId获取新值:

UserId = SELECT Coalesce(NextId, 0) + 1 from NextId

Then update the NextID table: 然后更新NextID表:

UPDATE NEXTID SET NextId = IserID

And then use that value in your user creation code 然后在您的用户创建代码中使用该值

You can get gaps, there are more complicated methods to avoid them; 你可以得到差距,有更复杂的方法来避免它们; but I think this will do 但我认为这样做

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM