You can change your UPDATE
statement as follows to avoid NULL
-ing out the fields for parameters set to NULL
:
UPDATE UserProfile
SET
FirstName = CASE WHEN @p_FirstName_set THEN @p_FirstName ELSE FirstName END
, LastName = CASE WHEN @p_LastName_set THEN @p_LastName ELSE LastName END
-- ...and so on
WHERE UserId = @p_UserId
This doubles the number of parameters - for each optional parameter @XYZ
you need to add a @XYZ_set
parameter that you set to 1
if the @XYZ
is used, or to 0
when the @XYZ
is not used.
if (changeFirstName) {
cmd.Parameters.AddWithValue("@p_FirstName", userProfile.FirstName);
cmd.Parameters.AddWithValue("@p_FirstName_set", 1);
} else {
cmd.Parameters.AddWithValue("@p_FirstName", "");
cmd.Parameters.AddWithValue("@p_FirstName_set", 0);
}
// ... and so on
You can add a function to encapsulate this if
statement.
This approach lets you set values to NULL
if you need to do so, because the information on whether the corresponding parameter is set or not is no longer contained in the value of the parameter itself.
Note that the query remains static regardless of how many fields are set, so your RDBMS could avoid building a new query plan each time you set a different group of parameters.