Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

update table with différents conditions

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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'

sqlfiddle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading