Functions
Description
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
Inline Table-Valued Function Syntax
Multi-Statement Table-Valued Function Syntax
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
Snowflake
Function use
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.
Transact-SQL
Snowflake