CREATE FUNCTION

Other topics

Remarks:

CREATE FUNCTION creates a user-defined function that can be used when doing a SELECT, INSERT, UPDATE, or DELETE query. The functions can be created to return a single variable or a single table.

Create a new Function

CREATE FUNCTION FirstWord (@input varchar(1000))
RETURNS varchar(1000)
AS
BEGIN
    DECLARE @output varchar(1000)
    SET @output = SUBSTRING(@input, 0, CASE CHARINDEX(' ', @input)
        WHEN 0 THEN LEN(@input) + 1
        ELSE CHARINDEX(' ', @input)
    END)

    RETURN @output
END

This example creates a function named FirstWord, that accepts a varchar parameter and returns another varchar value.

Syntax:

  • CREATE FUNCTION function_name ( [list_of_paramenters] ) RETURNS return_data_type AS BEGIN function_body RETURN scalar_expression END

Parameters:

ArgumentDescription
function_namethe name of function
list_of_paramentersparameters that function accepts
return_data_typetype that function returs. Some SQL data type
function_bodythe code of function
scalar_expressionscalar value returned by function

Contributors

Topic Id: 2437

Example Ids: 8036

This site is not affiliated with any of the contributors.