Retrieving the First N Records from a SQL Query

3 Techniques

1. Simple Fixed ‘N’

SELECT TOP 10 NewsURL, ArticleTitle, ArticleAuthor
FROM NewsStoriesTable
ORDER BY PublicationDate DESC

2. Dynamic ‘N’ Records

CREATE PROCEDURE getRecentArticles
(
@ResultCount int
)
AS

Declare @sSQL

Set @sSQL = “Select TOP ” + @ResultCount + ” NewsURL, ArticleTitle, ArticleAuthor
FROM NewsStoriesTable ORDER BY PublicationDate DESC”

sp_executesql @sSQL

3. Dynamic ‘N’ Records (My Preferred way)

CREATE PROCEDURE getRecentArticles
(
@ResultCount int
)
AS

SET ROWCOUNT @ResultCount — KEY LINE WHICH DOES THE MAGIC

SELECT NewsURL, ArticleTitle, ArticleAuthor
FROM NewsStoriesTable
ORDER BY PublicationDate DESC

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: