DECLARE CURSOR (Transact-SQL)DECLARE CURSOR (Transact-SQL)
適用対象:Applies to: SQL ServerSQL Server (サポートされているすべてのバージョン)
SQL ServerSQL Server (all supported versions)
Azure SQL データベースAzure SQL Database
Azure SQL データベースAzure SQL Database
SQL ServerSQL Server (サポートされているすべてのバージョン)
SQL ServerSQL Server (all supported versions)
Azure SQL データベースAzure SQL Database
Azure SQL データベースAzure SQL Database
Transact-SQLTransact-SQL サーバー カーソルの属性を定義します。これには、スクロール動作や、カーソルが操作する結果セットを作成するクエリなどが含まれます。Defines the attributes of a Transact-SQLTransact-SQL server cursor, such as its scrolling behavior and the query used to build the result set on which the cursor operates. DECLARE CURSOR
は、ISO 標準に基づく構文と、Transact-SQLTransact-SQL の拡張機能のセットを使用する構文の両方で指定できます。DECLARE CURSOR
accepts both a syntax based on the ISO standard and a syntax using a set of Transact-SQLTransact-SQL extensions.
Transact-SQL 構文表記規則
Transact-SQL Syntax Conventions
構文Syntax
ISO Syntax
DECLARE cursor_name [ INSENSITIVE ] [ SCROLL ] CURSOR
FOR select_statement
[ FOR { READ ONLY | UPDATE [ OF column_name [ ,...n ] ] } ]
[;]
Transact-SQL Extended Syntax
DECLARE cursor_name CURSOR [ LOCAL | GLOBAL ]
[ FORWARD_ONLY | SCROLL ]
[ STATIC | KEYSET | DYNAMIC | FAST_FORWARD ]
[ READ_ONLY | SCROLL_LOCKS | OPTIMISTIC ]
[ TYPE_WARNING ]
FOR select_statement
[ FOR UPDATE [ OF column_name [ ,...n ] ] ]
[;]
注意
SQL Server 2014 以前の Transact-SQL 構文を確認するには、以前のバージョンのドキュメントを参照してください。To view Transact-SQL syntax for SQL Server 2014 and earlier, see Previous versions documentation.
引数Arguments
cursor_namecursor_name
定義された Transact-SQLTransact-SQL サーバー カーソルの名前です。Is the name of the Transact-SQLTransact-SQL server cursor defined. cursor_name は識別子の規則に準拠している必要があります。cursor_name must conform to the rules for identifiers.
INSENSITIVEINSENSITIVE
データの一時コピーを作成するためのカーソルを定義します。作成されるコピーは、カーソルで使用されます。Defines a cursor that makes a temporary copy of the data to be used by the cursor. このカーソルに対する要求の応答は、すべて tempdb 内のこの一時テーブルから得られます。したがって、ベース テーブルへの修正は、このカーソルで取り出したデータには反映されません。また、このカーソルで修正を行うこともできません。All requests to the cursor are answered from this temporary table in tempdb; therefore, modifications made to base tables are not reflected in the data returned by fetches made to this cursor, and this cursor does not allow modifications. ISO 構文で INSENSITIVE
を指定しない場合は、任意のユーザーによって基になるテーブルに加えられた削除および更新がコミットされると、以降のフェッチで反映されます。When ISO syntax is used, if INSENSITIVE
is omitted, committed deletes and updates made to the underlying tables (by any user) are reflected in subsequent fetches.
SCROLLSCROLL
すべてのフェッチ オプション (FIRST
、LAST
、PRIOR
、NEXT
、RELATIVE
、ABSOLUTE
) を使用可能に指定します。Specifies that all fetch options (FIRST
, LAST
, PRIOR
, NEXT
, RELATIVE
, ABSOLUTE
) are available. ISO 形式の DECLARE CURSOR
ステートメントに SCROLL
を指定しない場合、NEXT
は、サポートされている唯一のフェッチ オプションです。If SCROLL
is not specified in an ISO DECLARE CURSOR
, NEXT
is the only fetch option supported. FAST_FORWARD
も指定されている場合は、SCROLL
を指定できません。SCROLL
cannot be specified if FAST_FORWARD
is also specified. SCROLL
が指定されていない場合は、フェッチ オプション NEXT
だけが使用でき、カーソルは FORWARD_ONLY
になります。If SCROLL
is not specified then only the fetch option NEXT
is available and the cursor becomes FORWARD_ONLY
.
select_statementselect_statement
カーソルの結果セットを定義する標準の SELECT
ステートメントです。Is a standard SELECT
statement that defines the result set of the cursor. カーソル宣言の select_statement 内で FOR BROWSE
および INTO
キーワードは許可されません。The keywords FOR BROWSE
, and INTO
are not allowed within select_statement of a cursor declaration.
select_statement 内の句が、要求されたカーソルの種類の機能と矛盾する場合、SQL ServerSQL Server によってカーソルが別の種類に暗黙的に変換されます。SQL ServerSQL Server implicitly converts the cursor to another type if clauses in select_statement conflict with the functionality of the requested cursor type.
READ ONLYREAD ONLY
このカーソルによる更新を禁止します。Prevents updates made through this cursor. UPDATE
または DELETE
ステートメントの WHERE CURRENT OF
句では、このカーソルを参照できません。The cursor cannot be referenced in a WHERE CURRENT OF
clause in an UPDATE
or DELETE
statement. このオプションは、更新対象のカーソルの既定の機能をオーバーライドします。This option overrides the default capability of a cursor to be updated.
UPDATE [OF column_name [,...n]]UPDATE [OF column_name [,...n]]
カーソル内で更新できる列を定義します。Defines updatable columns within the cursor. OF <column_name> [, <... n>] を指定した場合は、指定した列に対してのみ更新ができます。If OF <column_name> [, <... n>] is specified, only the columns listed allow modifications. 列リストなしで UPDATE
を指定した場合は、すべての列を更新できます。If UPDATE
is specified without a column list, all columns can be updated.
cursor_namecursor_name
定義された Transact-SQLTransact-SQL サーバー カーソルの名前です。Is the name of the Transact-SQLTransact-SQL server cursor defined. cursor_name は識別子の規則に準拠している必要があります。cursor_name must conform to the rules for identifiers.
LOCALLOCAL
カーソルのスコープは、カーソルが作成されたバッチ、ストアド プロシージャ、またはトリガーに対してローカルです。Specifies that the scope of the cursor is local to the batch, stored procedure, or trigger in which the cursor was created. カーソル名は、そのスコープの中でだけ有効です。The cursor name is only valid within this scope. カーソルは、バッチ、ストアド プロシージャ、またはトリガー内のローカル カーソル変数から、またはストアド プロシージャの OUTPUT
パラメーターから参照できます。The cursor can be referenced by local cursor variables in the batch, stored procedure, or trigger, or a stored procedure OUTPUT
parameter. OUTPUT
パラメーターは、呼び出し側のバッチ、ストアド プロシージャ、トリガーにローカル カーソルを戻すのに使用されます。呼び出し側はパラメーターをカーソル変数に割り当て、ストアド プロシージャが終了した後でカーソルを参照できます。An OUTPUT
parameter is used to pass the local cursor back to the calling batch, stored procedure, or trigger, which can assign the parameter to a cursor variable to reference the cursor after the stored procedure terminates. カーソルは、OUTPUT
パラメーターで戻された場合を除いて、バッチ、ストアド プロシージャ、またはトリガーが終了するときに暗黙的に割り当てを解除されます。The cursor is implicitly deallocated when the batch, stored procedure, or trigger terminates, unless the cursor was passed back in an OUTPUT
parameter. OUTPUT
パラメーターで戻された場合は、カーソルを参照している最後の変数の割り当てが解除されるか、そのスコープが失われたときに、カーソルの割り当てが解除されます。If it is passed back in an OUTPUT
parameter, the cursor is deallocated when the last variable referencing it is deallocated or goes out of scope.
GLOBALGLOBAL
カーソルのスコープは、接続に対してグローバルです。Specifies that the scope of the cursor is global to the connection. カーソル名は、その接続によって実行されるストアド プロシージャやバッチの中で参照できます。The cursor name can be referenced in any stored procedure or batch executed by the connection. カーソルは、切断のときだけ暗黙的に割り当てを解除されます。The cursor is only implicitly deallocated at disconnect.
注意
GLOBAL
も LOCAL
も指定しない場合は、default to local cursor データベース オプションの設定によって既定の動作が決まります。If neither GLOBAL
or LOCAL
is specified, the default is controlled by the setting of the default to local cursor database option.
FORWARD_ONLYFORWARD_ONLY
カーソルは前方にだけ移動でき、先頭行から最終行までスクロールできることを指定します。Specifies that the cursor can only move forward and be scrolled from the first to the last row. FETCH NEXT
は、サポートされている唯一のフェッチ オプションです。FETCH NEXT
is the only supported fetch option. 現在のユーザーが行い (または別のユーザーがコミットし)、結果セット内の行に影響を与えたすべての挿入、更新、削除ステートメントは、行がフェッチされると認識できるようになります。All insert, update, and delete statements made by the current user (or committed by other users) that affect rows in the result set are visible as the rows are fetched. ただし、カーソルは後方にスクロールできないので、データベース内の行のフェッチ後にその行に対して行われた変更内容は、カーソル内で確認できません。Because the cursor cannot be scrolled backward, however, changes made to rows in the database after the row was fetched are not visible through the cursor. 順方向専用カーソルは既定では動的であり、現在の行が処理されるとすべての変更が検出されることを意味します。Forward-only cursors are dynamic by default, meaning that all changes are detected as the current row is processed. これにより、カーソルを開く時間が短縮され、基になるテーブルに対して行われた更新を結果セットで表示できるようになります。This provides faster cursor opening and enables the result set to display updates made to the underlying tables. 順方向専用カーソルでは後方スクロールはサポートされていませんが、アプリケーションでカーソルを閉じて開きなおすことにより、結果セットの先頭にカーソルを戻すことができます。While forward-only cursors do not support backward scrolling, applications can return to the beginning of the result set by closing and reopening the cursor. STATIC
、KEYSET
、または DYNAMIC
キーワードなしで FORWARD_ONLY
を指定した場合、カーソルは動的カーソルとして動作します。If FORWARD_ONLY
is specified without the STATIC
, KEYSET
, or DYNAMIC
keywords, the cursor operates as a dynamic cursor. FORWARD_ONLY
と SCROLL
のどちらも指定しない場合、既定値は FORWARD_ONLY
になります。ただし、キーワードに STATIC
、KEYSET
、または DYNAMIC
が指定されている場合を除きます。When neither FORWARD_ONLY
nor SCROLL
is specified, FORWARD_ONLY
is the default, unless the keywords STATIC
, KEYSET
, or DYNAMIC
are specified. STATIC
、KEYSET
、および DYNAMIC
の各カーソルは既定で SCROLL
になります。STATIC
, KEYSET
, and DYNAMIC
cursors default to SCROLL
. ODBC や ADO などのデータベース API と異なり、FORWARD_ONLY
は、STATIC
、KEYSET
、DYNAMIC
の Transact-SQLTransact-SQL カーソルと共にサポートされます。Unlike database APIs such as ODBC and ADO, FORWARD_ONLY
is supported with STATIC
, KEYSET
, and DYNAMIC
Transact-SQLTransact-SQL cursors.
STATICSTATIC
カーソルが最初に開かれた時点での結果セットを常に表示し、カーソルによって使用されるデータの一時的なコピーを作成することを指定します。Specifies that the cursor always displays the result set as it was when the cursor was first opened, and makes a temporary copy of the data to be used by the cursor. カーソルに対するすべての要求は、tempdb 内のこの一時テーブルから応答されます。All requests to the cursor are answered from this temporary table in tempdb. したがって、ベース テーブルに対して行われた挿入、更新、削除は、このカーソルに対して行われたフェッチによって返されるデータには反映されず、カーソルが開かれた後で結果セットのメンバーシップ、順序、値に対して行われた変更は、このカーソルでは検出されません。Therefore inserts, updates, and deletes made to base tables are not reflected in the data returned by fetches made to this cursor, and this cursor does not detect changes made to the membership, order, or values of the result set after the cursor is opened. 静的カーソルは、それ自体の更新、削除、挿入を検出してもかまいませんが、必ず行う必要はありません。Static cursors may detect their own updates, deletes, and inserts, although they are not required to do so. たとえば、静的カーソルが行をフェッチした後で、別のアプリケーションによってその行が更新されるものとします。For example, suppose a static cursor fetches a row, and another application then updates that row. アプリケーションで静的カーソルから行を再フェッチした場合、他のアプリケーションによって変更が行われたにも関わらず、認識される値は変更されていません。If the application refetches the row from the static cursor, the values it sees are unchanged, despite the changes made by the other application. すべての種類のスクロールがサポートされています。All types of scrolling are supported.
KEYSETKEYSET
カーソルを開くときに、カーソル内の行の構成要素と順序が固定されることを指定します。Specifies that the membership and order of rows in the cursor are fixed when the cursor is opened. 行を一意に識別するキーのセットは、tempdb 内の keyset というテーブルに組み込まれています。The set of keys that uniquely identify the rows is built into a table in tempdb known as the keyset. このカーソルでは、変更を検出する機能において、静的カーソルと動的カーソルの中間の機能が提供されます。This cursor provides functionality between a static and a dynamic cursor in its ability to detect changes. 静的カーソルと同様に、結果セットのメンバーシップと順序に対する変更は常に検出されません。Like a static cursor, it does not always detect changes to the membership and order of the result set. 動的カーソルと同様に、結果セット内の行の値に対する変更は検出されます。Like a dynamic cursor, it does detect changes to the values of rows in the result set. キーセット ドリブン カーソルは、キーセットという一意の識別子 (キー) のセットにより制御されます。Keyset-driven cursors are controlled by a set of unique identifiers (keys) known as the keyset. これらのキーは、結果セットの行を一意に識別する列のセットから構築されます。The keys are built from a set of columns that uniquely identify the rows in the result set. キーセットは、クエリ ステートメントによって返されるすべての行からのキー値のセットです。The keyset is the set of key values from all the rows returned by the query statement. キーセット ドリブン カーソルでは、カーソルの行ごとにキーが作成されて保存され、クライアント ワークステーションまたはサーバーに格納されます。With keyset-driven cursors, a key is built and saved for each row in the cursor and stored either on the client workstation or on the server. 各行にアクセスすると、格納されているキーを使用して、データ ソースから現在のデータ値がフェッチされます。When you access each row, the stored key is used to fetch the current data values from the data source. キーセット ドリブン カーソルでは、キーセットが完全に作成された時点で、結果セットのメンバーシップは凍結されます。In a keyset-driven cursor, result set membership is frozen when the keyset is fully populated. したがって、メンバーシップに影響を与える追加または更新は、開き直されるまで結果セットには反映されません。Thereafter, additions or updates that affect membership are not a part of the result set until it is reopened. (キーセットの所有者または他のプロセスによって行われた) データ値に対する変更は、ユーザーが結果セットをスクロールすると表示されます。Changes to data values (made either by the keyset owner or other processes) are visible as the user scrolls through the result set:
- 行が削除された場合は、削除された行は結果セット内のギャップとして認識されるので、行のフェッチを試みると -2 の
@@FETCH_STATUS
が返されます。If a row is deleted, an attempt to fetch the row returns an@@FETCH_STATUS
of -2 because the deleted row appears as a gap in the result set. 行に対するキーはキーセット内に存在しますが、結果セットには行は存在しなくなっています。The key for the row exists in the keyset, but the row no longer exists in the result set. - (他のプロセスによって) カーソルの外部で行われた挿入は、カーソルを閉じて再度開いた場合にのみ表示されます。Inserts made outside the cursor (by other processes) are visible only if the cursor is closed and reopened. カーソルの内部から行われた挿入は、結果セットの末尾に表示されます。Inserts made from inside the cursor are visible at the end of the result set.
- カーソル外部からキー値を更新すると、古い行を削除した後で新しい行を挿入した場合と同様に、Updates of key values from outside the cursor resemble a delete of the old row followed by an insert of the new row. 新しい値の行は表示されず、古い値の行をフェッチしようとすると
@@FETCH_STATUS
が -2 に設定されて返されます。The row with the new values is not visible, and attempts to fetch the row with the old values return an@@FETCH_STATUS
of -2. 新しい値は、WHERE CURRENT OF
句を指定してカーソルから更新が行われた場合に表示されます。The new values are visible if the update is done through the cursor by specifying theWHERE CURRENT OF
clause.
注意
クエリが一意なインデックスのないテーブルを少なくとも 1 つ参照する場合、このキーセット カーソルは静的カーソルに変換されます。If the query references at least one table without a unique index, the keyset cursor is converted to a static cursor.
DYNAMICDYNAMIC
変更がカーソル内またはカーソル外の他のユーザーのどちらによって行われたのかに関係なく、カーソルをスクロールして新しいレコードをフェッチすると、結果内の行に対して行われたすべてのデータ変更が反映されるカーソルを定義します。Defines a cursor that reflects all data changes made to the rows in its result set as you scroll around the cursor and fetch a new record, regardless of whether the changes occur from inside the cursor or by other users outside the cursor. したがって、すべてのユーザーによって行われたすべての挿入、更新、削除ステートメントが、カーソルによって表示されます。Therefore all insert, update, and delete statements made by all users are visible through the cursor. 行のデータ値、順序、メンバーシップは、各フェッチ操作で変化する可能性があります。The data values, order, and membership of the rows can change on each fetch. ABSOLUTE
フェッチ オプションは、動的カーソルではサポートされません。The ABSOLUTE
fetch option is not supported with dynamic cursors. カーソルの外部から行った更新は、(カーソルのトランザクション分離レベルが UNCOMMITTED
に設定されている場合を除き) コミットされるまで表示されません。Updates made outside the cursor are not visible until they are committed (unless the cursor transaction isolation level is set to UNCOMMITTED
). たとえば、動的カーソルで 2 つの行がフェッチされた後、別のアプリケーションによって一方の行は更新され、他の行は削除されたものとします。For example, suppose a dynamic cursor fetches two rows and another application then updates one of those rows and deletes the other. その後、動的カーソルでこれらの行がフェッチされた場合、削除された行は検出されませんが、更新された行は新しい値が表示されます。If the dynamic cursor then fetches those rows, it will not find the deleted row, but it will display the new values for the updated row.
FAST_FORWARDFAST_FORWARD
パフォーマンスの最適化が有効に設定された FORWARD_ONLY
、READ_ONLY
カーソルを指定します。Specifies a FORWARD_ONLY
, READ_ONLY
cursor with performance optimizations enabled. SCROLL
または FOR_UPDATE
も指定されている場合、FAST_FORWARD
は指定できません。FAST_FORWARD
cannot be specified if SCROLL
or FOR_UPDATE
is also specified. この種類のカーソルでは、カーソル内からのデータ変更は許可されません。This type of cursor does not allow data modifications from inside the cursor.
注意
FAST_FORWARD
と FORWARD_ONLY
の両方を同じ DECLARE CURSOR
ステートメントで使用できます。Both FAST_FORWARD
and FORWARD_ONLY
can be used in the same DECLARE CURSOR
statement.
READ_ONLYREAD_ONLY
このカーソルによる更新を禁止します。Prevents updates made through this cursor. UPDATE
または DELETE
ステートメントの WHERE CURRENT OF
句では、このカーソルを参照できません。The cursor cannot be referenced in a WHERE CURRENT OF
clause in an UPDATE
or DELETE
statement. このオプションは、更新対象のカーソルの既定の機能をオーバーライドします。This option overrides the default capability of a cursor to be updated.
SCROLL_LOCKSSCROLL_LOCKS
カーソルによって行われる位置指定更新または位置指定削除の成功が保証されることを指定します。Specifies that positioned updates or deletes made through the cursor are guaranteed to succeed. SQL ServerSQL Server はカーソルに読み取られた行をロックし、後で変更できることを保証します。locks the rows as they are read into the cursor to ensure their availability for later modifications. FAST_FORWARD
または STATIC
も指定されている場合、SCROLL_LOCKS
は指定できません。SCROLL_LOCKS
cannot be specified if FAST_FORWARD
or STATIC
is also specified.
OPTIMISTICOPTIMISTIC
行がカーソルに読み取られてから更新された場合に、カーソルによって行われる位置指定更新または位置指定削除が失敗することを指定します。Specifies that positioned updates or deletes made through the cursor do not succeed if the row has been updated since it was read into the cursor. SQL ServerSQL Server では、行がカーソルに読み取られるとき、その行はロックされません。does not lock rows as they are read into the cursor. 代わりに timestamp 列の値を比較するか、テーブルに timestamp 列がない場合はチェックサム値を使用して、行がカーソルに読み込まれてから変更されたかどうかが判別されます。It instead uses comparisons of timestamp column values, or a checksum value if the table has no timestamp column, to determine whether the row was modified after it was read into the cursor. 行が変更されている場合、位置指定更新または位置指定削除の試行は失敗します。If the row was modified, the attempted positioned update or delete fails. FAST_FORWARD
も指定されている場合は、OPTIMISTIC
を指定できません。OPTIMISTIC
cannot be specified if FAST_FORWARD
is also specified.
TYPE_WARNINGTYPE_WARNING
カーソルの種類が、要求されたものから別のものに暗黙的に変換された場合、クライアントに警告メッセージが送信されることを指定します。Specifies that a warning message is sent to the client when the cursor is implicitly converted from the requested type to another.
select_statementselect_statement
カーソルの結果セットを定義する標準の SELECT ステートメントです。Is a standard SELECT statement that defines the result set of the cursor. カーソル宣言の select_statement 内で COMPUTE
、COMPUTE BY
、FOR BROWSE
および INTO
キーワードは許可されません。The keywords COMPUTE
, COMPUTE BY
, FOR BROWSE
, and INTO
are not allowed within select_statement of a cursor declaration.
注意
カーソル宣言内ではクエリ ヒントを使用できますが、FOR UPDATE OF
句も使用する場合は、FOR UPDATE OF
の後に OPTION (<query_hint>)
を指定する必要があります。You can use a query hint within a cursor declaration; however, if you also use the FOR UPDATE OF
clause, specify OPTION (<query_hint>)
after FOR UPDATE OF
.
select_statement 内の句が、要求されたカーソルの種類の機能と矛盾する場合、SQL ServerSQL Server によってカーソルが別の種類に暗黙的に変換されます。SQL ServerSQL Server implicitly converts the cursor to another type if clauses in select_statement conflict with the functionality of the requested cursor type. 詳細については、「暗黙的なカーソル変換」を参照してください。For more information, see Implicit Cursor Conversions.
FOR UPDATE [OF column_name [,...n]]FOR UPDATE [OF column_name [,...n]]
カーソル内で更新できる列を定義します。Defines updatable columns within the cursor. OF <column_name> [, <... n>]
を指定した場合は、指定した列に対してのみ更新できます。If OF <column_name> [, <... n>]
is supplied, only the columns listed allow modifications. 列リストなしで UPDATE
を指定した場合は、すべての列を更新できます。ただし、READ_ONLY
コンカレンシー オプションを指定した場合を除きます。If UPDATE
is specified without a column list, all columns can be updated, unless the READ_ONLY
concurrency option was specified.
注釈Remarks
DECLARE CURSOR
は、Transact-SQLTransact-SQL サーバー カーソルの属性を定義します。これには、スクロール動作や、カーソルが操作する結果セットを作成するクエリなどが含まれます。DECLARE CURSOR
defines the attributes of a Transact-SQLTransact-SQL server cursor, such as its scrolling behavior and the query used to build the result set on which the cursor operates. OPEN
ステートメントは結果セットを設定し、FETCH
ステートメントは結果セットから行を返します。The OPEN
statement populates the result set, and FETCH
returns a row from the result set. CLOSE
ステートメントは、カーソルに関係付けられた現在の結果セットを解放します。The CLOSE
statement releases the current result set associated with the cursor. DEALLOCATE
ステートメントは、カーソルが使用するリソースを解放します。The DEALLOCATE
statement releases the resources used by the cursor.
最初の形式の DECLARE CURSOR
ステートメントは、ISO 構文を使用してカーソルの動作を宣言します。The first form of the DECLARE CURSOR
statement uses the ISO syntax for declaring cursor behaviors. 2 番目の形式の DECLARE CURSOR
は、Transact-SQLTransact-SQL の拡張機能を使用します。これによって、ODBC または ADO のデータベース API カーソル関数で使用されるカーソルの種類と同じカーソルの種類を使用して、カーソルを定義できます。The second form of DECLARE CURSOR
uses Transact-SQLTransact-SQL extensions that allow you to define cursors using the same cursor types used in the database API cursor functions of ODBC or ADO.
2 つの形式を混在することはできません。You cannot mix the two forms. CURSOR
キーワードの前に SCROLL
または INSENSITIVE
キーワードを指定した場合、CURSOR
キーワードと FOR <select_statement>
キーワードの間にはキーワードを一切使用できません。If you specify the SCROLL
or INSENSITIVE
keywords before the CURSOR
keyword, you cannot use any keywords between the CURSOR
and FOR <select_statement>
keywords. CURSOR
と FOR <select_statement>
の各キーワードの間にキーワードを指定した場合、CURSOR
キーワードの前に SCROLL
または INSENSITIVE
を指定できません。If you specify any keywords between the CURSOR
and FOR <select_statement>
keywords, you cannot specify SCROLL
or INSENSITIVE
before the CURSOR
keyword.
Transact-SQLTransact-SQL 構文を使用した DECLARE CURSOR
で READ_ONLY
、OPTIMISTIC
、または SCROLL_LOCKS
を指定していない場合、既定値は次のようになります。If a DECLARE CURSOR
using Transact-SQLTransact-SQL syntax does not specify READ_ONLY
, OPTIMISTIC
, or SCROLL_LOCKS
, the default is as follows:
権限が十分でなかったり、更新をサポートしないリモート テーブルにアクセスしているなどの理由で、
SELECT
ステートメントが更新をサポートしない場合、カーソルはREAD_ONLY
です。If theSELECT
statement does not support updates (insufficient permissions, accessing remote tables that do not support updates, and so on), the cursor isREAD_ONLY
.STATIC
およびFAST_FORWARD
の各カーソルは既定でREAD_ONLY
になります。STATIC
andFAST_FORWARD
cursors default toREAD_ONLY
.DYNAMIC
およびKEYSET
の各カーソルは既定でOPTIMISTIC
になります。DYNAMIC
andKEYSET
cursors default toOPTIMISTIC
.
カーソル名は、他の Transact-SQLTransact-SQL ステートメントでのみ参照できます。Cursor names can be referenced only by other Transact-SQLTransact-SQL statements. データベース API 関数でカーソル名を参照することはできません。They cannot be referenced by database API functions. たとえば、カーソルの宣言後、OLE DB、ODBC、または ADO 関数やメソッドからカーソル名を参照することはできません。For example, after declaring a cursor, the cursor name cannot be referenced from OLE DB, ODBC or ADO functions or methods. カーソル行は、フェッチ関数や API のメソッドでフェッチすることはできません。Transact-SQLTransact-SQL FETCH ステートメントによってのみフェッチできます。The cursor rows cannot be fetched using the fetch functions or methods of the APIs; the rows can be fetched only by Transact-SQLTransact-SQL FETCH statements.
カーソルの宣言後、次に示すシステム ストアド プロシージャを使用すると、カーソルの特性を判断できます。After a cursor has been declared, these system stored procedures can be used to determine the characteristics of the cursor.
システム ストアド プロシージャSystem stored procedures | 説明Description |
---|---|
sp_cursor_listsp_cursor_list | 現在接続時に可視であるカーソルとその属性の一覧を返します。Returns a list of cursors currently visible on the connection and their attributes. |
sp_describe_cursorsp_describe_cursor | 順方向専用カーソルか、スクロール カーソルかなど、カーソルの属性を記述します。Describes the attributes of a cursor, such as whether it is a forward-only or scrolling cursor. |
sp_describe_cursor_columnssp_describe_cursor_columns | カーソル結果セット内の列の属性を記述します。Describes the attributes of the columns in the cursor result set. |
sp_describe_cursor_tablessp_describe_cursor_tables | カーソルがアクセスするベース テーブルを記述します。Describes the base tables accessed by the cursor. |
カーソルを宣言する select_statement の一部として、変数を使用できます。Variables may be used as part of the select_statement that declares a cursor. カーソルが宣言された後、カーソル変数の値は変更されません。Cursor variable values do not change after a cursor is declared.
アクセス許可Permissions
DECLARE CURSOR
権限は、特に指定のない限りカーソル内で使用されるビュー、テーブル、および列の SELECT
権限を持つユーザーに与えられます。Permissions of DECLARE CURSOR
default to any user that has SELECT
permissions on the views, tables, and columns used in the cursor.
制限事項と制約事項Limitations and Restrictions
クラスター化列ストア インデックスを使用しているテーブルでは、カーソルやトリガーは使用できません。You cannot use cursors or triggers on a table with a clustered columnstore index. この制限は、非クラスター化列ストア インデックスには適用されません。非クラスター化列ストア インデックスを使用しているテーブルでは、カーソルとトリガーを使用できます。This restriction does not apply to nonclustered columnstore indexes; you can use cursors and triggers on a table with a nonclustered columnstore index.
例Examples
A.A. 単純なカーソルと構文を使用するUsing simple cursor and syntax
このカーソルのオープン時に作成された結果セットには、テーブルに存在するすべての行と列が含まれています。The result set generated at the opening of this cursor includes all rows and all columns in the table. このカーソルは更新することができ、すべての更新結果および削除結果は、このカーソルに対して行ったフェッチに反映されます。This cursor can be updated, and all updates and deletes are represented in fetches made against this cursor. SCROLL
オプションを指定していないため、フェッチに使用できるのは FETCH NEXT
のみです。FETCH NEXT
is the only fetch available because the SCROLL
option has not been specified.
DECLARE vend_cursor CURSOR
FOR SELECT * FROM Purchasing.Vendor
OPEN vend_cursor
FETCH NEXT FROM vend_cursor;
B.B. 入れ子になったカーソルを使用してレポート出力を作成するUsing nested cursors to produce report output
次の例では、カーソルを入れ子にして複雑なレポートを作成する方法を示します。The following example shows how cursors can be nested to produce complex reports. 内部のカーソルは、各製造元に対して宣言されます。The inner cursor is declared for each vendor.
SET NOCOUNT ON;
DECLARE @vendor_id INT, @vendor_name NVARCHAR(50),
@message VARCHAR(80), @product NVARCHAR(50);
PRINT '-------- Vendor Products Report --------';
DECLARE vendor_cursor CURSOR FOR
SELECT VendorID, Name
FROM Purchasing.Vendor
WHERE PreferredVendorStatus = 1
ORDER BY VendorID;
OPEN vendor_cursor
FETCH NEXT FROM vendor_cursor
INTO @vendor_id, @vendor_name
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT ' '
SELECT @message = '----- Products From Vendor: ' +
@vendor_name
PRINT @message
-- Declare an inner cursor based
-- on vendor_id from the outer cursor.
DECLARE product_cursor CURSOR FOR
SELECT v.Name
FROM Purchasing.ProductVendor pv, Production.Product v
WHERE pv.ProductID = v.ProductID AND
pv.VendorID = @vendor_id -- Variable value from the outer cursor
OPEN product_cursor
FETCH NEXT FROM product_cursor INTO @product
IF @@FETCH_STATUS <> 0
PRINT ' <<None>>'
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @message = ' ' + @product
PRINT @message
FETCH NEXT FROM product_cursor INTO @product
END
CLOSE product_cursor
DEALLOCATE product_cursor
-- Get the next vendor.
FETCH NEXT FROM vendor_cursor
INTO @vendor_id, @vendor_name
END
CLOSE vendor_cursor;
DEALLOCATE vendor_cursor;
参照See Also
@@FETCH_STATUS (Transact-SQL) @@FETCH_STATUS (Transact-SQL)
CLOSE (Transact-SQL) CLOSE (Transact-SQL)
カーソル (Transact-SQL) Cursors (Transact-SQL)
DEALLOCATE (Transact-SQL) DEALLOCATE (Transact-SQL)
FETCH (Transact-SQL) FETCH (Transact-SQL)
SELECT (Transact-SQL) SELECT (Transact-SQL)
sp_configure (Transact-SQL)sp_configure (Transact-SQL)