I want to make an update in my Student table ( colums : Id, name , age UpdatedDate) according two conditions:
@id = 10
UPDATE Student SET Id = @id, UpdatedDate = GETDATE() WHERE Name = "David"
IF age is NULL AND @id = 10 UPDATE Student SET Id = @id, UpdatedDate = GETDATE(), age = 22 WHERE Name = "David"
how can I do this update in a more optimal way please ? the two updates are similar except the difference of a column that we only update if a condition is verified thank you
CodePudding user response:
You can try to UPDATE
by CASE WHEN
expression, Making your expectation condition then return result to UPDATE
, otherwise use original value in ELSE
do nothing.
UPDATE Student
SET Id = @id,
UpdatedDate = GETDATE(),
age = (CASE WHEN age is NULL AND @id = 10 THEN 22 ELSE age END)
WHERE Name = 'David'