How random hex in sql?

This is a pretty complicated topic for me couse SQL is not the best skill;)

I have to insert random hex colors in the data string. How to do it? Can I create a function that will draw numbers?

+4
source share
5 answers
SET [Color] =  '#' +  CONVERT(VARCHAR(max), CRYPT_GEN_RANDOM(3), 2)
+9
source

This will give you six digit hexadecimal codes in MySQL

SELECT concat('#',SUBSTRING((lpad(hex(round(rand() * 10000000)),6,0)),-6))

Here is a great one that will give you incremental colors

SELECT *, 
       concat('#',SUBSTRING((lpad(hex(@curRow := @curRow + 10),6,0)),-6)) AS color 
FROM table 
       INNER JOIN (SELECT @curRow := 5426175) color_start_point
+5
source

, rand - https://dev.mysql.com/doc/refman/5.0/en/mathematical-functions.html#function_rand - i.e.

INSERT INTO ... VALUES ( ... , ROUND(RAND(255 * 255 * 255)), ...)
0
with cte1 as (
select round(round(rand(),1)*15,0) as hex1,
 round(round(rand(),1)*15,0) as hex2,
 round(round(rand(),1)*15,0) as hex3,
 round(round(rand(),1)*15,0) as hex4,
 round(round(rand(),1)*15,0) as hex5,
 round(round(rand(),1)*15,0) as hex6
),
cte2 as (
select case when hex1 = 10 then 'A' 
when hex1 = 11 then 'B'
when hex1 = 12 then 'C'
when hex1 = 13 then 'D'
when hex1 = 14 then 'E'
when hex1 = 15 then 'F'
else str(hex1) end as hex1h,
case when hex2 = 10 then 'A' 
when hex2 = 11 then 'B'
when hex2 = 12 then 'C'
when hex2 = 13 then 'D'
when hex2 = 14 then 'E'
when hex2 = 15 then 'F'
else str(hex2) end as hex2h,
case when hex3 = 10 then 'A' 
when hex3 = 11 then 'B'
when hex3 = 12 then 'C'
when hex3 = 13 then 'D'
when hex3 = 14 then 'E'
when hex3 = 15 then 'F'
else str(hex3) end as hex3h,
case when hex4 = 10 then 'A' 
when hex4 = 11 then 'B'
when hex4 = 12 then 'C'
when hex4 = 13 then 'D'
when hex4 = 14 then 'E'
when hex4 = 15 then 'F'
else str(hex4) end as hex4h,
case when hex5 = 10 then 'A' 
when hex5 = 11 then 'B'
when hex5 = 12 then 'C'
when hex5 = 13 then 'D'
when hex5 = 14 then 'E'
when hex5 = 15 then 'F'
else str(hex5) end as hex5h,
case when hex6 = 10 then 'A' 
when hex6 = 11 then 'B'
when hex6 = 12 then 'C'
when hex6 = 13 then 'D'
when hex6 = 14 then 'E'
when hex6 = 15 then 'F'
else str(hex6) end as hex6h from cte1)

select '#'+ltrim(hex1h)+ltrim(hex2h)+ltrim(hex3h)+ltrim(hex4h)+ltrim(hex5h)+ltrim(hex6h) from cte2
0

:

SELECT '#' +  CONVERT(VARCHAR(MAX), CRYPT_GEN_RANDOM(3), 2) AS Color
0

Source: https://habr.com/ru/post/1530834/


All Articles