Under the Case Method in SQL Server (favorites)

Source: Internet
Author: User
Next

4. Conditional UPDATE.

For example, the following update conditions are available:

  1. For employees with a salary of more than 5000, the salary is reduced by 10%.
  2. Employees with salaries between 2000 and 4600 increase by 15%

You can easily choose to execute two UPDATE statements, as shown below:

-- Condition 1 UPDATE PersonnelSET salary = salary * 0.9 WHERE salary> = 5000; -- condition 2 UPDATE PersonnelSET salary = salary * 1.15 WHERE salary> = 2000 AND salary <4600;

However, it is not as simple as you think. Suppose there is a personal salary of 5000 RMB. First, according to condition 1, the salary is reduced by 10% to 4500. Next, when we run the second SQL statement, because the salary of this person is within the range of 4500 to 2000, we need to increase by 4600. Finally, the salary of this person is 15%, which is not only not reduced, instead, it increases. If this is done in turn, 4600 of the employees will be reduced. No matter how absurd this rule is, if you want an SQL statement to implement this function, we need to use the Case function. The Code is as follows:

UPDATE PersonnelSET salary = CASE WHEN salary >= 5000             THEN salary * 0.9WHEN salary >= 2000 AND salary < 4600THEN salary * 1.15ELSE salary END;

Note that the ELSE salary in the last line is necessary. If there is no such line, the salary of a person who does not meet the two conditions will be written as NUll, which is not a good deal. In the Case function, the default value of the Else part is NULL, which is worth attention.
This method can also be used in many places, such as changing the primary key.
Generally, to exchange the Primary key, a, and B of two data, you need to temporarily store, copy, and read the data back. If you use the Case function, everything is much easier.

P_key Col_1 Col_2
A 1 Zhang San
B 2 Li Si
C 3 Wang Wu

Assume that the primary key must beaAndbExchange. The Code is as follows:

UPDATE SomeTableSET p_key = CASE WHEN p_key = 'a'THEN 'b'WHEN p_key = 'b'THEN 'a'ELSE p_key ENDWHERE p_key IN ('a', 'b');

You can also exchange two Unique keys. It should be noted that if primary keys need to be exchanged, most of the reasons are that the design of the table was not enough. We recommend that you check whether the table is properly designed.

5. Check whether the data of the two tables is consistent.

The Case function is different from the DECODE function. IN the Case function, BETWEEN, LIKE, is null, IN, EXISTS, and so on can be used. For example, you can use IN and EXISTS to perform subqueries to implement more functions.
Two tables, tbl_A and tbl_ B, both of which have keyCol columns. Now we compare the two tables. If the data in the keyCol column of tbl_A can be found in the data in the keyCol column of tbl_ B, the return result is 'matched'. If not, the returned result is 'unmatched '.
To implement the following functions, you can use the following two statements:

-- SELECT keyCol WHEN using IN, case when keyCol IN (SELECT keyCol FROM tbl_ B) THEN 'matched' ELSE 'unmatched' END LabelFROM tbl_A; -- SELECT keyCol WHEN using EXISTS, case when exists (SELECT * FROM tbl_BWHERE tbl_A.keyCol = tbl_ B .keyCol) THEN 'matched' ELSE 'unmatched' END LabelFROM tbl_A;

The results of using IN and EXISTS are the same. You can also use not in and not exists, but pay attention to NULL.

6. Use the aggregate function in the Case Function

Assume that the following table exists.

Student ID (std_id) Course ID (class_id) Course name (class_name) Major: flag (main_class_flg)
100 1 Economics Y
100 2 History N
200 2 History N
200 3 Archaeology Y
200 4 Computer N
300 4 Computer N
400 5 Chemistry N
500 6 Mathematics N

Some students choose to take several courses (100,200) at the same time, and some students choose only one course (300,400,500 ). If you are a student of multiple courses, You must select a course as your major. The major is flag, which is written into Y. Students who only select one course, whose major is flag is N (in fact, if I write Y, there will be no troubles below. For example, please include more ).
Now we need to query the table according to the following two conditions:

  1. The person who takes only one course returns the ID of the course.
  2. Returns the ID of the selected primary course.

The simple idea is to execute two different SQL statements for query.
Condition 1

-- Condition 1: SELECT std_id, MAX (class_id) AS main_classFROM StudentclassGROUP BY std_idHAVING COUNT (*) = 1;

Execution result 1

STD_ID   MAIN_class------   ----------300      4400      5500      6

Condition 2

-- Condition 2: SELECT std_id and class_id AS main_classFROM StudentclassWHERE main_class_flg = 'y' for students of multiple courses ';

Result 2

STD_ID  MAIN_class------  ----------100     1200     3

If the Case function is used, we only need one SQL statement to solve the problem, as shown below:

SELECT std_id, case when count (*) = 1 -- SELECT only the students of one course. then max (class_id) else max (case when main_class_flg = 'y' THEN class_idELSE null end) end as main_classFROM StudentclassGROUP BY std_id;

Running result

STD_ID   MAIN_class------   ----------100      1200      3300      4400      5500      6

By embedding Case functions in Case functions and using Case functions in aggregate functions, we can easily solve this problem. The use of the Case function gives us greater freedom.
Finally, I would like to remind the novice who uses the Case function not to make the following mistakes.

CASE col_1WHEN 1        THEN 'Right'WHEN NULL  THEN 'Wrong'END

In this statement, the When Null Line always returns unknown, so Wrong will never occur. This statement can be replaced with WHEN col_1 = NULL. This IS an incorrect usage. In this case, we should use WHEN col_1 is null.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.