Re: SELECT TOP
From: David Gugick (davidg-nospam_at_imceda.com)
Date: 01/23/05
- Next message: Andrew J. Kelly: "Re: NOLOCK statement"
- Previous message: ann: "User-defined functions"
- In reply to: Elie Grouchko: "SELECT TOP"
- Next in thread: Anith Sen: "Re: SELECT TOP"
- Messages sorted by: [ date ] [ thread ]
Date: Sun, 23 Jan 2005 13:16:29 -0500
Elie Grouchko wrote:
> Hi All
>
> I am writing a stored procedure to retrieve the top n rows of a SELECT
> statement.
>
> I tried passing the number of rows as a variable (topcount in the
> example), but I get a syntax error:
>
> Am I missing something?
>
> Thanks in advance
>
> Elie Grouchko
>
> CREATE PROCEDURE Proc_SelectTopForumCommentsOrderByDate
> @topcount int,
> @twc_comment_subject int
> AS
> SELECT TOP @topcount * FROM [twt_comment] WHERE
> ([twc_comment_subject] = @twc_comment_subject)
> AND ([twc_comment_id] != @twc_comment_subject)
> AND ([twc_comment_state] = 2) ORDER BY [twc_comment_date] DESC
SET ROWCOUNT, as Jacco mentioned is one workaround since the TOP
statement does not allow variables in its current implementation. The
other option is to use dynamic SQL. SET ROWCOUNT does not work in all
cases.
For example, the following query does not respect the ROWCOUNT setting
on inner SELECT.
SET ROWCOUNT 100
Select DISTINCT * From (
SELECT a, b, c
From TableA
Where x = 3 )
You'll get only 100 rows in the final select, but the sample is on all
rows. To implement this you'll need to use TOP.
Select DISTINCT * From (
Select TOP 100 a, b, c
From TableA
Where x = 3)
Your example, however, should be fine.
Despite the fact that scope of the ROWCOUNT is only for the SP in
question, it's a good idea to set it back to 0 immediately after the
SELECT.
-- David Gugick Imceda Software www.imceda.com
- Next message: Andrew J. Kelly: "Re: NOLOCK statement"
- Previous message: ann: "User-defined functions"
- In reply to: Elie Grouchko: "SELECT TOP"
- Next in thread: Anith Sen: "Re: SELECT TOP"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|