Jesse Christmann Jesse Christmann - 5 months ago 17
SQL Question

Input to determine how many datasets to pull from

Hopefully this will make sense:

Basically I want the user to input a variable at the start to determine how many datasets they want to compare:

DECLARE @NumberOfRuns INT
SET @NumberOfRuns = (1,2,3.. normally just 2)


After this I will have a query on multiple datasets:

SELECT*
FROM (Dataset 1)
UNION ALL
SELECT*
FROM (Dataset 2)


Is there a way that if the input for
@NumberOfRuns = 1
it only runs the first part, and if the input was 2 it would run both?

Answer

Which rdbms? sql-server, mysql oracle? etc. For the non-dynamic route one other method is to use temp table

CREATE TABLE #TempTable (
    --Columns And DataTypes of Select Statements
)

INSERT INTO #TempTable (columns)
SELECT *
FROM
    Dataset 1

IF @NumberOfRuns >= 2
INSERT INTO #TempTable (columns)
SELECT *
FROM
    Dataset 2

IF @NumberOfRuns >= 3
INSERT INTO #TempTable (columns)
SELECT *
FROM
    Dataset 3

SELECT *
FROM
    #TempTable