-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdbo.udf_hex_diff.sql
More file actions
71 lines (59 loc) · 4.27 KB
/
Copy pathdbo.udf_hex_diff.sql
File metadata and controls
71 lines (59 loc) · 4.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
USE [NBA]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*------------------------------------------------------------------------------
Function Name: [dbo].[udf_hex_diff]
Purpose: Calculates the Euclidean distance between two hex color values in RGB space
Project: T-SQL-Scripts
Date Created: 2025-10-14
Author: Ludwig Mark
Parameters:
@hexa - CHAR(5) - First hex color value
@hexb - CHAR(5) - Second hex color value to compare
Returns: DECIMAL(18, 10)
Notes:
- Converts hex colors to RGB using udtf_hex_torgb
- Uses Euclidean distance formula: sqrt((R1-R2)² + (G1-G2)² + (B1-B2)²)
- Result represents perceptual color difference
- Thread-safe and deterministic
- Higher values indicate greater color difference
Performance:
- Execution time: Constant time O(1)
- Memory usage: Minimal
- Single table function call per color
Dependencies:
- Requires dbo.udtf_hex_torgb function
- Hex values must be valid color codes
Example:
------------------------
DECLARE @Color1 CHAR(5) = '#FFF' -- White
DECLARE @Color2 CHAR(5) = '#000' -- Black
SELECT dbo.udf_hex_diff(@Color1, @Color2) AS ColorDistance
Returns: 441.67295593 (maximum possible difference)
Modification History:
Date Author Description
---------- ---------- ------------------------------------------------
2025-10-14 Ludwig M. Initial creation
Validation:
- Returns NULL if either input is NULL
- Accepts 3 or 6 character hex codes (with #)
- Result range: 0 (identical) to 441.67... (max diff)
- Handles invalid hex values gracefully
LICENSE: MIT
------------------------------------------------------------------------------*/
CREATE FUNCTION [dbo].[udf_hex_diff] (@hexa CHAR(5), @hexb CHAR(5))
RETURNS DECIMAL(18, 10)
AS
BEGIN
RETURN (
SELECT SQRT((X.R-Y.R)*(X.R-Y.R) +
(X.G-Y.G)*(X.G-Y.G) +
(X.B-Y.B)*(X.B-Y.B))
FROM dbo.udtf_hex_torgb(@hexa) X
OUTER APPLY dbo.udtf_hex_torgb(@hexb) Y
)
END
GO