Home > Database > Mysql Tutorial > How Can I Efficiently Update Records with a CASE Statement in SQL Server 2005?

How Can I Efficiently Update Records with a CASE Statement in SQL Server 2005?

Susan Sarandon
Release: 2024-12-27 20:16:10
Original
433 people have browsed it

How Can I Efficiently Update Records with a CASE Statement in SQL Server 2005?

How to Utilize CASE Statement in SQL Server 2005 Updates

The CASE statement provides a concise method for updating records based on specified conditions. However, it's essential to consider efficiency when using CASE statements, especially when dealing with large tables.

Problem:

The following SQL statement updates records in the TestStudents table, changing specific last names to new values using the CASE statement:

UPDATE dbo.TestStudents  
SET LASTNAME = 
( CASE  
WHEN (LASTNAME = 'AAA') THEN 'BBB' 
WHEN (LASTNAME = 'CCC') THEN 'DDD' 
WHEN (LASTNAME = 'EEE') THEN 'FFF' 
ELSE  (LASTNAME)
END )
Copy after login

While this statement achieves the desired result, it scans through every record in the table, even those that remain unaffected.

Solution:

To improve performance and maintain data integrity, a WHERE clause can be added to limit the update to only those rows that qualify for the change:

UPDATE dbo.TestStudents  
SET     LASTNAME =  CASE  
                        WHEN LASTNAME = 'AAA' THEN 'BBB' 
                        WHEN LASTNAME = 'CCC' THEN 'DDD' 
                        WHEN LASTNAME = 'EEE' THEN 'FFF' 
                        ELSE LASTNAME
                    END 
WHERE   LASTNAME IN ('AAA', 'CCC', 'EEE')
Copy after login

The WHERE clause specifies that only records where the last name equals 'AAA', 'CCC', or 'EEE' should be included in the update. This ensures that unaffected rows remain unchanged, reducing unnecessary operations on the table.

By combining the CASE statement with a properly defined WHERE clause, you can efficiently update specific records in your SQL database while maintaining data integrity.

The above is the detailed content of How Can I Efficiently Update Records with a CASE Statement in SQL Server 2005?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template