create function

Description

Creates a user-defined function, which is a saved Transact-SQL routine that returns a specified value.

Syntax

create function [ owner_name. ] function_name 
( [ { @parameter_name [as] parameter_datatype [ = default ] } [ ,...n ] ] ) 
returns return_datatype
[ with recompile] ] 
as 
[begin]
function_body 
return scalar_expression
[end]

Parameters

Examples

This example creates a user-defined function named bonus:

create function BONUS(@salary int, @grade int, @dept_id int)
returns int
as
    begin
    declare @bonus int
    declare @cat int
    set @bonus = 0
    select  @cat = dept_cat from department where dept_id = @dept_id

    if (@cat < 10)
        begin
            set @bonus = @salary *15/100

        end
        else
            begin
            set     @bonus = @salary * 10/100
        end
return @bonus
end

Usage

If the owner of the user-defined function also owns all the database objects referenced inside, then all the other users who have execute permission on the function are automatically granted access permissions to all the referenced objects when they execute the function.

Permissions

By default, users with the sa and the dbo role have permission to run create function. Users with the sa or dbo role can grant create function permissions to other logins.

Owners of functions have execute permission on their functions. Other users do not have execute permissions unless execute permissions on the specific function are granted to them.