Sqlserver
 sql >> Base de données >  >> RDS >> Sqlserver

Comment écrire un foreach dans SQL Server ?

Vous semblez vouloir utiliser un CURSOR . Bien que la plupart du temps, il soit préférable d'utiliser une solution basée sur un ensemble, il arrive parfois qu'un CURSOR est la meilleure solution. Sans en savoir plus sur votre véritable problème, nous ne pouvons pas vous aider plus que cela :

DECLARE @PractitionerId int

DECLARE MY_CURSOR CURSOR 
  LOCAL STATIC READ_ONLY FORWARD_ONLY
FOR 
SELECT DISTINCT PractitionerId 
FROM Practitioner

OPEN MY_CURSOR
FETCH NEXT FROM MY_CURSOR INTO @PractitionerId
WHILE @@FETCH_STATUS = 0
BEGIN 
    --Do something with Id here
    PRINT @PractitionerId
    FETCH NEXT FROM MY_CURSOR INTO @PractitionerId
END
CLOSE MY_CURSOR
DEALLOCATE MY_CURSOR