User defined functions allow reusable SQL code that accepts parameters and returns tables or scalar values. They provide modular programming and can be used in FROM clauses like views that accept parameters. However, functions should be avoided in WHERE clauses due to performance issues and their "hidden cursor" behavior. Functions are created using CREATE FUNCTION and can return single values with scalar functions or tables with table valued functions using either inline or multi-statement syntax. Functions can be joined to tables using APPLY operators like CROSS APPLY or OUTER APPLY.
User defined functions allow reusable SQL code that accepts parameters and returns tables or scalar values. They provide modular programming and can be used in FROM clauses like views that accept parameters. However, functions should be avoided in WHERE clauses due to performance issues and their "hidden cursor" behavior. Functions are created using CREATE FUNCTION and can return single values with scalar functions or tables with table valued functions using either inline or multi-statement syntax. Functions can be joined to tables using APPLY operators like CROSS APPLY or OUTER APPLY.
User defined functions allow reusable SQL code that accepts parameters and returns tables or scalar values. They provide modular programming and can be used in FROM clauses like views that accept parameters. However, functions should be avoided in WHERE clauses due to performance issues and their "hidden cursor" behavior. Functions are created using CREATE FUNCTION and can return single values with scalar functions or tables with table valued functions using either inline or multi-statement syntax. Functions can be joined to tables using APPLY operators like CROSS APPLY or OUTER APPLY.
User Defined Function Concepts Reusable blocks of SQL code Accepts parameters Possible return types Tables Scalar Values User Defined Function Concepts Advantages Modular programming Table valued functions can be used in FROM clauses Similar to a view that accepts parameters Disadvantages Performance Avoid using functions in WHERE clauses Hidden cursor Read only Advantages and Disadvantages Creating User Defined Functions Returns a single value
CREATE FUNCTION <name> (<parameters>) RETURNS <dataType> AS BEGIN -- Logic RETURN <variable> END; Scalar Functions Single SELECT statement to return values Similar to a view that accepts parameters
CREATE FUNCTION <name> (<parameters>) RETURNS TABLE AS RETURN -- SELECT statement Inline Table Valued Functions Returns a table, but can use complex logic
CREATE FUNCTION <name> (<parameters>) RETURNS <variableName> TABLE (<tableDefinition>) AS BEGIN -- Logic -- INSERT INTO <variableName> RETURN END; Multi-Statement Table Valued Function Apply Operators Join tables to functions Pass column as parameter into function Options CROSS APPLY Similar to an inner join OUTER APPLY Similar to an inner join