//  home   //  advanced search   //  news   //  categories   //  sql build chart   //  downloads   //  statistics
 ASP FAQ 
Home
ASP FAQ Tutorials

   8000XXXX Errors
   ASP.NET 2.0
   Classic ASP 1.0
   Databases
      Access DB & ADO
      General SQL Server & Access Articles
      MySQL
      Other Articles
      Schema Tutorials
      Sql Server 2000
      Sql Server 2005
   General Concepts
   Search Engine Optimization (SEO)

Contact Us
Site Map

Search

Web
aspfaq.com
tutorials.aspfaq.com
sqlserver2000.databases.aspfaq.com

ASP FAQ Tutorials :: Databases :: Sql Server 2000 :: Can SQL Server tell me which row was inserted most recently?


Can SQL Server tell me which row was inserted most recently?

Often, people ask, "how do I get the last row out of a table?" Let me be absolutely clear that I am not talking about people who are inserting a row and then want to know what the ID number is—there's already an article for that (Article #2174). What I'm walking about here is people who are monitoring a system, and want details about the newest row in a table (not just the id number, and not related to any specific or recent interaction they had with the system). 
 
The main comprehension problem here is that SQL Server doesn't know what row was inserted last; you need to track that information yourself. Unlike Access and other file-based database platforms, a table in SQL Server is essentially an unordered heap. You can not assume that the last row inserted will be at the "end" of the table, mainly because tables in SQL Server don't have an "end." You need to tell SQL Server what you mean by "last" (using TOP with an ORDER BY, or aggregate functions like MAX) — which might require a change to your existing schema. 
 

Using the IDENTITY 
 
A built-in way to identify the last row is to use an IDENTITY column; for example: 
 
CREATE TABLE dbo.tracking0 

    userID INT IDENTITY(1,1) 
        PRIMARY KEY CLUSTERED, 
    username VARCHAR(32) 

GO
 
Then, to get the "last" row: 
 
SELECT userID, username 
    FROM dbo.tracking0 
    WHERE userID = 
    ( 
        SELECT MAX(userid) 
        FROM dbo.tracking0 
    )
 
You can also use: 
 
SELECT TOP 1 userID, username 
    FROM dbo.tracking0 
    ORDER BY UserID DESC
 
One problem with this approach is that you don't have any indication of *when* the last row was inserted. Also, it ties you to an incrementing surrogate key, which may not be desirable (especially in distributed systems). 
 

Storing the INSERT date/time 
 
Another simple way to track order of insert is to have a DATETIME or SMALLDATETIME column, with a default value of GETDATE() or CURRENT_TIMESTAMP. 
 
SET NOCOUNT ON 
 
CREATE TABLE dbo.tracking1 

    username VARCHAR(32) PRIMARY KEY, 
    dt DATETIME DEFAULT GETDATE() 

GO 
 
INSERT dbo.tracking1(username) VALUES('a') 
INSERT dbo.tracking1(username) VALUES('b') 
 
-- wait for two seconds 
WAITFOR DELAY '00:00:02' 
 
INSERT dbo.tracking1(username) VALUES('c') 
INSERT dbo.tracking1(username) VALUES('d')
 
Now, to get the "last" row: 
 
SELECT TOP 1 
    username, dt 
    FROM dbo.tracking1 
    ORDER BY dt DESC
 
And if you expect ties, and want to show all matches: 
 
SELECT TOP 1 WITH TIES 
    username, dt 
    FROM dbo.tracking1 
    ORDER BY dt DESC
 

Tracking Updates 
 
It is a little trickier to track updates. If you can control data manipulation so that stored procedures are always used, and never ad-hoc UPDATE statements, then you can simply include a "date updated" column as part of the update statement. For example: 
 
CREATE TABLE dbo.tracking2 

    userid INT IDENTITY(1,1)  
        PRIMARY KEY CLUSTERED, 
    username VARCHAR(32), 
    dtAdded DATETIME DEFAULT GETDATE(), 
    dtUpdated DATETIME DEFAULT GETDATE() 
 
    -- you might want to make this NULL 
    -- as a flag that the row has been 
    -- inserted but never updated 

GO
 
CREATE PROCEDURE dbo.insertTracking2 
    @username VARCHAR(32) 
AS 
BEGIN 
    SET NOCOUNT ON 
    INSERT dbo.tracking2(username) 
        VALUES(@username) 
END 
GO
 
CREATE PROCEDURE dbo.updateTracking2 
    @userID INT, 
    @username VARCHAR(32) 
AS 
BEGIN 
    UPDATE dbo.tracking2 
        SET username = @username, 
        dtUpdated = GETDATE() 
        WHERE userid = @userID 
END 
GO
 
Now, let's throw some data in there, wait one second, and then update one of the rows: 
 
EXEC dbo.insertTracking2 'aaron' 
EXEC dbo.insertTracking2 'macgyver' 
 
WAITFOR DELAY '00:00:01' 
 
EXEC dbo.updateTracking2 1, 'aaronb'
 
And you can see how the rows come back when you ORDER BY dtUpdated DESC: 
 
SELECT username, dtAdded, dtUpdated 
    FROM dbo.tracking2 
    ORDER BY dtUpdated DESC
 
If you cannot control data manipulation through stored procedures, you might have to use a trigger in order to capture ad hoc updates. Here is how the trigger would look: 
 
CREATE TRIGGER dbo.trUpdateTracking2 
    ON dbo.tracking2 
    FOR UPDATE 
AS 
    -- to prevent recursion 
    IF NOT UPDATE(dtUpdated) 
 
        UPDATE dbo.tracking2 
            SET dtUpdated = GETDATE() 
            -- convenient, self-join and 
            -- against the inserted table 
            FROM dbo.tracking2 t2 
            INNER JOIN inserted i 
            ON t2.userid = i.userid 
GO
 
Same as above; run an update against one of the rows, and then run another select, and you will see the dtUpdated date has changed. 
 
You might want to add logic to verify that at least one of the columns has actually *changed* before changing the updated date; this depends on whether you are trying to track activity on your database, or actual deltas in your data. 
 

More Information 
 
For more advanced methods of auditing SQL Server data changes, see Article #2448.

Related Articles

Are there tools available for auditing changes to SQL Server data?
Can I create an index on a BIT column?
Can I have optional parameters to my stored procedures?
Can I implement an input mask in SQL Server?
Can I make SQL Server format dates and times for me?
Can I start IDENTITY values at a new seed?
How can I learn more about undocumented SQL Server stored procedures?
How can I make my SQL queries case sensitive?
How do I audit changes to SQL Server data?
How do I connect to a non-default instance of SQL Server?
How do I connect to SQL Server on a port other than 1433?
How do I create a cross-tab (or "pivot") query?
How do I determine if a table exists in a SQL Server database?
How do I drop a SQL Server database?
How do I find all the available SQL Servers on my network?
How do I get a list of SQL Server tables and their row counts?
How do I get rid of Named Pipes / DBNMPNTW errors?
How do I get the correct date/time from the msdb.sysjob* tables?
How do I get the nth row in a SQL Server table?
How do I get the result of dynamic SQL into a variable?
How do I handle REPLACE() within an NTEXT column in SQL Server?
How do I hide system tables in SQL Server's Enterprise Manager?
How do I know which version of SQL Server I'm running?
How do I limit the number of rows returned in my resultset?
How do I load text or csv file data into SQL Server?
How do I manage changes in SQL Server objects?
How do I monitor SQL Server performance?
How do I prevent linked server errors?
How do I reclaim space in SQL Server?
How do I recover data from SQL Server's log files?
How do I search for special characters (e.g. %) in SQL Server?
How do I start SQL Server Agent from ASP?
How do I time my T-SQL code?
How do I upsize from Access to SQL Server?
How do I upsize my MSDE database to full-blown SQL Server 2000?
How do I use a variable in a TOP clause in SQL Server?
How do I use GETDATE() within a User-Defined Function (UDF)?
How should I store an IP address in SQL Server?
Schema: How do I find all the foreign keys in a database?
SQL Server & MSDE
What are reserved Access, ODBC and SQL Server keywords?
What are the capacities of Access, SQL Server, and MSDE?
What are the main differences between Access and SQL Server?
What do I need to know about SQL Server 2000 SP4?
Where else can I learn about SQL Server?
Where is SP4 for SQL Server 2000?
Why am I having problems with SQL Server 2000 SP3 / SP3a?
Why can't I install SQL Server on Windows Server 2003?
Why can't I install SQL Server on Windows XP?
Why can't I use LIKE '%datepart%' queries?
Why do I get "Login failed for user '\'."?
Why do I get 'object could not be found' or 'invalid object name'?
Why do I get errors about master..spt_values?
Why do I get script errors in Enterprise Manager's 'taskpad' view?
Why do I get SQLSetConnectAttr Failed errors?
Why do I have problems with views after altering the base table?
Why does EM crash when I get an error in a stored procedure?
Why does Enterprise Manager return 'Invalid cursor state'?
Why does my DELETE query not work?
Why does sp_spaceused return inaccurate values?
Why is Enterprise Manager slow at expanding my database list?
Why is my app slow after upgrading from SQL Server 7 to 2000?
Why is tempdb full, and how can I prevent this from happening?
Why should I consider using an auxiliary calendar table?
Why should I consider using an auxiliary numbers table?

 

 


Created: 12/2/2003 | Last Updated: 3/12/2005 | broken links | helpful | not helpful | statistics
© Copyright 2006, UBR, Inc. All Rights Reserved. (206)

 

Copyright 1999-2006, All rights reserved.
Finding content
Finding content.  An error has occured...