I have a query in a stored procedure that runs every week. The result set has a 4 columns for each month. (ie for July: JulInvTotal, JulRPct, JulSPct, JulCPct) So I've got these 48 columns in my table, plus CurrentMonth. I only want the stored procedure to update the 4 columns for a month, when it is that month.
For example, during May all columns in the result set of the query besides MayInvTotal, MayRPct, MaySPct, MayCPct will be zero. So I just want to update the may columns in my table. The next month, the query will return zeros everywhere but the June columns. I will want to update the June Columns, but not the May columns, so as to preserve last months data in the table.
Eventually, this table will hold monthly snapshots of what the inventory was at the end of each month that year.
Is there a way to use case statements with an update like I'm trying below?
CASE WHEN CurrentMonth=5 THEN
UPDATE MonthlyInventorySnapshot
SET
MayInvTotal = MayInvTotal
, MayRPct = MayRPct
, MaySPct = MaySPct
, MayCPct = MayCPct
CASE WHEN CurrentMonth=6 THEN
UPDATE MonthlyInventorySnapshot
SET
JunInvTotal = JunInvTotal
, JunRPct = JunRPct
, JunSPct = JunSPct
, JunCPct = JunCPct
Thank you very much for your time. Let me know if you need more information.
Use a if statement
instead of a case
IF CurrentMonth=5
UPDATE MonthlyInventorySnapshot
SET
MayInvTotal = MayInvTotal
, MayRPct = MayRPct
, MaySPct = MaySPct
, MayCPct = MayCPct
If CurrentMonth=6
UPDATE MonthlyInventorySnapshot
SET
JunInvTotal = JunInvTotal
, JunRPct = JunRPct
, JunSPct = JunSPct
, JunCPct = JunCPct
One option is to use the case
statement in each set statement:
update MonthlyInventorySnapshot
set MayInvTotal = case when @currentmonth = 5 then @MayInvTotal else MayInvTotal end,
MayRPct = case when @currentmonth = 5 then @MayRPct else MayRPct end,
...,
JunInvTotal = case when @currentmonth = 6 then @JunInvTotal else JunInvTotal end,
JunRPct = case when @currentmonth = 6 then @JunRPct else JunRPct end,
...
The idea here is to update the value to the passed in parameter if the current month is met, else update it to itself.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.