Home > Back-end >  UNION Results from same SQL each with Different Parameter values
UNION Results from same SQL each with Different Parameter values

Time:09-23

I have SQL that pulls data for a given timeframe. I want to run the SQL multiple times and merge/union the results together into one result set. Currently I copy the SQL and change the date ranges. As an example:

SELECT '2022' AS Period, Name, Status, Wage
  FROM Wages_Table
  WHERE YEAR(Wage_Date) = 2022
UNION
SELECT '2021' AS Period, Name, Status, Wage
  FROM Wages_Table
  WHERE YEAR(Wage_Date) = 2021
UNION
SELECT '2020' AS Period, Name, Status, Wage
  FROM Wages_Table
  WHERE YEAR(Wage_Date) = 2020;

Since I need to repeat this for multiple years, I would like to make the year a parameter and execute the SQL repeatedly for each of the years and have all the runs merged together into one results set.

CodePudding user response:

Why not do it as a single query? No need to UNION based on what you have shown.

DECLARE @StartYear int = 2020;

SELECT YEAR(Wage_Date) AS [Period], [Name], [Status], Wage
FROM Wages_Table
WHERE YEAR(Wage_Date) >= @StartYear
ORDER BY YEAR(Wage_Date) DESC;
  • Related