([@parameter [AS] [type_schema_name.] datatype
[= default] [READONLY]
, @parameter [AS] [type_schema_name.] datatype
[= default] [READONLY]]
)
RETURNS return_datatype
[WITH {ENCRYPTION
| SCHEMABINDING
| RETURNS NULL ON NULL INPUT
| CALLED ON NULL INPUT
| EXECUTE AS Clause]
[AS]
BEGIN
[declaration_section]
executable_section
RETURN return_value
END;
Parameters:
CREATE FUNCTION fuNhanvien
(@nhanvien_id INT)
RETURNS VARCHAR (50)
AS
BEGIN
DECLARE @nhanvien_name VARCHAR (50);
IF @nhanvien_id <10
SET @nhanvien_name = 'Smith';
ELSE
SET @nhanvien_name = 'Lawrence';
RETURN @nhanvien_name;
END;
The above function is named fuNhanvien, has an @nhanvien_id parameter with the INT data type. The function will return the VARCHAR (50) value when executing the RETURNS statement.
Then you can make the reference fuNhanvien as follows:
USE [test]
GO
SELECT dbo.fuNhanvien (8);
GO
Once you have created the function successfully, there will be cases where you want to remove the function from the database for a few reasons.
To remove a function, we have the following syntax:
DROP FUNCTION function_name ;
Parameters :
function_name: The function name you want to delete .
DROP FUNCTION fuNhanvien;
By executing this command, you have just removed the fu function from the database.
Previous post: SEQUENCE in SQL Server
Next lesson: PROCEDURE (Procedure) in SQL Server