PROCEDURE GetTopResults
CREATE PROCEDURE GetTopOrBottomResults
@N INT, -- Accepts number of top/bottom results
@OrderType VARCHAR(10) -- Accepts 'Top', 'Bottom', or 'All'
AS
BEGIN
SET NOCOUNT ON;
-- Determine the number of rows in the table if 'All' is specified
DECLARE @TotalRows INT;
SET @TotalRows = (SELECT COUNT(*) FROM YourTable);
-- Handle the 'All' case by setting @N to the total number of rows
IF @OrderType = 'All'
BEGIN
SET @N = @TotalRows;
END
-- Determine the query to execute based on the @OrderType parameter
IF @OrderType = 'Top' OR @OrderType = 'All'
BEGIN
-- Select top N results ordered by SomeColumn
SELECT TOP (@N) *
FROM YourTable
ORDER BY SomeColumn; -- Adjust the ordering column as needed
END
ELSE IF @OrderType = 'Bottom'
BEGIN
-- Select bottom N results ordered by SomeColumn in descending order
;WITH CTE AS (
SELECT *, ROW_NUMBER() OVER (ORDER BY SomeColumn DESC) AS RowNum
FROM YourTable
)
SELECT *
FROM CTE
WHERE RowNum <= @N
ORDER BY SomeColumn; -- Adjust the ordering column as needed
END
ELSE
BEGIN
-- If invalid @OrderType is provided, return an error message
RAISERROR('Invalid OrderType. Please specify "Top", "Bottom", or "All".', 16, 1);
END
END;
Comments
Post a Comment