Você está na página 1de 28

Cursores (Transact-SQL)

Las instrucciones de SQL Server producen un conjunto completo de resultados, pero hay ocasiones en que los resultados se procesan mejor de fila en fila. Abrir un cursor sobre un conjunto de resultados permite procesar el conjunto de resultados de fila en fila. Puede asignar un cursor a una variable o parmetro con un tipo de datos cursor. Las operaciones de cursor estn admitidas en las siguientes instrucciones: CLOSE CREATE PROCEDURE DEALLOCATE DECLARE CURSOR DECLARE @local_variable DELETE FETCH OPEN UPDATE SET Las siguientes funciones del sistema y procedimientos almacenados del sistema admiten tambin cursores: @@CURSOR_ROWS CURSOR_STATUS @@FETCH_STATUS sp_cursor_list sp_describe_cursor sp_describe_cursor_columns sp_describe_cursor_tables

@@CURSOR_ROWS (Transact-SQL)
Devuelve el nmero de filas certificadas que se encuentran en el ltimo cursor abierto en la conexin. Para mejorar el rendimiento, SQL Server puede rellenar asincrnicamente los cursores estticos y de conjunto de claves de gran tamao. Puede llamar a @@CURSOR_ROWS para determinar que el nmero de filas que cumplan las condiciones del cursor se recuperen en el momento en que se llama a @@CURSOR_ROWS. Convenciones de sintaxis de Transact-SQL

@@CURSOR_ROWS

Tipos de valor devueltos

integer

Valor devuelto

Valor devuelto
-m

Descripcin
El cursor se rellena de forma asincrnica. El valor devuelto (-m) es el nmero de filas que contiene actualmente el conjunto de claves.

-1

El cursor es dinmico. Como los cursores dinmicos reflejan todos los cambios, el nmero de filas correspondientes al cursor cambia constantemente. Nunca se puede afirmar que se han recuperado todas las filas que correspondan.

No se han abierto cursores, no hay filas calificadas para el ltimo cursor abierto, o ste se ha cerrado o su asignacin se ha cancelado.

El cursor est completamente relleno. El valor devuelto (n) es el nmero total de filas del cursor.

Comentarios

El nmero que devuelve @@CURSOR_ROWS es negativo cuando el ltimo cursor se ha abierto de forma asincrnica. Los cursores controlados por conjunto de claves y los estticos se abren de forma asincrnica cuando el valor de sp_configure cursor threshold es mayor que cero y el nmero de filas del conjunto de resultados del cursor es mayor que su umbral.

Ejemplos

El ejemplo siguiente declara un cursor y utiliza SELECT para mostrar el valor de @@CURSOR_ROWS. La opcin tiene el valor 0 antes de abrir el cursor y el valor -1 para indicar que el conjunto de claves del cursor se est rellenando de forma asincrnica.

USE AdventureWorks2008R2; GO SELECT @@CURSOR_ROWS; DECLARE Name_Cursor CURSOR FOR SELECT LastName ,@@CURSOR_ROWS FROM Person.Person; OPEN Name_Cursor; FETCH NEXT FROM Name_Cursor; SELECT @@CURSOR_ROWS; CLOSE Name_Cursor; DEALLOCATE Name_Cursor; GO
Los conjuntos de resultados son los siguientes. ----------0 LastName --------------Snchez -----------1

CURSOR_STATUS (Transact-SQL)
Una funcin escalar que permite a quien llama a un procedimiento almacenado determinar si el procedimiento ha devuelto un cursor y el conjunto de resultados de un parmetro determinado.

CURSOR_STATUS ( { 'local' , 'cursor_name' } | { 'global' , 'cursor_name' } | { 'variable' , 'cursor_variable' } )

Argumentos

'local' Especifica una constante que indica que el origen del cursor es un nombre de cursor local. 'cursor_name' Es el nombre del cursor. Un nombre de cursor debe ajustarse a las reglas para los identificadores. 'global' Especifica una constante que indica que el origen del cursor es un nombre de cursor global. 'variable' Especifica una constante que indica que el origen del cursor es una variable local. 'cursor_variable' Es el nombre de la variable de cursor. Una variable de cursor debe definirse mediante el tipo de datos cursor.

Tipos de valor devueltos

smallint

Valor devuelto
1

Nombre de cursor
El conjunto de resultados del cursor tiene al menos una fila. Para los cursores INSENSITIVE y de conjunto de claves, el conjunto de resultados tiene al menos una fila. Para los cursores dinmicos, el conjunto de resultados puede tener cero, una o ms filas.

Variable de cursor
El cursor asignado a esta variable est abierto. Para los cursores INSENSITIVE y de conjunto de claves, el conjunto de resultados tiene al menos una fila. Para los cursores dinmicos, el conjunto de resultados puede tener cero, una o ms filas.

El conjunto de resultados del cursor est vaco.*

El cursor asignado a esta variable est abierto, pero el conjunto de resultados est definitivamente vaco.*

-1

El cursor est cerrado.

El cursor asignado a esta variable est cerrado.

-2

No aplicable.

Puede ser: El procedimiento llamado anteriormente no ha asignado ningn cursor a esta variable OUTPUT. El procedimiento llamado anteriormente asign un cursor a esta variable OUTPUT, pero se encontraba en un estado cerrado al terminar el procedimiento. Por tanto, se cancela la asignacin del cursor y no se devuelve al procedimiento que hace la llamada. No hay ningn cursor asignado a una variable declarada de cursor.

-3

No existe ningn cursor con el nombre indicado.

No existe una variable de cursor con el nombre indicado o, si existe, no tiene todava ningn cursor asignado.

*Los cursores dinmicos no devuelven nunca este resultado.

Ejemplos

En el ejemplo siguiente, se usa la funcin CURSOR_STATUS para mostrar el estado de un cursor antes y despus de abrirlo y cerrarlo.

CREATE TABLE #TMP ( ii int ) GO

INSERT INTO #TMP(ii) VALUES(1) INSERT INTO #TMP(ii) VALUES(2) INSERT INTO #TMP(ii) VALUES(3)

GO

--Create a cursor. DECLARE cur CURSOR FOR SELECT * FROM #TMP

--Display the status of the cursor before and after opening --closing the cursor.

SELECT CURSOR_STATUS('global','cur') AS 'After declare' OPEN cur SELECT CURSOR_STATUS('global','cur') AS 'After Open' CLOSE cur SELECT CURSOR_STATUS('global','cur') AS 'After Close'

--Remove the cursor.

DEALLOCATE cur

--Drop the table. DROP TABLE #TMP

El conjunto de resultados es el siguiente. After declare ---------------1 After Open ---------1 After Close -----------1

@@FETCH_STATUS (Transact-SQL)
Devuelve el estado de la ltima instruccin FETCH de cursor emitida para cualquier cursor abierto en ese momento por la conexin.

@@FETCH_STATUS

Tipo devuelto

integer

Valor devuelto

Valor devuelto
0

Descripcin
La instruccin FETCH se ejecut correctamente.

-1

La instruccin FETCH no se ejecut correctamente o la fila estaba ms all del conjunto de resultados.

-2

Falta la fila capturada.

Comentarios

Al ser @@FETCH_STATUS global para todos los cursores de una conexin, debe usarse con cuidado. Despus de ejecutar una instruccin FETCH, la comprobacin de @@FETCH_STATUS se debe realizar antes de que se ejecute otra instruccin FETCH sobre otro cursor. El valor de @@FETCH_STATUS no est definido antes de producirse las capturas en la conexin. Por ejemplo, supongamos que un usuario ejecuta una instruccin FETCH sobre un cursor y a continuacin llama a un procedimiento almacenado que abre y procesa los resultados de otro cursor. Cuando vuelve el control desde el procedimiento almacenado llamado, @@FETCH_STATUS reflejar la ltima instruccin FETCH ejecutada en el procedimiento almacenado, no la ejecutada antes de llamar al procedimiento. Para recuperar el ltimo estado capturado de un cursor especfico, realice una consulta en la columna fetch_status de la funcin de administracin dinmica sys.dm_exec_cursors.

Ejemplos

En el ejemplo siguiente se usa @@FETCH_STATUS para controlar las actividades del cursor en un bucle WHILE.

DECLARE Employee_Cursor CURSOR FOR SELECT BusinessEntityID, JobTitle FROM AdventureWorks2008R2.HumanResources.Employee; OPEN Employee_Cursor; FETCH NEXT FROM Employee_Cursor; WHILE @@FETCH_STATUS = 0 BEGIN FETCH NEXT FROM Employee_Cursor;

END; CLOSE Employee_Cursor; DEALLOCATE Employee_Cursor; GO

sp_cursor_list (Transact-SQL)
sp_cursor_list [ @cursor_return = ] cursor_variable_name OUTPUT , [ @cursor_scope = ] cursor_scope [;]

Arguments

[ @cursor_return= ] cursor_variable_nameOUTPUT Is the name of a declared cursor variable. cursor_variable_name is cursor, with no default. The cursor is a scrollable, dynamic, read-only cursor. [ @cursor_scope= ] cursor_scope Specifies the level of cursors to report. cursor_scope is int, with no default, and can be one of these values.

Value
1

Description
Report all local cursors.

Report all global cursors.

Report both local and global cursors.

Return Code Values

None

Cursors Returned

sp_cursor_list returns its report as a Transact-SQL cursor output parameter, not as a result set. This allows Transact-SQL batches, stored procedures, and triggers to work with the output one row at a time. It also means the procedure cannot be called directly from database API functions. The cursor output parameter must be bound to a program variable, but the database APIs do not support binding cursor parameters or variables. This is the format of the cursor returned by sp_cursor_list. The format of the cursor is the same as the format returned by sp_describe_cursor.

Column name Data type

Description

reference_name sysname The name used to refer to the cursor. If the reference to the cursor was through the name given on a DECLARE CURSOR statement, the reference name is the same as cursor name. If the reference to the cursor was through a variable, the reference name is the name of the cursor variable.

cursor_name

sysname The name of the cursor from a DECLARE CURSOR statement. In SQL Server, if the cursor was created by setting a cursor variable to a cursor, cursor_name returns the name of the cursor variable. In previous releases, this output column returns a system-generated name.

cursor_scope

smallint

1 = LOCAL 2 = GLOBAL

status

smallint

The same values as reported by the CURSOR_STATUS system function: 1 = The cursor referenced by the cursor name or variable is open. If the cursor is insensitive, static, or keyset, it has at least one row. If the cursor is dynamic, the result set has zero or more rows. 0 = The cursor referenced by the cursor name or variable is open but has no rows. Dynamic cursors never return this value. -1 = The cursor referenced by the cursor name or variable is closed. -2 = Applies only to cursor variables. There is no cursor assigned to the variable. Possibly, an OUTPUT parameter assigned a cursor to the

variable, but the stored procedure closed the cursor before returning. -3 = A cursor or cursor variable with the specified name does not exist, or the cursor variable has not had a cursor allocated to it.

model

smallint

1 = Insensitive (or static) 2 = Keyset 3 = Dynamic 4 = Fast Forward

concurrency

smallint

1 = Read-only 2 = Scroll locks 3 = Optimistic

scrollable

smallint

0 = Forward-only 1 = Scrollable

open_status

smallint

0 = Closed 1 = Open

cursor_rows

int

The number of qualifying rows in the result set. For more information, see @@CURSOR_ROWS.

fetch_status

smallint

The status of the last fetch on this cursor. For more information, see @@FETCH_STATUS: 0 = Fetch successful. -1 = Fetch failed or is beyond the bounds of the cursor. -2 = The requested row is missing. -9 = There has been no fetch on the cursor.

column_count

smallint

The number of columns in the cursor result set.

row_count

smallint

The number of rows affected by the last operation on the cursor. For more information, see @@ROWCOUNT.

last_operation

smallint

The last operation performed on the cursor: 0 = No operations have been performed on the cursor. 1 = OPEN 2 = FETCH 3 = INSERT 4 = UPDATE 5 = DELETE 6 = CLOSE 7 = DEALLOCATE

cursor_handle

int

A unique value that identifies the cursor within the scope of the server.

Remarks

sp_cursor_list produces a list of the current server cursors opened by the connection and describes the attributes global to each cursor, such as the scrollability and updatability of the cursor. The cursors listed by sp_cursor_list include:

Transact-SQL server cursors. API server cursors opened by an ODBC application that is then called SQLSetCursorName to name the cursor.

Use sp_describe_cursor_columns for a description of the attributes of the result set returned by the cursor. Use sp_describe_cursor_tables for a report of the base tables referenced by the cursor. sp_describe_cursor reports the same information as sp_cursor_list, but only for a specified cursor.

Permissions

Execute permissions default to the public role.

Examples

The following example opens a global cursor and uses sp_cursor_list to report on the attributes of the cursor.

sp_describe_cursor (Transact-SQL)
Notifica los atributos de un cursor de servidor. Convenciones de sintaxis de Transact-SQL

sp_describe_cursor [ @cursor_return = ] output_cursor_variable OUTPUT { [ , [ @cursor_source = ] N'local' , [ @cursor_identity = ] N'local_cursor_name' ] | [ , [ @cursor_source = ] N'global' , [ @cursor_identity = ] N'global_cursor_name' ] | [ , [ @cursor_source = ] N'variable' , [ @cursor_identity = ] N'input_cursor_variable' ] } [;]

Argumentos

[ @cursor_return = ] output_cursor_variable OUTPUT Es el nombre de una variable de cursor declarada que recibir la salida del cursor. output_cursor_variable es de tipo cursor, no tiene valor predeterminado y no debe estar asociada a ningn cursor en el momento en el que se llama a sp_describe_cursor. El cursor devuelto es un cursor desplazable, dinmico y de slo lectura. [ @cursor_source = ] { N'local' | N'global' | N'variable' } Especifica si el cursor del que se informa est especificado con el nombre de un cursor local, un cursor global o una variable de cursor. El parmetro es de tipo nvarchar(30).

[ @cursor_identity = ] N'local_cursor_name' ] Es el nombre de un cursor creado por una instruccin DECLARE CURSOR que tiene la palabra clave LOCAL u obtuvo el valor predeterminado LOCAL. local_cursor_name es de tipo nvarchar(128). [ @cursor_identity = ] N'global_cursor_name' ] Es el nombre de un cursor creado por una instruccin DECLARE CURSOR que tiene la palabra clave GLOBAL u obtuvo el valor predeterminado GLOBAL. global_cursor_name es de tipo nvarchar(128). global_cursor_name tambin puede ser el nombre de un cursor de servidor API que se abri con una aplicacin ODBC y que, a continuacin, se denomin al llamar a SQLSetCursorName. [ @cursor_identity = ] N'input_cursor_variable' ] Es el nombre de una variable de cursor asociada a un cursor abierto. input_cursor_variable es de tipo nvarchar(128).

Valores de cdigo de retorno

Ninguno

Cursores devueltos

sp_describe_cursor encapsula su conjunto de resultados en un parmetro de salida de tipo cursor de Transact-SQL. Esto habilita a los lotes, procedimientos almacenados y desencadenadores de Transact-SQL para trabajar con la salida de fila en fila. Tambin significa que no se puede llamar al procedimiento directamente desde funciones de una API de base de datos. El parmetro de salida de tipo cursor debe estar enlazado a una variable del programa, pero las API de base de datos no admiten el enlace de parmetros o variables de cursor. En la siguiente tabla se muestra el formato del cursor devuelto por sp_describe_cursor. El formato del cursor es el mismo que el devuelto con sp_cursor_list.

Nombre de columna
reference_name

Tipo de datos
sysname

Descripcin
Nombre que se utiliza para hacer referencia al cursor. Si la referencia al cursor se realiz utilizando el nombre especificado en una instruccin DECLARE CURSOR, el nombre de referencia es el mismo que el nombre del cursor. Si la referencia al cursor se hizo utilizando una variable, el nombre de referencia es el de la

variable.

cursor_name

sysname

Nombre del cursor desde una instruccin DECLARE CURSOR. En SQL Server, si el cursor se cre estableciendo una variable de cursor como un cursor, cursor_name devuelve el nombre de la variable de cursor. En versiones anteriores de SQL Server, esta columna de salida devuelve un nombre generado por el sistema.

cursor_scope

tinyint

1 = LOCAL 2 = GLOBAL

status

int

Los mismos valores de los que inform la funcin del sistema CURSOR_STATUS: 1 = El cursor al que hace referencia el nombre del cursor o ?la variable est abierto. Si se trata de un cursor que no distingue, esttico o de conjunto de claves, el conjunto de resultados tiene una fila, como mnimo. Si el cursor es dinmico, el conjunto de resultados tiene cero o ms filas. 0 = El cursor al que hace referencia el nombre del cursor o la variable est abierto pero no tiene filas. Los cursores dinmicos nunca devuelven este valor. -1 = El cursor al que hace referencia el nombre del cursor o la variable est cerrado. -2 = Se aplica slo a variables de cursor. No hay ningn cursor asignado a la variable. Posiblemente, un parmetro OUTPUT asign un cursor a la variable pero el procedimiento almacenado cerr el cursor antes de devolver resultados. -3 = No existe un cursor o variable de cursor con el nombre especificado, o la variable del cursor no tiene todava un cursor asignado.

model

tinyint

1 = Sin distincin (o esttico) 2 = Conjunto de claves

3 = Dinmico 4 = Avance rpido

concurrency

tinyint

1 = Slo lectura 2 = Bloqueos de desplazamiento 3 = Optimista

scrollable

tinyint

0 = De slo avance 1 = Desplazable

open_status

tinyint

0 = Cerrado 1 = Abierto

cursor_rows

decimal(10,0) Nmero de filas certificadas en el conjunto de resultados. Para obtener ms informacin, vea @@CURSOR_ROWS (Transact-SQL).

fetch_status

smallint

Estado de la ltima captura de este cursor. Para obtener ms informacin, vea @@FETCH_STATUS (Transact-SQL). 0 = Captura correcta. -1 = Error en la captura o se sobrepasaron los lmites del cursor. -2 = Falta la fila solicitada. -9 = No se registr ninguna captura en el cursor.

column_count

smallint

Nmero de columnas del conjunto de resultados del cursor.

row_count

decimal(10,0) Nmero de filas afectadas por la ltima operacin del cursor. Para obtener ms informacin, vea @@ROWCOUNT (Transact-SQL).

last_operation

tinyint

ltima operacin realizada en el cursor: 0 = No se realiz ninguna operacin en el cursor. 1 = OPEN

2 = FETCH 3 = INSERT 4 = UPDATE 5 = DELETE 6 = CLOSE 7 = DEALLOCATE

cursor_handle

int

Valor nico del cursor dentro del mbito del servidor.

Comentarios

sp_describe_cursor describe los atributos globales de un cursor de servidor, como la posibilidad de desplazarlo y actualizarlo. Utilice sp_describe_cursor_columns para obtener una descripcin de los atributos del conjunto de resultados devuelto por el cursor. Utilice sp_describe_cursor_tables para obtener un informe de las tablas base a las que hace referencia el cursor. Para obtener un informe de los cursores de servidor de Transact-SQL visibles en la conexin, use sp_cursor_list. Una instruccin DECLARE CURSOR puede solicitar un tipo de cursor no compatible con la instruccin SELECT de SQL Server dentro de DECLARE CURSOR. SQL Server convierte implcitamente el cursor a un tipo de datos compatible con la instruccin SELECT. Si se especifica TYPE_WARNING en la instruccin DECLARE CURSOR, SQL Server enva a la aplicacin un mensaje informativo que indica que se ha completado una conversin. Entonces es posible llamar a sp_describe_cursor para determinar el tipo de cursor implementado.

Permisos

Debe pertenecer al rol public.

Ejemplos

En el ejemplo siguiente se abre un cursor global y se utiliza sp_describe_cursor para obtener un informe de los atributos del cursor. other Copiar

USE AdventureWorks2008R2;

GO -- Declare and open a global cursor. DECLARE abc CURSOR STATIC FOR SELECT LastName FROM Person.Person;

OPEN abc;

-- Declare a cursor variable to hold the cursor output variable -- from sp_describe_cursor. DECLARE @Report CURSOR;

-- Execute sp_describe_cursor into the cursor variable. EXEC master.dbo.sp_describe_cursor @cursor_return = @Report OUTPUT, @cursor_source = N'global', @cursor_identity = N'abc';

-- Fetch all the rows from the sp_describe_cursor output cursor. FETCH NEXT from @Report; WHILE (@@FETCH_STATUS <> -1) BEGIN FETCH NEXT from @Report; END

-- Close and deallocate the cursor from sp_describe_cursor. CLOSE @Report; DEALLOCATE @Report; GO

-- Close and deallocate the original cursor. CLOSE abc;

DEALLOCATE abc; GO

sp_describe_cursor_columns (Transact-SQL)
sp_describe_cursor_columns [ @cursor_return = ] output_cursor_variable OUTPUT { [ , [ @cursor_source = ] N'local' , [ @cursor_identity = ] N'local_cursor_name' ] | [ , [ @cursor_source = ] N'global' , [ @cursor_identity = ] N'global_cursor_name' ] | [ , [ @cursor_source = ] N'variable' , [ @cursor_identity = ] N'input_cursor_variable' ] }

Arguments

[ @cursor_return= ] output_cursor_variable OUTPUT Is the name of a declared cursor variable to receive the cursor output. output_cursor_variable is cursor, with no default, and must not be associated with any cursors at the time sp_describe_cursor_columns is called. The cursor returned is a scrollable, dynamic, read-only cursor. [ @cursor_source= ] { N'local' | N'global' | N'variable' } Specifies whether the cursor being reported on is specified by using the name of a local cursor, a global cursor, or a cursor variable. The parameter is nvarchar(30). [ @cursor_identity= ] N'local_cursor_name' Is the name of a cursor created by a DECLARE CURSOR statement that either has the LOCAL keyword or that defaulted to LOCAL. local_cursor_name is nvarchar(128). [ @cursor_identity= ] N'global_cursor_name'

Is the name of a cursor created by a DECLARE CURSOR statement that either has the GLOBAL keyword or that defaulted to GLOBAL. global_cursor_name is nvarchar(128). global_cursor_name can also be the name of an API server cursor that is opened by an ODBC application and then named by calling SQLSetCursorName. [ @cursor_identity= ] N'input_cursor_variable' Is the name of a cursor variable associated with an open cursor. input_cursor_variable is nvarchar(128).

Return Code Values

None

Cursors Returned

sp_describe_cursor_columns encapsulates its report as a Transact-SQL cursor output parameter. This enables Transact-SQL batches, stored procedures, and triggers to work with the output one row at a time. This also means that the procedure cannot be called directly from database API functions. The cursor output parameter must be bound to a program variable, but the database APIs do not support binding cursor parameters or variables. The following table shows the format of the cursor returned by using sp_describe_cursor_columns.

Column name
column_name

Data type
sysname (nullable)

Description
Name assigned to the result set column. The column is NULL if the column was specified without an accompanying AS clause.

ordinal_position

int

Relative position of the column from the leftmost column in the result set. The first column is in position 0.

column_characteristics_flags int

A bitmask that indicates the information stored in DBCOLUMNFLAGS in OLE DB. Can be one or a combination of the following: 1 = Bookmark 2 = Fixed length

4 = Nullable 8 = Row versioning 16 = Updatable column (set for projected columns of a cursor that has no FOR UPDATE clause and, if there is such a column, can be only one per cursor). When bit values are combined, the characteristics of the combined bit values apply. For example, if the bit value is 6, the column is a fixed-length (2), nullable (4) column.

column_size

int

Maximum possible size for a value in this column.

data_type_sql

smallint

Number that indicates the SQL Server data type of the column.

column_precision

tinyint

Maximum precision of the column as per the bPrecision value in OLE DB.

column_scale

tinyint

Number of digits to the right of the decimal point for the numeric or decimal data types as per the bScale value in OLE DB.

order_position

int

If the column participates in the ordering of the result set, the position of the column in the order key relative to the leftmost column.

order_direction

varchar(1) (nullable)

A = The column is in the order key and the ordering is ascending. D = The column is in the order key and the ordering is descending. NULL = The column does not participate in ordering.

hidden_column

smallint

0 = this column appears in the select list. 1 = Reserved for future use.

columnid

int

Column ID of the base column. If the result set column was built from an expression, columnid is -1.

objectid

int

Object ID of the object or base table that is supplying the column. If the result set column was built from an expression, objectid is -1.

dbid

int

ID of the database that contains the base table that is supplying the column. If the result set column was built from an expression, dbid is -1.

dbname

sysname (nullable)

Name of the database that contains the base table that is supplying the column. If the result set column was built from an expression, dbname is NULL.

Remarks

sp_describe_cursor_columns describes the attributes of the columns in the result set of a server cursor, such as the name and data type of each cursor. Use sp_describe_cursor for a description of the global attributes of the server cursor. Use sp_describe_cursor_tables for a report of the base tables referenced by the cursor. To obtain a report of the Transact-SQL server cursors visible on the connection, use sp_cursor_list.

Permissions

Requires membership in the public role.

Examples

The following example opens a global cursor and uses sp_describe_cursor_columns to report on the columns used in the cursor. other Copy

USE AdventureWorks2008R2;

GO -- Declare and open a global cursor. DECLARE abc CURSOR KEYSET FOR SELECT LastName FROM Person.Person; GO OPEN abc;

-- Declare a cursor variable to hold the cursor output variable -- from sp_describe_cursor_columns. DECLARE @Report CURSOR;

-- Execute sp_describe_cursor_columns into the cursor variable. EXEC master.dbo.sp_describe_cursor_columns @cursor_return = @Report OUTPUT ,@cursor_source = N'global' ,@cursor_identity = N'abc';

-- Fetch all the rows from the sp_describe_cursor_columns output cursor. FETCH NEXT from @Report; WHILE (@@FETCH_STATUS <> -1) BEGIN FETCH NEXT from @Report; END

-- Close and deallocate the cursor from sp_describe_cursor_columns. CLOSE @Report; DEALLOCATE @Report; GO -- Close and deallocate the original cursor.

CLOSE abc; DEALLOCATE abc; GO

sp_describe_cursor_tables (Transact-SQL)
sp_describe_cursor_tables [ @cursor_return = ] output_cursor_variable OUTPUT { [ , [ @cursor_source = ] N'local' , [@cursor_identity = ] N'local_cursor_name' ] | [ , [ @cursor_source = ] N'global' , [ @cursor_identity = ] N'global_cursor_name' ] | [ , [ @cursor_source = ] N'variable' , [ @cursor_identity = ] N'input_cursor_variable' ] }

Arguments

[ @cursor_return = ] output_cursor_variable OUTPUT Is the name of a declared cursor variable to receive the cursor output. output_cursor_variable is cursor, with no default, and must not be associated with any cursors at the time sp_describe_cursor_tables is called. The cursor returned is a scrollable, dynamic, read-only cursor. [ @cursor_source = ] { N'local'| N'global' | N'variable' } Specifies whether the cursor being reported on is specified by using the name of a local cursor, a global cursor, or a cursor variable. The parameter is nvarchar(30). [ @cursor_identity = ] N'local_cursor_name' Is the name of a cursor created by a DECLARE CURSOR statement either having the LOCAL keyword, or that defaulted to LOCAL. local_cursor_name is nvarchar(128). [ @cursor_identity = ] N'global_cursor_name'

Is the name of a cursor created by a DECLARE CURSOR statement either having the GLOBAL keyword, or that defaulted to GLOBAL. global_cursor_name can also be the name of an API server cursor opened by an ODBC application that then named the cursor by calling SQLSetCursorName.global_cursor_name is nvarchar(128). [ @cursor_identity = ] N'input_cursor_variable' Is the name of a cursor variable associated with an open cursor. input_cursor_variable is nvarchar(128).

Return Code Values

None

Remarks

sp_describe_cursor_tables describes the base tables that are referenced by a server cursor. For a description of the attributes of the result set returned by the cursor, use sp_describe_cursor_columns. For a description of the global characteristics of the cursor, such as its scrollability and updatability, use sp_describe_cursor. To obtain a report of the Transact-SQL server cursors that are visible on the connection, use sp_cursor_list.

Permissions

Requires membership in the public role.

Cursors Returned

sp_describe_cursor_tables encapsulates its report as a Transact-SQL cursor output parameter. This enables Transact-SQL batches, stored procedures, and triggers to work with the output one row at a time. This also means that the procedure cannot be called directly from API functions. The cursor output parameter must be bound to a program variable, but the APIs do not support bind cursor parameters or variables. The following table shows the format of the cursor that is returned by sp_describe_cursor_tables.

Column name
table owner

Data type Description


sysname User ID of the table owner.

Table_name

sysname

Name of the object or base table. In SQL Server 2005, server cursors always return the user-specified object, not the base tables. In SQL Server 2000, server cursors return the base tables, unless the view or function is created by using WITH VIEW_METADATA.

Optimizer_hints smallint

Bitmap that is made up of one or more of the following: 1 = Row-level locking (ROWLOCK) 4 = Page-level locking (PAGELOCK) 8 = Table lock (TABLOCK) 16 = Exclusive table lock (TABLOCKX) 32 = Update lock (UPDLOCK) 64 = No lock (NOLOCK) 128 = Fast first-row option (FASTFIRST) 4096 = Read repeatable semantic when used with DECLARE CURSOR (HOLDLOCK) When multiple options are supplied, the system uses the most restrictive. However, sp_describe_cursor_tables shows the flags that are specified in the query.

lock_type

smallint

Scroll-lock type requested either explicitly or implicitly for each base table that underlies this cursor. The value can be one of the following: 0 = None 1 = Shared 3 = Update

server_name

sysname, nullable

Name of the linked server that the table resides on. NULL when OPENQUERY or OPENROWSET are used.

Objectid

int

Object ID of the table. 0 when OPENQUERY or OPENROWSET are used.

dbid

int

ID of the database that the table resides in. 0 when OPENQUERY or OPENROWSET are used.

dbname

sysname, nullable

Name of the database that the table resides in. NULL when OPENQUERY or OPENROWSET are used.

Examples

The following example opens a global cursor and uses sp_describe_cursor_tables to report on the tables that are referenced by the cursor. other Copy

USE AdventureWorks GO -- Declare and open a global cursor. DECLARE abc CURSOR KEYSET FOR SELECT LastName FROM Person.Contact WHERE LastName LIKE 'S%'

OPEN abc GO -- Declare a cursor variable to hold the cursor output variable -- from sp_describe_cursor_tables. DECLARE @Report CURSOR

-- Execute sp_describe_cursor_tables into the cursor variable. EXEC master.dbo.sp_describe_cursor_tables @cursor_return = @Report OUTPUT, @cursor_source = N'global', @cursor_identity = N'abc'

-- Fetch all the rows from the sp_describe_cursor_tables output cursor. FETCH NEXT from @Report WHILE (@@FETCH_STATUS <> -1) BEGIN FETCH NEXT from @Report END

-- Close and deallocate the cursor from sp_describe_cursor_tables. CLOSE @Report DEALLOCATE @Report GO

-- Close and deallocate the original cursor. CLOSE abc DEALLOCATE abc GO

Você também pode gostar