This custom UDF is added to return a datetimeoffset value that is changed from the stored time zone offset to a specified new time zone offset.
Custom UDF overloads
Parameters
source_timestamp: A TIMESTAMP_TZ that can be resolved to a datetimeoffset(n) value.
target_tz: A varchar that represents the time zone offset
CREATE OR REPLACE FUNCTION PUBLIC.SWITCHOFFSET_UDF(source_timestamp TIMESTAMP_TZ, target_tz varchar)RETURNS TIMESTAMP_TZLANGUAGE SQLCOMMENT='{"origin":"sf_sc","name":"snowconvert","version":{"major":1, "minor":0},"attributes":{"component":"udf"}}'AS$$WITH tz_values AS (SELECT RIGHT(source_timestamp::varchar, 5) as source_tz,REPLACE(source_tz::varchar, ':', '') as source_tz_clean,REPLACE(target_tz::varchar, ':', '') as target_tz_clean, target_tz_clean::integer- source_tz_clean::integeras offset, RIGHT(offset::varchar, 2) as tz_min, PUBLIC.OFFSET_FORMATTER(RTRIM(offset::varchar, tz_min)) as tz_hrs, TIMEADD( hours, tz_hrs::integer, source_timestamp ) as adj_hours, TIMEADD( minutes, (LEFT(tz_hrs, 1) || tz_min)::integer, adj_hours::timestamp_tz ) as new_timestampFROM DUAL)SELECT (LEFT(new_timestamp, 24) ||' '|| target_tz)::timestamp_tzFROM tz_values$$;-- ==========================================================================-- Description: The function OFFSET_FORMATTER(offset_hrs varchar) serves as-- an auxiliar function to format the offter hours and its prefix operator.-- ========================================================================== CREATE OR REPLACE FUNCTION PUBLIC.OFFSET_FORMATTER(offset_hrs varchar)RETURNS varcharLANGUAGE SQLCOMMENT='{"origin":"sf_sc","name":"snowconvert","version":{"major":1, "minor":0},"attributes":{"component":"udf"}}'AS$$CASEWHEN LEN(offset_hrs) =0THEN'+'||'0'||'0'WHEN LEN(offset_hrs) =1THEN'+'||'0'|| offset_hrsWHEN LEN(offset_hrs) =2THENCASEWHEN LEFT(offset_hrs, 1) ='-'THEN'-'||'0'|| RIGHT(offset_hrs, 1)ELSE'+'|| offset_hrsENDELSE offset_hrsEND$$;
SQL Server
IN -> SqlServer_01.sql
SELECT'1998-09-20 7:45:50.71345 +02:00'as fr_time,SWITCHOFFSET('1998-09-20 7:45:50.71345 +02:00', '-06:00') as cr_time;
SELECT
'1998-09-20 7:45:50.71345 +02:00' as fr_time,
SWITCHOFFSET('1998-09-20 7:45:50.71345 +02:00', '-06:00') as cr_time;
Snowflake
OUT -> SqlServer_01.sql
SELECT'1998-09-20 7:45:50.71345 +02:00'as fr_time, PUBLIC.SWITCHOFFSET_UDF('1998-09-20 7:45:50.71345 +02:00', '-06:00') as cr_time;