How to write a foreach in SQL Server?

后端 未结 10 2162
没有蜡笔的小新
没有蜡笔的小新 2020-12-12 08:39

I am trying to achieve something along the lines of a for-each, where I would like to take the Ids of a returned select statement and use each of them.

DECLAR         


        
10条回答
  •  青春惊慌失措
    2020-12-12 09:21

    You seem to want to use a CURSOR. Though most of the times it's best to use a set based solution, there are some times where a CURSOR is the best solution. Without knowing more about your real problem, we can't help you more than that:

    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
    

提交回复
热议问题