我有一个记录表,每个记录都存储一个颜色名称。 e.g:
Product | Colour
-------------------
Product A | Blue
Product B | Black
我添加了3个新列:R,G& B.如何使用单个SQL查询将颜色转换为RGB值?
答案 0 :(得分:3)
;with Colours(Name, R, G, B) as
(
select 'White', 255, 255, 255 union all
select 'Silver', 192, 192, 192 union all
select 'Gray', 128, 128, 128 union all
select 'Black', 0 , 0 , 0 union all
select 'Red', 255, 0 , 0 union all
select 'Maroon', 128, 0 , 0 union all
select 'Yellow', 255, 255, 0 union all
select 'Olive', 128, 128, 0 union all
select 'Lime', 0 , 255, 0 union all
select 'Green', 0 , 128, 0 union all
select 'Aqua', 0 , 255, 255 union all
select 'Teal', 0 , 128, 128 union all
select 'Blue', 0 , 0 , 255 union all
select 'Navy', 0 , 0 , 128 union all
select 'Fuchsia', 255, 0 , 255 union all
select 'Purple', 128, 0 , 128
)
update P set
R = C.R,
G = C.G,
B = C.B
from products as P
inner join Colours as C
on P.Colour = C.Name
答案 1 :(得分:2)
您需要自己添加相应名称的RGB值,无法从颜色名称中获取该信息(毕竟是什么构成“深蓝色”?)。
您可以使用CSS names提示来构建初始查找表。
答案 2 :(得分:1)
您需要在用于更新表的同一查询中将颜色解码为RGB值。虽然您没有使用任何函数,变量或其他表,但可以使用CASE表达式来完成。这不是优雅的解决方案,但它会起作用。
UPDATE products
SET
r = (CASE colour
WHEN 'Black' THEN 0
WHEN 'Red' THEN 255
WHEN 'Green' THEN 0
WHEN 'Blue' THEN 0
WHEN 'White' THEN 255
ELSE NULL
END),
g = (CASE colour
WHEN 'Black' THEN 0
WHEN 'Red' THEN 0
WHEN 'Green' THEN 255
WHEN 'Blue' THEN 0
WHEN 'White' THEN 255
ELSE NULL
END),
b = (CASE colour
WHEN 'Black' THEN 0
WHEN 'Red' THEN 0
WHEN 'Green' THEN 0
WHEN 'Blue' THEN 255
WHEN 'White' THEN 255
ELSE NULL
END)
或者可能以下列方式:
UPDATE products
SET
r = (CASE
WHEN Colour IN ('Black', 'Green', 'Blue') THEN 0
WHEN Colour IN ('Red', 'White') THEN 255
ELSE NULL
END),
g = (CASE
WHEN Colour IN ('Black', 'Red', 'Blue') THEN 0
WHEN Colour IN ('Green', 'White') THEN 255
ELSE NULL
END),
b = (CASE
WHEN Colour IN ('Black', 'Red', 'Green') THEN 0
WHEN Colour IN ('Blue', 'White') THEN 255
ELSE NULL
END)