我正在使用SQL Server 2014,并希望利用新功能CHOOSE和RAND.基本上想从列表中返回随机颜色.
就像是:
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
可能吗?
你必须在下面使用RAND
+ ROUND
来获得从1到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
为了更准确,您可以使用CEILING
@GarethD评论如下:
DECLARE @num INT = CEILING(RAND()*29)
工作 SQL-FIDDLE
您没有提到您知道这一点,如果您不知道这种情况,我会再给您一个解决方案:
SELECT TOP 1 v FROM(VALUES('bg-blue'), ('bg-blue-madison'), ('bg-blue-hoki'))t(v) ORDER BY NEWID()