SQL if not null update

前端 未结 5 1760
忘掉有多难
忘掉有多难 2021-01-26 03:18

I have this query

UPDATE users SET username = Param1,email = Param2,PASSWORD = Param3 WHERE id = Param4;

this is updating my user row, but

5条回答
  •  感动是毒
    2021-01-26 03:39

    Like this

    UPDATE users 
    SET 
      username = Param1,
      email = COALESCE(Param2, email),
      password = COALESCE(Param3, password)
    WHERE id = Param4;
    

    COALESCE works from left to right taking the first non null argument. If you provide null as Param2, it will update email to email (no change). If you provide a value to Param2, coalesce will return that non null value so email is updated to whatever param2 is

    Ps: understood your request to be "I will provide either a null or a value in the parameter. If I provide a null I don't want to update the db table. If I provide a value I do want to update the DB table"

    This seemed more logical to me than how your question reads which is "if my table value is null for email then I forever want it to remain null and never want any of the values I supply in the parameters to be written to the table"

提交回复
热议问题