Update wit filter condition for multiple columns in sql server

Naresh y 146 Reputation points
2023-03-29T15:07:52.0733333+00:00

update columns based on effectivedate filter.

If effectivedate is null then update the column1,column2,column3

from table

else

If effectivedate is not null then update the column1,column2,column3

from table

how to write this condition using sql code

SQL Server Other
{count} votes

2 answers

Sort by: Most helpful
  1. Erland Sommarskog 121.4K Reputation points MVP Volunteer Moderator
    2023-03-29T21:21:35.4466667+00:00

    Hm, you are updating the same columns in both cases. The order is different, but that does not matter.

    But say that you want to update col1 when effectiveDate is NULL and update col2 is it is non-NULL. This is how you can do it:

    UPDATE tbl
    SET  col1 = CASE WHEN effectiveDate IS NULL THEN <some new value> ELSE col1 END,
         col2 = CASE WHEN effectiveDate IS NULL THEN col2 ELSE <some new value> END
    WHERE ...
    
    
    0 comments No comments

  2. Anonymous
    2023-03-30T02:21:30.1233333+00:00

    Hi @Naresh y

    Your description confuses me.

    If column1, column2, and column3 are updated at the same time. All you need is a simple update statement like this.

    update table 
    set column1 = <some new value>,column2 = <some new value>,column3 =<some new value> 
    where effectivedate is (not) null;
    

    If you need columns 1, 2, and 3 to update differently depending on whether the effectiveDate is null or not, you can try Erland's method.

    Best regards,

    Percy Tang


    If the answer is the right solution, please click "Accept Answer". If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.