Simplifying repetitive SQL conditions with varying parameters

I’m working on a stored procedure that does a ton of calculations. There’s a part that repeats about 9 times with slight changes. It looks like this:

IF @param1 = 1
  SELECT COUNT(items) FROM myTable WHERE category = @type1

IF @param2 = 1
  SELECT COUNT(items) FROM myTable WHERE category = @type2

IF @param3 = 1
  SELECT COUNT(items) FROM myTable WHERE category = @type3

This goes on for a while. Is there a way to make a function or something where I can pass in a true/false flag and another argument? It should only give me the result if the flag is true. I’m trying to make my code less repetitive and easier to manage. Any ideas on how to streamline this?

yo, have u tried using a temp table? could be a cool way to handle this. like:

CREATE TABLE #Params (flag bit, type nvarchar(50))
INSERT INTO #Params VALUES (1, @type1), (1, @type2), ...
SELECT COUNT(t.items) FROM myTable t
JOIN #Params p ON t.category = p.type WHERE p.flag = 1

might make ur code cleaner n easier to manage. just a thought!

hey, have u thought about using a case statement? it could make things simpler. something like:

SELECT 
  SUM(CASE WHEN @param1 = 1 AND category = @type1 THEN 1 ELSE 0 END),
  SUM(CASE WHEN @param2 = 1 AND category = @type2 THEN 1 ELSE 0 END),
  ...
FROM myTable

what do you think? it might be more efficient than separate counts. curious to hear ur thoughts!

You can simplify this repetitive pattern using a table-valued function (TVF) in SQL Server. Here’s how you might approach it:

Create a TVF that takes a flag and category type as parameters. This function would return the count only if the flag is true, otherwise returning 0 or NULL.

Then, use this function in your stored procedure, calling it for each parameter-type pair. This approach significantly reduces code duplication and makes your procedure more maintainable.

For example:

CREATE FUNCTION dbo.GetItemCount (@flag BIT, @categoryType NVARCHAR(50))
RETURNS TABLE
AS
RETURN
(
    SELECT CASE WHEN @flag = 1 
           THEN (SELECT COUNT(items) FROM myTable WHERE category = @categoryType)
           ELSE 0 END AS ItemCount
)

-- In your stored procedure:
SELECT 
    (SELECT ItemCount FROM dbo.GetItemCount(@param1, @type1)) AS Count1,
    (SELECT ItemCount FROM dbo.GetItemCount(@param2, @type2)) AS Count2,
    -- ... and so on

This solution keeps your code DRY and easier to modify in the future.