5

Possible Duplicate:
Simple update statement so that all rows are assigned a different value

Is there a way to pick a random value (like a color) from a subquery? here is what I tried but getting the same value on every run:

SELECT TOP (100) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS ID,--Sequential number from 1 to ..
                 (SELECT TOP 1 color
                  FROM   ( VALUES (0, 'Red'),
                                  (1, 'Green'),
                                  (2, 'Yellow') ) colors(id, color)
                  ORDER  BY NEWID() )                        AS RandomColor
FROM   sys.all_columns ac1
       CROSS JOIN sys.all_columns ac2 

but if I run this piece alone, I am getting different colors:

SELECT TOP 1 color
FROM   ( VALUES (0, 'Red'),
                (1, 'Green'),
                (2, 'Yellow') ) colors(id, color)
ORDER  BY NEWID() 
Community
  • 1
  • 1
mishkin
  • 5,932
  • 8
  • 45
  • 64
  • 1
    You need to make the subquery correlated so that it is re-evaluated for each row. `WHERE COALESCE(ac1.object_id, ac2.object_id, ac1.column_id, ac2.column_id) IS NOT NULL ORDER BY NEWID()` seems to do it for me. – Martin Smith Dec 17 '12 at 10:58

1 Answers1

3

Something like this perhaps

select ac1.ID, r.color from
(SELECT TOP (100)
-- changed because it didn't work in mssql 2012
--ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) as ID,
ROW_NUMBER() OVER (ORDER BY newid()) as ID,
ROW_NUMBER() OVER (ORDER BY newid()) as dummy
FROM sys.all_columns
order by id
) ac1
cross apply
(SELECT top 1 color FROM ( VALUES (0,'Red'),(1,'Green'),(2,'Yellow') ) colors(id,color) 
where id = dummy % 3
) r
t-clausen.dk
  • 43,517
  • 12
  • 59
  • 92