Merging data in a single SQL table without a Cursor

后端 未结 4 1279
-上瘾入骨i
-上瘾入骨i 2021-01-31 19:51

I have a table with an ID column and another column with a number. One ID can have multiple numbers. For example

ID | Number
 1 |  25
 1 |  26
 1 |  30
 1 |  24
         


        
4条回答
  •  不要未来只要你来
    2021-01-31 20:48

    I'd suggest using a WHILE loop structure with a table variable instead of the cursor.

    For example,

    DECLARE @TableVariable TABLE
    (
        MyID int IDENTITY (1, 1) PRIMARY KEY NOT NULL,
        [ID] int,
        [Number] int
    )
    
    DECLARE @Count int, @Max int
    
    INSERT INTO @TableVariable (ID, Number)
    SELECT ID, Number
    FROM YourSourceTable
    
    SELECT @Count = 1, @Max = MAX(MyID)
    FROM @TableVariable
    
    WHILE @Count <= @Max
    BEGIN
    
        ...do your processing here...
    
    
        SET @Count = @Count + 1
    
    END
    

提交回复
热议问题