Move block of data SQL

Leif Nyström 21 Reputation points
2020-12-04T11:34:58.69+00:00

I have a problem finding a good way of moving data in a table without using a while loop.
I need to move the data in the table one step ahead. See my SQL code. Looping trough the data with a while loop is too slow a process.
My question is, is it possible to move a block of data instead?

DECLARE @Counter int,  @popMen float, @CountLocal int, @maxLocal int

SET @Counter=110
SET @CountLocal=1
SELECT @maxLocal = Max(locaid) From population where (regiod=1)
WHILE (@CountLocal <= @maxLocal)
    BEGIN
        WHILE (@Counter >=0)
        BEGIN
            SELECT @popMen = popMen 
            from population where (regiod=1 AND locaid=@CountLocal AND age=@Counter)
            SET @Counter=@Counter-1
            SET @popMen=0
        END
        SET @CountLocal = @CountLocal + 1
        SET @Counter=110
    END
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,784 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,637 questions
{count} votes

Accepted answer
  1. Viorel 117.2K Reputation points
    2020-12-04T19:37:31.007+00:00

    Check if the next statement performs the same things:

    update p1
    set p1.popMen = p2.popMen,
        p1.popWoman = p2.popWoman
    from population p1
    inner join population p2 on p2.regiod = p1.regiod and p2.locaid = p1.locaid and p2.age = p1.age - 1
    where p1.regiod = 1
    

    Or maybe execute ‘update population set age += 1’, remove the last row (age 111) and insert the first one (age 0), or replace the whole last row (within groups).


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.