Procedure to insert randomly selected data from same table, to bottom of that table

  • I've simplified your product table a little to concoct this example because I'm too lazy to build the requisite DDL and consumable sample data exactly as you've shown.

    DECLARE @OldProducts TABLE

    (

    ProductID INT IDENTITY

    ,[Current] INT

    );

    DECLARE @NewProducts TABLE

    (

    ProductID INT

    ,[Current] INT

    );

    WITH Tally (n) AS

    (

    SELECT TOP 10 ROW_NUMBER() OVER (ORDER BY (SELECT NULL))

    FROM sys.all_columns

    )

    INSERT INTO @OldProducts

    SELECT 1

    FROM Tally;

    SELECT *

    FROM @OldProducts;

    WITH TwoProducts AS

    (

    SELECT TOP (2) ProductID, [Current]

    FROM @OldProducts

    WHERE [Current] = 1

    ORDER BY NEWID()

    )

    UPDATE TwoProducts

    SET [Current] = 0

    OUTPUT INSERTED.ProductID, 1

    INTO @NewProducts;

    SELECT *

    FROM @OldProducts;

    SELECT *

    FROM @NewProducts;

    If this doesn't give you the idea then let me know.


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St

  • thanks for that dwain.c.

    that helped a lot.

    manage to work on it and also add a few things to your solution.

    much appreciated.

Viewing 2 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply