CREATE OR REPLACE FUNCTION monthname(arg TIMESTAMP)
RETURNS STRING
RETURN CASE EXTRACT(MONTH FROM arg)
WHEN 1 THEN 'Jan'
WHEN 2 THEN 'Feb'
WHEN 3 THEN 'Mar'
WHEN 4 THEN 'Apr'
WHEN 5 THEN 'May'
WHEN 6 THEN 'Jun'
WHEN 7 THEN 'Jul'
WHEN 8 THEN 'Aug'
WHEN 9 THEN 'Sep'
WHEN 10 THEN 'Oct'
WHEN 11 THEN 'Nov'
ELSE 'Dec' END;
OK
CREATE OR REPLACE FUNCTION dateadd(unit STRING, measure DECIMAL(10, 6), base TIMESTAMP)
RETURNS TIMESTAMP
RETURN CASE lower(unit)
WHEN 'year' THEN base + make_interval(measure)
WHEN 'month' THEN base + make_interval(0, measure)
WHEN 'day' THEN base + make_interval(0, 0, measure)
WHEN 'hour' THEN base + make_interval(0, 0, 0, measure)
WHEN 'minute' THEN base + make_interval(0, 0, 0, 0, measure)
WHEN 'second' THEN base + make_interval(0, 0, 0, 0, 0, measure)
END;
OK
-- Map an alpha-numeric digit in the VIN to numbers.
CREATE OR REPLACE FUNCTION validator.vin_digit -- If the function already exists replace it, the signature must match
(digit string COMMENT 'A single character 0..9, a..Z, A..Z') -- 0 or more parameters, optional comments
RETURNS integer -- This is a scalar function.
COMMENT 'Map alphanumeric digit to numeric digit' -- An optional decription of the function
LANGUAGE SQL -- FYI: LANGUAGE SQL is also the default
CONTAINS SQL -- FYI: The body contains a SQL expression, but does not READ SQL DATA
DETERMINISTIC -- FYI: The function returns the same result for a given set of arguments.
RETURN decode(upper(digit), -- A "simple" expression
'A',1,'B',2,'C',3,'D',4,'E',5,'F',6,'G',7,'H',8,
'J',1,'K',2,'L',3,'M',4,'N',5, 'P',7, 'R',9,
'S',2,'T',3,'U',4,'V',5,'W',6,'X',7,'Y',8,'Z',9,
digit::integer);
OK
-- Use the vin_digit() function above to compute the checksum.
-- The algorithm prescribes a weight to each position in the 17 digit VIN.
-- The weight is multiplied with the result of vin_digit() and then summed up.
CREATE OR REPLACE FUNCTION validator.vin_checksum
(vin string COMMENT 'A VIN')
RETURNS integer
COMMENT 'Computes the VIN checksum'
DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER -- FYI: A SQL UDF always executes using the definer's authorization
RETURN coalesce(nullif(mod((SELECT sum(vin_digit(substr(vin,pos,1)) -- The function invokes another SQL UDF
* mult) -- The function uses a scalar subquery but does not READ SQL DATA.
FROM VALUES( 1, 8), ( 2, 7), ( 3, 6),
( 4, 5), ( 5, 4), ( 6, 3),
( 7, 2), ( 8, 10), (10, 9),
(11, 8), (12, 7), (13, 6),
(14, 5), (15, 4), (16, 3),
(17, 2) AS t(pos, mult)),
11), 10)::string, 'X');
OK
SQL User-Defined Functions
Examples of SQL user-defined functions in Databricks Runtime. For more details, see CREATE FUNCTION (SQL).