Recherche…


Syntaxe

  • DECLARE nom_curseur CURSOR [LOCAL | GLOBAL ]
    • [FORWARD_ONLY | FAIRE DÉFILER ]
      [STATIQUE | KEYSET | DYNAMIQUE | AVANCE RAPIDE ]
      [READ_ONLY | SCROLL_LOCKS | OPTIMISTIQUE]
      [TYPE_WARNING]
    • FOR select_statement
    • [FOR UPDATE [OF nom_colonne [, ... n]]]

Remarques

Normalement, vous voudriez éviter d'utiliser des curseurs car ils peuvent avoir un impact négatif sur les performances. Cependant, dans certains cas particuliers, vous devrez peut-être parcourir votre enregistrement de données par enregistrement et effectuer certaines actions.

Curseur de base seulement

Normalement, vous voudriez éviter d'utiliser des curseurs car ils peuvent avoir un impact négatif sur les performances. Cependant, dans certains cas particuliers, vous devrez peut-être parcourir votre enregistrement de données par enregistrement et effectuer certaines actions.

DECLARE @orderId AS INT

-- here we are creating our cursor, as a local cursor and only allowing 
-- forward operations
DECLARE rowCursor CURSOR LOCAL FAST_FORWARD FOR
    -- this is the query that we want to loop through record by record
    SELECT [OrderId]
    FROM [dbo].[Orders]

-- first we need to open the cursor
OPEN rowCursor

-- now we will initialize the cursor by pulling the first row of data, in this example the [OrderId] column,
-- and storing the value into a variable called @orderId
FETCH NEXT FROM rowCursor INTO @orderId

-- start our loop and keep going until we have no more records to loop through
WHILE @@FETCH_STATUS = 0 
BEGIN

    PRINT @orderId
    
    -- this is important, as it tells SQL Server to get the next record and store the [OrderId] column value into the @orderId variable
    FETCH NEXT FROM rowCursor INTO @orderId

END

-- this will release any memory used by the cursor
CLOSE rowCursor
DEALLOCATE rowCursor

Syntaxe du curseur rudimentaire

Une syntaxe de curseur simple, fonctionnant sur quelques exemples de lignes de test:

/* Prepare test data */
DECLARE @test_table TABLE
(
    Id INT,
    Val VARCHAR(100)
);
INSERT INTO @test_table(Id, Val)
VALUES 
    (1, 'Foo'), 
    (2, 'Bar'), 
    (3, 'Baz');
/* Test data prepared */

/* Iterator variable @myId, for example sake */
DECLARE @myId INT;

/* Cursor to iterate rows and assign values to variables */
DECLARE myCursor CURSOR FOR
    SELECT Id
    FROM @test_table;

/* Start iterating rows */
OPEN myCursor;
FETCH NEXT FROM myCursor INTO @myId;

/* @@FETCH_STATUS global variable will be 1 / true until there are no more rows to fetch */
WHILE @@FETCH_STATUS = 0
BEGIN

    /* Write operations to perform in a loop here. Simple SELECT used for example */
    SELECT Id, Val
    FROM @test_table 
    WHERE Id = @myId;

    /* Set variable(s) to the next value returned from iterator; this is needed otherwise the cursor will loop infinitely. */
    FETCH NEXT FROM myCursor INTO @myId;
END
/* After all is done, clean up */
CLOSE myCursor;
DEALLOCATE myCursor;

Résultats du SSMS. Notez que ce sont toutes des requêtes séparées, elles ne sont en aucun cas unifiées. Notez que le moteur de requête traite chaque itération une par une au lieu d'un ensemble.

Id Val
1 Foo
(1 rang (s) affecté (s))
Id Val
2 Bar
(1 rang (s) affecté (s))
Id Val
3 Baz
(1 rang (s) affecté (s))


Modified text is an extract of the original Stack Overflow Documentation
Sous licence CC BY-SA 3.0
Non affilié à Stack Overflow