How to write a foreach in SQL Server?

后端 未结 10 2168
没有蜡笔的小新
没有蜡笔的小新 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:11

    This generally (almost always) performs better than a cursor and is simpler:

        DECLARE @PractitionerList TABLE(PracticionerID INT)
        DECLARE @PractitionerID INT
    
        INSERT @PractitionerList(PracticionerID)
        SELECT PracticionerID
        FROM Practitioner
    
        WHILE(1 = 1)
        BEGIN
    
            SET @PracticionerID = NULL
            SELECT TOP(1) @PracticionerID = PracticionerID
            FROM @PractitionerList
    
            IF @PracticionerID IS NULL
                BREAK
    
            PRINT 'DO STUFF'
    
            DELETE TOP(1) FROM @PractitionerList
    
        END
    

提交回复
热议问题