2. T-SQL Cursor 的使用,效率的魔鬼,複雜的天使


Posted by Mephisto on 2025-03-30

當要集中處理資料表中的每一筆紀錄,我們就要使用資料指標(Cursors)
$\star$ 之後語法我都用英文小寫。

2-0. 基本指令

T-SQL 指令 說明
declare 宣告與定義一個新的資料指標
open 執行資料指標定義的 select 指令來開啟與建立資料指標
fetch 從資料指標取出一筆紀錄資料
close 關閉資料指標
deallocate 刪除資料指標定義和釋放佔用的系統資源

2-1. 宣告資料指標

語法 :

declare 資料指標名稱 cursor
[ local | global ]                             --範圍
[ forward_only | scroll ]                      --讀取方式
[ fast_forward | static | keyset | dynamic ]   --資料指標種類
[ read_only | scroll_locks | optimistic ]      --並行控制選項
for select 指令敘述

各類引述詳細說明 : Microsoft Learn

範例 :
使用的資料表 :
| ID | Name | Sex | Phone | Birthday |
|------|--------|-----|-------------|------------|
| S001 | 陳會安 | M | 02-22222222 | 2003-09-03 |
| S002 | 江小魚 | F | 03-33333333 | 2004-02-02 |
| S003 | 張無忌 | M | 04-44444444 | 2002-05-03 |
| S004 | 陳小安 | M | 05-55555555 | 2002-06-13 |
| S005 | 孫燕之 | F | 06-66666666 | NULL |
| S006 | 周杰輪 | M | 02-33333333 | 2003-12-23 |
| S007 | 蔡一零 | F | 03-66666666 | 2003-11-23 |
| S008 | 劉得華 | M | 02-11111122 | 2003-02-23 |

test

#t-sql #cursor







Related Posts

跨越千年的對話:人們是如何從神明的庇佑走向人工智能的引導?

跨越千年的對話:人們是如何從神明的庇佑走向人工智能的引導?

健保卡讀取程式 (console app sample)

健保卡讀取程式 (console app sample)

SQL & NoSQL

SQL & NoSQL


Comments