user1108948
user1108948

Reputation:

Get the last 100 inserted records in sql server

I want to retrieve the last 100 inserted records in sql server 2008.

Please correct my code. Pkey in the table testContext.testDetailRecords is an identity column.

var pkeys = (from tests in testContext.testDetailRecords
                         where tests.Pkey > (select max(tests.Pkey)-100 from testContext.testDetailRecords))
                                select tests.Pkey).ToList();

Upvotes: 3

Views: 983

Answers (3)

Jamiec
Jamiec

Reputation: 136239

How about

var pkeys = testContext.testDetailRecords
                 .OrderByDescending(x => x.PKey)
                 .Take(100)
                 .Select(x => x.PKey);

This should roughly translate to SQL

SELECT TOP 100 PKey
FROM testDetailRecords
ORDER BY PKey DESC

Upvotes: 5

Danilo Vulović
Danilo Vulović

Reputation: 3063

var pkeys = (from tests in testContext.testDetailRecords
             orderby tests.Pkey descending
             select tests.Pkey).Take(100).ToList();

Upvotes: 2

J0HN
J0HN

Reputation: 26961

var result = testContext.testDetailRecords.OrderByDescending(tests.Pkey).Take(100).Select(...);

Upvotes: 0

Related Questions