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()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With