I think your whole procedure can be replaced by a single UPDATE
:
UPDATE Holidays
SET Status = CASE
WHEN @JobRole = 1003 and Status = 'Pending' THEN 'ManagerAcc'
WHEN @JobRole = 1003 and Status = 'AdminAcc' THEN 'Accepted'
WHEN @JobRole = 1002 and Status = 'Pending' THEN 'AdminAcc'
WHEN @JobRole = 1002 and Status = 'ManagerAcc' THEN 'Accepted'
ELSE Status END
WHERE @HolidayID = Holidays.ID
If you're wanting to have @Status
available to your callers, the parameter would need to be declared as OUTPUT
which it currently isn't, so I won't do the extension that actually sets the @Status
variable since it seems unnecessary.
In general, you should find ways in SQL to tell the system what to do, not how to do it. You shouldn't think, okay, first I'll extract the current status. Then, based on the current status and the job role, I'll apply a specific update. Tell the system what the specific conditions are and let it work out what order to do things in.
You should also be very careful whenever you specify a varchar(n)
variable or column, because:
When n is not specified in a data definition or variable declaration statement, the default length is 1.
You rarely, if ever, actually want a varchar(1)
variable.
When n is not specified when using the
CAST
andCONVERT
functions, the default length is 30
This is a slightly more useful data type, but is annoying just because there doesn't seem a good reason to have different defaults for n
in different contexts.