A user-defined function is a Transact-SQL or common language runtime (CLR) routine that accepts parameters, performs an action, such as a complex calculation, and returns the result of that action as a value. The return value can either be a scalar (single) value or a table. (Transact-SQL Language Reference CREATE FUNCTION)
Scalar Function Syntax
CREATE [ OR ALTER ] FUNCTION [ schema_name. ] function_name( [ { @parameter_name [ AS ][ type_schema_name. ] parameter_data_type [ NULL ] [ = default ] [ READONLY ] } [ ,...n ] ])RETURNS return_data_type [ WITH <function_option> [ ,...n ] ] [ AS ]BEGIN function_bodyRETURN scalar_expressionEND[ ; ]
Inline Table-Valued Function Syntax
CREATE [ OR ALTER ] FUNCTION [ schema_name. ] function_name( [ { @parameter_name [ AS ] [ type_schema_name. ] parameter_data_type [ NULL ] [ = default ] [ READONLY ] } [ ,...n ] ])RETURNSTABLE [ WITH <function_option> [ ,...n ] ] [ AS ]RETURN [ ( ] select_stmt [ ) ][ ; ]
Multi-Statement Table-Valued Function Syntax
CREATE [ OR ALTER ] FUNCTION [ schema_name. ] function_name( [ { @parameter_name [ AS ] [ type_schema_name. ] parameter_data_type [ NULL ] [ = default ] [READONLY] } [ ,...n ] ])RETURNS @return_variable TABLE<table_type_definition> [ WITH <function_option> [ ,...n ] ] [ AS ]BEGIN function_bodyRETURNEND[ ; ]
When working with UDF types, it is possible to subcategorize them into simple and complex, according to the inner logic.
Simple User-defined Functions: these functions match the Transact-SQL syntax with Snowflake syntax. This type doesn't add any logic and goes straight to the result. These usually match Snowflake's SQL UDFs.
Complex User-defined Functions: these UDFs extensively use particular language logic operators and usually represent a mismatch or violation of Snowflake's SQL UDFs definition.
Return Types
Scalar functions
Scalar functions return primitive data types such as but not limited to:
Table-valued functions
Table-valued functions return a table-like result. It consists of a set of columns specified in the function's declaration.
Differences
One of the main differences between these two is the amount of supporting languages offered. Snowflake supports up to three languages for the user to declare the UDFs, meanwhile, T-SQL only offers one language in that regard.
Limitations
T-SQL UDFs have some limitations not present in other database engines (such as Oracle and Teradata). These limitations help the translations by narrowing the failure scope. This means, there are specific scenarios we can expect to avoid.
Here are some of the limitations TSQL has on UDFs
UDFs cannot be used to perform actions that modify the database state.
User-defined functions cannot contain an OUTPUT INTO clause that has a table as its target.
User-defined functions can not return multiple result sets. Use a stored procedure if you need to return multiple result sets.
Sample Source Patterns
Simple User-defined Functions
Simple Scalar functions
Scalar functions can take several optional parameters, and execute a statement to return a single value as the final result. These functions are usually used inside SELECT statements, single variable setup (most likely inside a stored procedure).
Transact-SQL
IN -> SqlServer_01.sql
-- FUNCTION DECLARATIONCREATEFUNCTIONsales.udfNetSale( @quantity INT, @list_price DEC ( 10, 2 ), @discount DEC ( 4, 2 ))RETURNSDEC ( 10, 2 )ASBEGINRETURN @quantity * @list_price * ( 1- @discount );END;
-- FUNCTION USESELECT sales.udfNetSale ( 10, 100, 0.1 );
Simple Table-Valued functions
Table-valued functions take several parameters, execute a query, and return a single value as a final result. These are usually used inside DML statements (SELECT, INSERT, UPDATE, DELETE) to return table-like results.
-- USE THE FUNCTION, NOTE THE TABLE() TO CONVERT THE RESULT INTO A TABLESELECT product_name, model_year, list_priceFROMTABLE ( udfProductInYear ( 2021 ) );
Complex User-defined Functions
Complex UDFs incorporateadditional logical code (Transact-SQL exclusive) to handle different outcomes like nested conditionals and loops. The use of variables is another example of complex UDFs. This level of complexity isn't supported by Snowflake SQL UDFs, instead, it relies on stored procedures and helpers to offer the same functionality. Depending on the target language that was configured for the migration, the functions will be migrated to procedures written in JavaScript or Snowflake Scripting.
!!!RESOLVE EWI!!! /*** SSC-EWI-0068 - USER DEFINED FUNCTION WAS TRANSFORMED TO SNOWFLAKE PROCEDURE ***/!!!CREATEORREPLACEPROCEDURE get_sign (NUM FLOAT)RETURNSVARCHARLANGUAGESQLCOMMENT = '{"origin":"sf_sc","name":"snowconvert","version":{"major":1, "minor":0},{"attributes":{"component":"transact"}}'
EXECUTEASCALLERAS$$DECLARE RESULT VARCHAR(255) :='negative';BEGINIF (:NUM >=0) THENBEGINIF (:NUM >0) THENSELECT'positive'INTO :RESULT;ELSESELECT'zero'INTO :RESULT;ENDIF;END;ENDIF;RETURN :RESULT;END;$$;
OUT JS -> SqlServer_03.sql
!!!RESOLVE EWI!!! /*** SSC-EWI-0068 - USER DEFINED FUNCTION WAS TRANSFORMED TO SNOWFLAKE PROCEDURE ***/!!!CREATEORREPLACEPROCEDURE get_sign (NUM FLOAT)RETURNS STRINGLANGUAGE JAVASCRIPTEXECUTEASCALLERAS$$// SnowConvert Helpers Code Goes Here let RESULT =`negative`;if (NUM >=0) { {if (NUM >0) {SELECT(` 'positive'`,[],(value) => RESULT =value); } else {SELECT(` 'zero'`,[],(value) => RESULT =value); } } }return RESULT;$$;
User-defined Function Calls
Only scalar UDFs can be inside a SELECT statement.
Transact-SQL
-- FUNCTION DECLARATIONCREATEFUNCTIONsales.udfNetSale( @quantity INT, @list_price DEC ( 10, 2 ), @discount DEC ( 4, 2 ))RETURNSDEC ( 10, 2 )AS...-- FUNCTION USESELECT sales.udfNetSale ( 10, 100, 0.1 );
Snowflake
-- FUNCTION DECLARATIONCREATE OR REPLACEFUNCTIONsales.udfNetSale ( quantity NUMBER, list_price NUMBER ( 10, 2 ), discount NUMBER ( 4, 2 ))RETURNSNUMBERAS$$...-- FUNCTION USESELECT sales.udfNetSale ( 10, 100, 0.1 );