-2

Is there anyway to store the result of a case statement in a variable so that it has a fixed result that i can return at any point.

e.g.

    CASE 
    WHEN MONTH([DATE]) = MONTH(getdate()) AND
    YEAR([DATE]) = YEAR(getdate())
    THEN SUM(Figure)
    OVER (PARTITION BY [Name], 
    MONTH([DATE])) 
    ELSE 0 
    END INTO @MTD

Ideally i want to be able to return a consisted month to date value where the calculation is not affected by where clauses

1
  • Since this will be different for every record in the select, it can't be stored as a scalar variable. What you could do is create a temp table that does the calc and join to that in the main select.
    – HLGEM
    Sep 14, 2017 at 14:25

3 Answers 3

1

If you use a variable to store the profit it will only be able to store one row, therefore you should add a where clause to select a specific [Name], [Month] and probably [Year] for which you want to retrieve the overall profit. You should add [Year] to your partition as well as to the WHERE clause unless you want to sum profits from the same month in different years.

The resulting code would be like this:

declare
    @val int = 0;

select     
    @val = CASE 
        WHEN MONTH([DATE]) = MONTH(getdate()) AND
        YEAR([DATE]) = YEAR(getdate())
        THEN SUM(PROFIT)
        OVER (PARTITION BY [Name], 
            MONTH([DATE]), YEAR([DATE])) 
        ELSE 0 
        END 
FROM table_name
WHERE [Name] = @Name AND
      MONTH([DATE]) = @Month AND
      YEAR([DATE]) = @Year

print @val
0

You can try like this:

declare
  @MTD varchar(100) = null;

select 
  @MTD = CASE 
    WHEN MONTH([DATE]) = MONTH(getdate()) AND
    YEAR([DATE]) = YEAR(getdate())
    THEN SUM(PROFIT)
    OVER (PARTITION BY [Name], 
    MONTH([DATE])) 
    ELSE 0 
    END
1
  • This is what i get - "Warning: Null value is eliminated by an aggregate or other SET operation." Sep 13, 2017 at 9:41
0

Try this:

declare
  @val int = 0;

select 
  @val = CASE 
    WHEN MONTH([DATE]) = MONTH(getdate()) AND
    YEAR([DATE]) = YEAR(getdate())
    THEN SUM(isnull(PROFIT,0))
    OVER (PARTITION BY [Name], 
    MONTH([DATE])) 
    ELSE 0 
    END
    from table_name

    print @val

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.