Update Statement In Sql Server With Case

Update Statement In Sql Server With Case

Update statement in SQL Server is a way to update the data in your table with the same name. You can simply use T-SQL command to update your table details within a specified time interval. There are two types of updates you can do from your admin side.

CASE statement in SQL

Update Statement In Sql Server With Case

UPDATE Sales.SalesOrderHeader SET OrderDate = ‘2019-08-06’ WHERE SalesOrderID IN (SELECT SalesOrderID FROM Sales.SalesOrderDetail WHERE ProductID = 7) AND CustomerID = ‘ALFKI’;

Update Query With Case Statement In Sql Server

The CASE statement is one of the most useful constructs in SQL Server and is used for multiple purposes like checking for null values, performing conditional tests, etc. It can also be used for updating data records based on different conditions. The syntax of the UPDATE statement with CASE is listed below:

UPDATE table_name SET column_name1 = value1, column_name2 = value2 [WHERE condition];

Using Case With Select and Update Statement in SQL Server 2012

UPDATE Statement In Sql Server With Case

The UPDATE statement is used to modify the existing records in a database table. It can also be used to remove records from the database. The UPDATE statement is used to update a set of rows in a table or view. The columns that are specified in the SET clause must be identical for all rows that are modified by the UPDATE statement. If they are not, then the query will fail.

The UPDATE statement uses the following syntax:

UPDATE [LOW_PRIORITY] [IGNORE] table_name SET column1 = value1, column2 = value2[, …n] [WHERE search_condition]

Notice that this is similar to the DELETE statement because both statements have WHERE clauses and they both use search conditions to control which records are updated or deleted. The only difference between these two statements is that DELETE can remove more than one row at once whereas UPDATE modifies only one row at a time.

UPDATE SUM(Qty) WITH CASE WHEN P.ProdID = ‘P1’ THEN 0 ELSE SUM(Qty) END AS SumNew,

SUM(Qty) AS SumExisting

FROM Sales.SalesOrderDetail D

JOIN Sales.SalesOrderHeader H ON H.SalesOrderID = D.SalesOrderID AND H.StatusCode IN (3, 4, 5) AND D.ProductID = ‘P1’

GROUP BY P.ProdID

UPDATE Example:

Suppose we have Employee table with following records:

EmployeeID Name Salary

1 James 100000

2 Peter 5000

3 David 10000

4 Mark 220000

Leave a Reply

Your email address will not be published. Required fields are marked *