I have one table with some columns and I need to update it on conditional basis in SQL server. I have one table and I wanted to execute the 'Update' statement on this table after some UI operation. But the thing is I have to update only some columns on a condition basis and some columns will be updated without any condition.
Please check the schema details below
Table_1
| ID | Name | Phone | |
|---|---|---|---|
| 1 | A | [email protected] | 12345678890 |
| 2 | B | [email protected] | 14345678890 |
I have one procedure where we are sending the parameters for updating this table and we are also sending one flag parameter (for applying the condition in update statement)
CREATE PROC UpdateStudent
@Name VARCHAR(100) = NULL,
@Email VARCHAR(100) = NULL,
@Phone VARCHAR(20) = NULL,
@IsChanged BIT = NULL
AS
BEGIN
--update 'Table_1'
update Table_1 SET
Name = IIF(@IsChanged = 1, @Name, null),
Email = @Email,
Phone = IIF(@IsChanged = 1, @Phone , null)
where ID = 1
END
So if flag @IsChanged is 1 then as per the above query I need to update but if flag @IsChanged is 0 then I have to update different 'Update' statement-
IF @IsChanged = 0
BEGIN
--update 'Table_1'
update Table_1 SET
Name = NULL,
Email = NULL,
Phone = NULL
where ID = 1
END
Is there any best way to handle this requirement where if we have to update multiple columns with one condition, how we can do that in SQL server?
IIFwith aCASEexpression, but it would actually give you more code, not less.