Learn how to create and drop functions in SQL Server (Transact-SQL) with syntax and examples.
In SQL Server, a function is a stored program that you can pass parameters into and return a value.
You can create your own functions in SQL Server (Transact-SQL). Let's take a closer look.
The syntax to create a function in SQL Server (Transact-SQL) is:
The name of the schema that owns the function.
The name to assign to this function in SQL Server.
One or more parameters passed into the function.
The schema that owns the data type, if applicable.
The data type for @parameter.
The default value to assign to @parameter.
It means that @parameter can not be overwritten by the function.
The datatype of the function's return value.
It means that the source for the function will not be stored as plain text in the system views in SQL Server.
It means that the underlying objects can not be modified so as to affect the function.
It means that the function will return NULL if any parameters are NULL without having to execute the function.
It means that the function will execute the function even if any parameters are NULL.
Sets the security context to execute the function.
The value returned by the function.
Let's look at an example of how to create a function in SQL Server (Transact-SQL).
The following is a simple example of a function:
This function is called ReturnSite. It has one parameter called @site_id which is an INT datatype. The function returns a VARCHAR(50) value, as specified by the RETURNS clause.
You could then reference the new function called ReturnSite as follows:
Once you have created your function in SQL Server (Transact-SQL), you might find that you need to remove it from the database.
The syntax to a drop a function in SQL Server (Transact-SQL) is:
The name of the function that you wish to drop.
Let's look at an example of how to drop a function in SQL Server.
For example:
This DROP FUNCTION example would drop the function called ReturnSite.