SQL Server loop - how do I loop through a set of records

前端 未结 8 1459
慢半拍i
慢半拍i 2020-11-28 17:54

how do I loop through a set of records from a select?

So say for example I have a few records that I wish to loop through and do something with each record. Here\'s

相关标签:
8条回答
  • 2020-11-28 18:37

    Just another approach if you are fine using temp tables.I have personally tested this and it will not cause any exception (even if temp table does not have any data.)

    CREATE TABLE #TempTable
    (
        ROWID int identity(1,1) primary key,
        HIERARCHY_ID_TO_UPDATE int,
    )
    
    --create some testing data
    --INSERT INTO #TempTable VALUES(1)
    --INSERT INTO #TempTable VALUES(2)
    --INSERT INTO #TempTable VALUES(4)
    --INSERT INTO #TempTable VALUES(6)
    --INSERT INTO #TempTable VALUES(8)
    
    DECLARE @MAXID INT, @Counter INT
    
    SET @COUNTER = 1
    SELECT @MAXID = COUNT(*) FROM #TempTable
    
    WHILE (@COUNTER <= @MAXID)
    BEGIN
        --DO THE PROCESSING HERE 
        SELECT @HIERARCHY_ID_TO_UPDATE = PT.HIERARCHY_ID_TO_UPDATE
        FROM #TempTable AS PT
        WHERE ROWID = @COUNTER
    
        SET @COUNTER = @COUNTER + 1
    END
    
    
    IF (OBJECT_ID('tempdb..#TempTable') IS NOT NULL)
    BEGIN
        DROP TABLE #TempTable
    END
    
    0 讨论(0)
  • 2020-11-28 18:41

    this way we can iterate into table data.

    DECLARE @_MinJobID INT
    DECLARE @_MaxJobID INT
    CREATE  TABLE #Temp (JobID INT)
    
    INSERT INTO #Temp SELECT * FROM DBO.STRINGTOTABLE(@JobID,',')
    SELECT @_MinJID = MIN(JobID),@_MaxJID = MAX(JobID)  FROM #Temp
    
        WHILE @_MinJID <= @_MaxJID
        BEGIN
    
            INSERT INTO Mytable        
            (        
                JobID,        
            )        
    
            VALUES        
            (        
                @_MinJobID,        
            ) 
    
            SET @_MinJID = @_MinJID + 1;
        END
    
    DROP TABLE #Temp
    

    STRINGTOTABLE is user define function which will parse comma separated data and return table. thanks

    0 讨论(0)
提交回复
热议问题