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;

SUBSTRING(rank_name, 1, CHARINDEX(' ', rank_name) - 1) AS FirstWord, SUBSTRING(rank_name, CHARINDEX(' ', rank_name) + 1, LEN(rank_name) - CHARINDEX(' ', rank_name)) AS SecondWord 

Comments

Popular posts from this blog

host

Steps to create SSH key from git bash

test