admin

如何使用T-SQL将十六进制颜色转换为RGB颜色

sql

如何使用T-SQL将十六进制颜色转换为RGB颜色


阅读 268

收藏
2021-07-01

共1个答案

admin

https://data.stackexchange.com/stackoverflow/query/4803/so3087921

DECLARE @temp AS TABLE (hex char(6))

INSERT  INTO @temp
VALUES  ('3333CC') -- Should convert to Red: 51 Green: 51 Blue: 204

DECLARE @table AS varchar(16)
SET @table = '0123456789abcdef' -- Assuming case-insensitive collation!

SELECT  hex
       ,16 * (CHARINDEX(SUBSTRING(hex, 1, 1), @table) - 1) + (CHARINDEX(SUBSTRING(hex, 2, 1), @table) - 1) AS R
       ,16 * (CHARINDEX(SUBSTRING(hex, 3, 1), @table) - 1) + (CHARINDEX(SUBSTRING(hex, 4, 1), @table) - 1) AS G
       ,16 * (CHARINDEX(SUBSTRING(hex, 5, 1), @table) - 1) + (CHARINDEX(SUBSTRING(hex, 6, 1), @table) - 1) AS B
FROM    @temp

https://dpatrickcaldwell.blogspot.com/2009/05/converting-hexadecimal-or-
binary-to.html中有一个通用函数

我通常尽可能地避免使用标量函数,因为有可能诱使自己认为可以为500万行调用标量UDF,而不会对内联表达式造成任何损失。

您还可以使用内联表值UDF:

CREATE FUNCTION dbo.udf_HexToRGB (@hex char(6))
RETURNS TABLE
AS RETURN
    (
     SELECT 16 * (CHARINDEX(SUBSTRING(@hex, 1, 1), '0123456789abcdef') - 1) + (CHARINDEX(SUBSTRING(@hex, 2, 1),
                                                                                         '0123456789abcdef') - 1) AS R
           ,16 * (CHARINDEX(SUBSTRING(@hex, 3, 1), '0123456789abcdef') - 1) + (CHARINDEX(SUBSTRING(@hex, 4, 1),
                                                                                         '0123456789abcdef') - 1) AS G
           ,16 * (CHARINDEX(SUBSTRING(@hex, 5, 1), '0123456789abcdef') - 1) + (CHARINDEX(SUBSTRING(@hex, 6, 1),
                                                                                         '0123456789abcdef') - 1) AS B
    )
GO

DECLARE @temp AS TABLE (hex char(6))

INSERT  INTO @temp 
VALUES  ('3333CC') -- Should convert to Red: 51 Green: 51 Blue: 204

SELECT  hex 
       ,R 
       ,G 
       ,B 
FROM    @temp
OUTER APPLY dbo.udf_HexToRGB(hex)
2021-07-01