Question

I have created a cte that produces a range of numbers.

What I would like to do is join on this table and do an insert with randomly selected values, this is all to produce test data.

The random portion of the insert would look something like this:

(SELECT TOP 1 Name FROM @Titles ORDER BY NEWID())

The problem is, when I do the insert and join on the CTE my results don't seem random at all? It always uses the same value from @Titles? (Also there are other tables too, like @Notes.

WITH MyCte AS
    (SELECT   MyCounter = 1
     UNION ALL
     SELECT   MyCounter + 1
     FROM     MyCte
     where    MyCounter < 100) 

INSERT INTO [MyTable]
           ( Title, Note )

    select (SELECT TOP 1 Name FROM @Titles ORDER BY NEWID()),
              (SELECT TOP 1 Note FROM @Notes ORDER BY NEWID())
            from mycte
Était-ce utile?

La solution

The reason why you're getting the same record 100 times is that SELECT TOP 1 Name FROM @Titles ORDER BY NEWID() is executed only once and then returned for each record in mycte.

You can use a good old loop to achieve what you want. You can use that with multiple tables. It doesn't matter how many records you have in your source tables (though you should have at least 1).

declare @count int = 100

while @count > 0
begin
    INSERT INTO [MyTable] ( Title )
    SELECT TOP 1 Name FROM @Titles ORDER BY NEWID()

    INSERT INTO [MyTable] ( Title )
    SELECT TOP 1 Note FROM @Notes ORDER BY NEWID()

    set @count = @count - 1
end

Autres conseils

As Szymon said in his answer that there is no need to use CTE to get random 100 record from a table. So apart from the answer given by Szymon, you can achieve the same using below query.

INSERT INTO [MyTable] ( Title )
    SELECT TOP 1 Name FROM @Titles ORDER BY NEWID()
Go 100

To Specify more than one table.

INSERT INTO [MyTable] ( Title, Note )
    SELECT (SELECT TOP 1 Name FROM @Titles ORDER BY NEWID()), 
           (SELECT TOP 1 Name FROM @Notes ORDER BY NEWID())
GO 100

and now check your result in MyTable table.

SELECT * FROM MyTable
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top