SQL是一種基于集合的語言(a set-based language) ,他更擅長(zhǎng)操作和提出一組數(shù)據(jù),而不是對(duì)
數(shù)據(jù)進(jìn)行一行一行的處理。
SQL is a set-based language ,meaning that is excels at mantipulating and retrieving
set of rows ,rather than performing single row-by-row processing.
如果你的程序里一定要一條一條的執(zhí)行,那么一定要先考慮使用如while循環(huán),子查詢,
臨時(shí)表,表變量等等,如果這些都不能滿足要求,在考慮使用游標(biāo)。
T-SQL中游標(biāo)的生存周期:
1.用返回一個(gè)有效結(jié)果集的sql語句來定義一個(gè)游標(biāo)。
a cursor is defined via a SQL statement that returns a valid result set.
2. 打開游標(biāo)
3. 一旦游標(biāo)被打開就可以從游標(biāo)中每次取出一行數(shù)據(jù),要根據(jù)游標(biāo)的定義可以向前去數(shù)據(jù)或
向后取數(shù)據(jù)
the rows can be fetched moving forword or backword ,depending on the original cursor definition.
4. 根據(jù)游標(biāo)的類型,數(shù)據(jù)可以被修改或者只能讀。
5.最后,用完游標(biāo)后,必須被顯示的關(guān)閉,并且從內(nèi)存中移除。
游標(biāo)定義格式:
declare cursor_name cursor
[local|global]
[forword_only|scroll]
[static|keyset|dynamic|fast_forword]
[read_only| scroll_locks|optimistic]
[type_warning]
for select_statement[for update [of column[,...]]]
The select_statement argument is the query used to define the data within the cursor. Avoid
using a query that hasmore columns and rows than will actually be used, because cursors, while
open, are kept inmemory. The UPDATE [OF column_name [,...n]] is used to specify those columns
that are allowed to be updated by the cursor.