I am trying to create a stored procedure for assigning call in customers to callers. We have several teams of callers that are identified by a variable @team_id. What I want to do is check and see if the customer (@code) has someone assigned to them yet. If they do, return that person’s ID. If not, run the THEN statement that determines who it should be assigned to, update the record to that caller, and return that caller’s ID. Here is what I have, but it won’t let me run the update inside the select. I would like to avoid updating the table every time (adding an update clause to the end of the stored procedure) if I can.
declare @team_id char(3), @code char(4)
--If team is an intake department
if (@team_id IN ('03V', '09X'))
SELECT
CASE
WHEN a.intake_caller_id IS NOT NULL and a.intake_caller_id <> '' THEN a.intake_caller_id
ELSE
(
SELECT employee_id
FROM
(
SELECT TOP 1 COUNT(a.id) as count, a.employee_id
FROM event.dbo.event a
JOIN event.dbo.event_triage b ON a.employee_id = b.employee_id
WHERE task_id in ('WS', 'WF', 'WT', 'WU' ) and a.status = 1 AND b.team_id = @team_id
GROUP BY a.employee_id
ORDER BY count ASC
) a
update event.dbo.referral_data
SET intake_caller_id = a.employee_id
WHERE CODE_ = @code
)
END
FROM event.dbo.referral_data a
WHERE CODE_ = @code
ELSE
--if team is a PO department
IF (@team_id IN ('00R', '154'))
SELECT
CASE
WHEN @team_id = '00R' AND intake_rx_caller_id IS NOT NULL AND intake_rx_caller_id <> '' THEN intake_rx_caller_id
WHEN @team_id = '00R' AND (intake_rx_caller_id IS NULL OR intake_rx_caller_id = '') THEN
(
SELECT employee_id
FROM
(
SELECT top 1 COUNT(a.id) as count, a.employee_id
FROM event.dbo.event a
JOIN event.dbo.event_triage b ON a.employee_id = b.employee_id
WHERE task_id IN ('WR', 'CR') AND status = 1 and b.team_id = '00R'
GROUP BY a.employee_id
ORDER BY count ASC
) a
)
WHEN @team_id = '154' AND reorder_rx_caller_id IS NOT NULL AND reorder_rx_caller_id <> '' THEN reorder_rx_caller_id
WHEN @team_id = '154' AND (reorder_rx_caller_id IS NULL OR reorder_rx_caller_id = '') THEN
(
SELECT employee_id
FROM
(
SELECT top 1 COUNT(a.id) as count, a.employee_id
FROM event.dbo.event a
JOIN event.dbo.event_triage b ON a.employee_id = b.employee_id
WHERE task_id IN ('RS', 'RY') AND status = 1 and b.team_id = '154'
GROUP BY a.employee_id
ORDER BY count ASC
)a
)
END
FROM event.dbo.doctor_data
WHERE CODE_ = @code
Why dont you update first and then do a select inside first IF statement.
You can apply the same conditional logic in update statement.
Edit:here is the code.Not tested though….