RBAR vs. Set based programming for SQL

有些话、适合烂在心里 提交于 2019-11-26 19:08:14

Set-based programming is based upon the mathematical concept of a set, and has operators that work on a whole set at a time. Procedural (RBAR) programming is based more on the traditional computer concepts of files and records. So to increase the salary of all employees in department X by 10%:

Set-based:

UPDATE employees SET salary = salary * 1.10 WHERE department = 'X';

Procedural (extreme example, pseudo-code):

OPEN cursor FOR SELECT * FROM employees;
LOOP
   FETCH cursor INTO record;
   EXIT WHEN (no more records to fetch);
   IF record.department = 'X' THEN
      UPDATE employees
      SET    salary = salary * 1.10
      WHERE  employee_id = record.employee_id;
   END IF
END LOOP
CLOSE cursor;

In the procedural version, only one employee row is being updated at a time; in the set-based version, all rows in the "set of employees in department X" are updated at once (as far as we are concerned).

Not sure this adds anything to what you will have already read in your links, but I thought I'd have a shot at it!

I will point out that set-based processing can involve loops. If you want to process in batches rather than tie up several tables while you load a million records into them in one set-based process, you can loop through batches of records, this is faster than a cursor which operates one row at a time and may be far better for your database than doing one giant insert statement.

Some RBAR processes don't look like cursors or loops either. These would include correlated subqueries and many user-defined functions.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!