开发者

SQL OUTER JOIN with NEWID to generate random data for each row

I want to generate some test data so for each row in a table I want to insert 10 random rows in another, see below:

INSERT INTO CarFeatures 
  (carID, featureID)
SELECT C.ID, F.ID
  FROM dbo.Cars AS C
OUTER APPLY开发者_StackOverflow社区 (
     SELECT TOP 10 ID
       FROM dbo.Features
   ORDER BY NEWID()
) AS F

Only trouble is this returns the same values for each row. How do I order them randomly?


What i usually do is create a temp table and define the PK as a GUID with the default value of newid(). You'll need a create table statement for this, no select into. Then I insert my records into it and then I can order by the Id field and select the top ten.


The problem is that any function you call will be evaluated only once. How about something like this:

SELECT ID, NEWID() AS guid
INTO #temp
FROM dbo.Features

INSERT INTO CarFeatures (carID, featureID) 
SELECT C.ID, F.ID 
FROM dbo.Cars AS C 
OUTER APPLY ( 
SELECT TOP 10 *
FROM #temp
ORDER BY 2
) AS F 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜