`

update using case

阅读更多

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.
分享到:
评论

相关推荐

    using System;using System;using System;

    listViewMRU.BeginUpdate(); ListViewGroup pro = listViewMRU.Groups.Add("profile", "profile"); listViewMRU.Items.Add(Environment.GetFolderPath(Environment.SpecialFolder.Recent)).Group = pro; ...

    Delphi7.1 Update

    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...

    AN12900 Secure Over-the-Air Prototype for Linux Using CAAM and Mender

    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...

    Visual Assist X 2107官方原版 带破解补丁

    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 ...

    DATA ANALYSIS USING SQL AND EXCEL

    - **数据操纵语言(DML)**:主要包括插入数据(INSERT INTO)、更新数据(UPDATE)、删除数据(DELETE)等命令。 - **数据查询语言(DQL)**:使用SELECT语句从数据库中检索数据。 - **数据控制语言(DCL)**:用于...

    case0705_sqlserver_

    - 使用`using`语句管理资源,确保连接在使用后及时关闭。 3. **增(添加)操作**: - 使用SqlCommand的`ExecuteNonQuery()`方法执行INSERT语句,将新记录插入到表中。 - 需要指定列名和对应的值,或者使用参数化...

    MySql存储过程编程.chm

    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 ...

    Practical jQuery(Apress,2015)

    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 ...

    plsqldev13.0.3.1902x32主程序+ v12中文包+keygen

    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...

    plsqldev13.0.3.1902x64主程序+ v12中文包+keygen

    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...

    实验八访问数据库应用实例参照.pdf

    case 4: Update(connstr); break; default: break; } ``` 这是一个switch语句,用于根据用户输入的不同操作编号(Operator)来选择执行不同的数据库操作方法。这里的操作编号1、2、3、4分别对应选择、添加、删除和...

    Unity变形插件最新版 Mega-Fiers_2.44.unitypackage

    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 泰克 w540e固件开4x.rar

    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. ...

    idoc上传Step-by-step guide on File-to-IDoc using SAP PI 7.0

    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 ...

    Beginning JavaScript with DOM Scripting and Ajax: Second Editon

    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...

    Hibernate Reference Documentation3.1

    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 ...

Global site tag (gtag.js) - Google Analytics