Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing IF Condition Within a T-SQL UPDATE Statement

Tags:

Using T-SQL, I would like to execute an UPDATE statement that will SET columns only if the corresponding variables are defined.

Here's a simple pseudo-tsql example of what I'm trying to accomplish:


--Declaring vars @ID int, @Name nvarchar(20), @Password nvarchar(10)  --Run the update UPDATE User SET IF LEN(@NAME) > 0   Name = @Name, IF LEN(@Password) > 0   Password = @Password 

From what I can tell by reading how IF conditions work in T-SQL, in order to accomplish the same result as the above pseudo code, I would have to create an UPDATE statement for every IF condition - which is what I'm trying to avoid having to do.

Is it possible to dynamically SET fields/columns based on a condition using only one UPDATE statement? - If so, how?

like image 615
Jed Avatar asked Jul 15 '10 06:07

Jed


People also ask

Can you write UPDATE query with WHERE condition?

The SQL UPDATE Query is used to modify the existing records in a table. You can use the WHERE clause with the UPDATE query to update the selected rows, otherwise all the rows would be affected.

How do I UPDATE conditionally in SQL?

To do a conditional update depending on whether the current value of a column matches the condition, you can add a WHERE clause which specifies this. The database will first find rows which match the WHERE clause and then only perform updates on those rows.

Can we use with clause in UPDATE statement in SQL?

6 – Update using WITH ClauseYou can use a subquery in the WITH clause (called a CTE or Common Table Expression) to update data in one table from another table. WITH subquery AS ( SELECT account_id, account_number, person_id FROM account ) UPDATE person SET account_number = subquery.


2 Answers

The CASE expression

UPDATE User SET     Name = CASE WHEN LEN(@NAME) > 0 THEN @Name ELSE Name END,     Password = CASE WHEN LEN(@Password) > 0 THEN @Password ELSE Password END WHERE    ... 
like image 150
gbn Avatar answered Sep 18 '22 03:09

gbn


I think this will be useful:

Create PROCEDURE [dbo].[CodeUpdate]  (     @Id int,      @Name nVarChar(150)=null,      @IsActive bit =null,      @IsSystem bit=null ) AS  BEGIN      UPDATE [dbo].[Code] SET          [Name] = CASE WHEN @Name is null THEN [Name] ELSE @Name END,         [IsActive] = CASE WHEN @IsActive is null THEN [IsActive] ELSE @IsActive END,         [IsSystem] = CASE WHEN @IsSystem is null THEN [IsSystem] ELSE @IsSystem END     WHERE  ID = @Id End 

Do you like it? Enjoy.

like image 39
Ahmad Ebrahimi Avatar answered Sep 21 '22 03:09

Ahmad Ebrahimi