IF/ELSE branching using temp table(s)

0

Please login or register to vote for this query.

(click on this box to dismiss)

Stack Overflow

Q&A for professional and enthusiast programmers

-- A simple example of using IF/ELSE branches in a SQL query
-- More info: https://docs.microsoft.com/en-us/sql/t-sql/language-elements/if-else-transact-sql

-- This variable determines which branch to use
-- Change between 0 and 1 to see the difference in the results
DECLARE @OrderByCreationDate BIT = 1

-- Get the data set I want to use as a source
SELECT TOP 100
    Id,
    DisplayName,
    Reputation,
    CreationDate
-- Save the results into a temporary table
INTO #TempUsers
FROM Users
ORDER BY Reputation DESC

-- Branch using IF/ELSE IF/ELSE as needed
IF @OrderByCreationDate = 1
    SELECT *
    FROM #TempUsers
    -- This clause is different between the 2 conditionals
    ORDER BY CreationDate DESC
ELSE
    SELECT *
    FROM #TempUsers
    ORDER BY Reputation DESC

Enter Parameters

Options:
Switch sites:
loading Hold tight while we fetch your results