Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return random value from the list

I'm using SQL Server 2014, and would like to take advantage of new function CHOOSE and RAND. Basically would like to return random color from the list.

Something like:

Select CHOOSE(RAND(29), 'bg-blue', 'bg-blue-madison', 'bg-blue-hoki', 'bg-blue-steel', 'bg-blue-chambray',
                    'bg-green-meadow', 'bg-green', 'bg-green-seagreen', 'bg-green-turquoise', 'bg-green-haze', 'bg-green-jungle',
                    'bg-red', 'bg-red-pink', 'bg-red-sunglo', 'bg-red-intense', 'bg-red-thunderbird', 'bg-red-flamingo',
                    'bg-yellow', 'bg-yellow-gold', 'bg-yellow-casablanca', 'bg-yellow-lemon',
                    'bg-purple', 'bg-purple-plum', 'bg-purple-studio', 'bg-purple-seance',
                    'bg-grey-cascade', 'bg-grey-silver', 'bg-grey-steel', 'bg-grey-gallery') AS Colour

Is it possible?

like image 593
Whistler Avatar asked Dec 21 '15 14:12

Whistler


2 Answers

You didn't mention that you know this and I will give you one more solution in case you don't know this way:

SELECT TOP 1 v FROM(VALUES('bg-blue'), ('bg-blue-madison'), ('bg-blue-hoki'))t(v)
ORDER BY NEWID()
like image 160
Giorgi Nakeuri Avatar answered Sep 28 '22 04:09

Giorgi Nakeuri


You have to use RAND + ROUND in following to get integers from 1 up to 29:

DECLARE @num INT = ROUND(RAND()*28,0) + 1

SELECT CHOOSE(@num, 'bg-blue', 'bg-blue-madison', 'bg-blue-hoki', 'bg-blue-steel', 'bg-blue-chambray',
                    'bg-green-meadow', 'bg-green', 'bg-green-seagreen', 'bg-green-turquoise', 'bg-green-haze', 'bg-green-jungle',
                    'bg-red', 'bg-red-pink', 'bg-red-sunglo', 'bg-red-intense', 'bg-red-thunderbird', 'bg-red-flamingo',
                    'bg-yellow', 'bg-yellow-gold', 'bg-yellow-casablanca', 'bg-yellow-lemon',
                    'bg-purple', 'bg-purple-plum', 'bg-purple-studio', 'bg-purple-seance',
                    'bg-grey-cascade', 'bg-grey-silver', 'bg-grey-steel', 'bg-grey-gallery') AS Test

To be more accurate you can use CEILING as @GarethD commented in following:

DECLARE @num INT = CEILING(RAND()*29)

Working SQL-FIDDLE

like image 41
Stanislovas Kalašnikovas Avatar answered Sep 28 '22 03:09

Stanislovas Kalašnikovas