I’m using SQL Server 2008 R2 and I have a database which contains two tables.
T1 contains raw data, however only the column Cost, Date and AccId is interesting for me.
T2 contains a few columns like Jan, Feb, Mar, Apr, … and a column AccId
I need now a stored procedure which sets the values in the appropriate column in T2 whenever I update T1. It should sum up the Cost for every AccId in the given month. If I set @year = 2012 and @month = 3, so it should update the column Mar with the sum of Cost in T2 for every AccId, which is in T1 and T2.
I have now a stored procedure which would work for one constant column. I want now CASE which selects the column depending on the given month. Here is a stored procedure how I think it should work, but it doesn’t work:
CREATE PROCEDURE [dbo].[SP_Calc]
@year int,
@month int
AS
MERGE INTO T2
USING (
SELECT AccId, SUM(Cost) AS CostSum
FROM T1
WHERE YEAR(Date) = @year
AND MONTH(Date) = @month
GROUP BY AccId
) AS source
ON T2.AccID = source.AccId
WHEN MATCHED THEN
UPDATE SET
SELECT
CASE @month
WHEN 1 THEN Jan = source.Cost
WHEN 2 THEN Feb = source.Cost
WHEN 3 THEN Mar = source.Cost
WHEN 4 THEN Apr = source.Cost
WHEN 5 THEN Mai = source.Cost
WHEN 6 THEN Jun = source.Cost
WHEN 7 THEN Jul = source.Cost
WHEN 8 THEN Aug = source.Cost
WHEN 9 THEN Sep = source.Cost
WHEN 10 THEN Oct = source.Cost
WHEN 11 THEN Nov = source.Cost
WHEN 12 THEN Dez = source.Cost
ELSE RAISERROR ('Month is out of range', 18, 1);
END
You don’t have a Cost in your Source, just CostSum
Also you need to change your setting to