SQL Case Statement in set; Does it always work?
I was wondering if in the following statement:
UPDATE u
SET u.isactive =
(
CASE WHEN e.LVStatus<>'B' AND u.IsActive=1 AND u.AutoUpdate=1 THEN
0
WHEN e.LVStatus='B' AND u.IsActive=0 AND u.AutoUpdate=1 THEN
1 END
),
u.UpdatedB y= 0
FROM tbl_e e
INNER JOIN tbl_Users u ON e.id=u.id
If the conditions in the case statement are not met, for example, u.IsActive = 1 and e.LVStatus = 'B', will u.UpdatedBy = 0 still be asked? I was hoping that if the conditions in the case statement are not met, do nothing, perhaps if I need this behavior, I just need to separate the update statements with different clauses. Thank!
source to share
Since your query sets u.UpdatedBy
to zero unconditionally, the answer is yes, the value u.UpdatedBy
will be set regardless of the result of the expression CASE
through which it is set u.isactive
.
To overcome this, you can add a separate expression CASE
for the field u.UpdatedBy
and use the current value if the conditions of the other statement are CASE
not met:
UPDATE u
SET u.isactive = CASE
WHEN e.LVStatus<>'B' AND u.IsActive=1 AND u.AutoUpdate=1 THEN 0
WHEN e.LVStatus='B' AND u.IsActive=0 AND u.AutoUpdate=1 THEN 1
ELSE u.isactive
END
, u.UpdatedBy= CASE
WHEN (e.LVStatus<>'B' AND u.IsActive=1 AND u.AutoUpdate=1) OR
(e.LVStatus='B' AND u.IsActive=0 AND u.AutoUpdate=1)
THEN 0
ELSE u.UpdatedBy
END
FROM tbl_e e
INNER JOIN tbl_Users u ON e.id=u.id
Alternatively, you can move this condition into a clause WHERE
, for example:
UPDATE u
SET u.isactive = CASE
WHEN e.LVStatus<>'B' AND u.IsActive=1 AND u.AutoUpdate=1 THEN 0
WHEN e.LVStatus='B' AND u.IsActive=0 AND u.AutoUpdate=1 THEN 1
-- No ELSE is needed, because WHERE filters out all other cases
END
, u.UpdatedBy=0
FROM tbl_e e
INNER JOIN tbl_Users u ON e.id=u.id
WHERE (e.LVStatus<>'B' AND u.IsActive=1 AND u.AutoUpdate=1) OR
(e.LVStatus='B' AND u.IsActive=0 AND u.AutoUpdate=1)
source to share
One way to do this is to add a clause else
and return the original column value:
UPDATE u
SET u.isactive=(CASE WHEN e.LVStatus<>'B' AND u.IsActive=1 AND u.AutoUpdate=1 THEN 0
WHEN e.LVStatus='B' AND u.IsActive=0 AND u.AutoUpdate=1 THEN 1
ELSE u.isactive END),
u.UpdatedBy=0
FROM tbl_e e
INNER JOIN tbl_Users u ON e.id=u.id
source to share