Introduction
One of the keys to database performance if keeping your transactions as short as possible. In this article we will look at a couple of tricks using the CASE statement to perform multiple updates on a table in a single operation.
Multiple updates to a single column
This example uses the pubs database to adjust book prices for a sale by different amounts according to different criteria. In the example I am going to knock 25% off all business books from any publisher, and 10% off any non-business books from a particular publisher. You might be tempted to wrap two separate update statements into one transaction like this:
begin tran
update titles set ...
update titles set ...
commit tran
The down side of this technique is that it will read through the table twice, once for each update. If we code our update like the example below, then the table will only need to be read once. For large tables, this can save us a lot of disk IO, especially if the query requires a table scan over a long table
update titles
set price =
case
when type = "business"
then price * 0.75
when pub_id = "0736"
then price * 0.9
end
where pub_id = "0736" OR
type = "business"
Note that there is a definite "top-down" priority involved in the CASE statement. For business books from publisher 0736 the "business" discount will apply because this is the first condition in the list to be fulfilled. However, we will not give a further 10% publisher discount, even though the criteria for the second "when" clause is satisfied, because the CASE statement only evaluates criteria until it finds the first one that fits.
Multi-column updates
We can use the CASE statement to update multiple columns in a table, even using separate update criteria for each column. This example updates the publishers table to set the state column to "--" for non-USA companies, and changes the city for one particular publisher, all in one table read operation.
update publishers
set
state = case
when country <> "USA"
then "--"
else state
end,
city = case
when pub_id = "9999"
then "LYON"
else city
end
where country <> "USA" OR
pub_id = "9999"
The same format will work for updates across three or more rows with different update criteria.
You may come across fewer opportunities to use this second technique efficiently. This query will almost invariably result in a table scan because we are selecting on multiple columns that are unlikely to all be in a covering index. If each column is updated only a small number of times, and is indexed, it may still be more efficient to do separate updates.
A good place to use this technique might be in cleaning up multiple columns in a long interface file from another system.
Because we are using two separate case statements, one for each test criteria/update, each case statement will be evaluated for every row, and updates applied where required. Therefore if more than one column in the row requires an update, they will all be updated.
Two things are particularly important to remember in this example:
- The else [column] clause is required for each case statement used, otherwise you will end up nulling-out data you do not want to.
- The where clause at the end must be used to restrict the update to rows that require at least one column updating, otherwise every column in the table will be updated, increasing both execution time and pressure on the transaction log.
分享到:
相关推荐
listViewMRU.BeginUpdate(); ListViewGroup pro = listViewMRU.Groups.Add("profile", "profile"); listViewMRU.Items.Add(Environment.GetFolderPath(Environment.SpecialFolder.Recent)).Group = pro; ...
not all of the features mentioned in this file are available inall editions of the product.This update resolves the following issues:IDE* Using the up/down arrow keys to navigate and select items from...
This document outlines a prototype implementation for Secure OTA updates for Linux images, specifically designed for NXP devices (in this case, i.MX8M/MM families) using the Cryptographic Acceleration...
NEW Sort Selected Lines now supports ascending and descending options, as well as case-sensitive and case-insensitive options. (case=29858) 8876, 9194, 12143 NEW Smart Select now supports more ...
- 使用`using`语句管理资源,确保连接在使用后及时关闭。 3. **增(添加)操作**: - 使用SqlCommand的`ExecuteNonQuery()`方法执行INSERT语句,将新记录插入到表中。 - 需要指定列名和对应的值,或者使用参数化...
Tuning DML (INSERT, UPDATE, DELETE) Section 21.6. Conclusion Chapter 22. Optimizing Stored Program Code Section 22.1. Performance Characteristics of Stored Programs Section 22.2. How Fast Is ...
Using this book, you will learn how to use jQuery's powerful DOM manipulation tools to dynamically update content on your site. You will be able to extend jQuery's capabilities by writing your own ...
Compare Table Data tool would commit every record in "update database" mode when using a commit interval Using the Auto Refresh function in the SQL Window would prompt for substitution variable values...
Compare Table Data tool would commit every record in "update database" mode when using a commit interval Using the Auto Refresh function in the SQL Window would prompt for substitution variable values...
case 4: Update(connstr); break; default: break; } ``` 这是一个switch语句,用于根据用户输入的不同操作编号(Operator)来选择执行不同的数据库操作方法。这里的操作编号1、2、3、4分别对应选择、添加、删除和...
Scrubbing time value on Point Cache modifier will now update mesh if animate is turned off. Added option to morph inspector to show mapping data so in case of failures it can help show what the issue ...
TEAC take no responsibility for any trouble caused by using this program (details are described in the Licensing Agreement). If you do not agree with this condition, do not execute this program. ...
Choose the appropriate RFC destination for importing the IDoc type you need, which in this case is likely to be "CREMAS". Follow the wizard to import the CREMAS IDoc structure. A.2.2 Create ...
How to access and update part of the page using code. How to use JavaScript to communicate with the server and retrieve data. How to use JavaScript to for form validation and user feedback. How to use...
14.1. Case Sensitivity 14.2. The from clause 14.3. Associations and joins 14.4. Forms of join syntax 14.5. The select clause 14.6. Aggregate functions 14.7. Polymorphic queries 14.8. The where clause ...
int result = ChangeDisplaySettingsEx(null, ref devMode, IntPtr.Zero, CDS_UPDATEREGISTRY, IntPtr.Zero); if (result == DISP_CHANGE_SUCCESSFUL) { return true; } else { return false; } } } ``` ...