Create user-defined function (T-SQL)
MS SQL user-defined functions are of 2 types: Scalar and Tabular-Valued based on the type of result set each return.
A Scalar function accepts one or more parameters and returns a single value.
A Table-Valued function takes one input parameter and returns the columns of the table.
Requires
CREATE FUNCTION
permission in the database andALTER
permission on the schema in which the functions are being created. [ as referred in the Microsoft Docs ]
Syntax
- T-SQL Scalar function syntax
CREATE FUNCTION [ schema_name. ] <function_name> [ (@parameterName datatype)]RETURNS return_data_typeBEGINfunction_body --T-SQL statementsRETURN scalar_expressionEND;
- T-SQL Inline Table-Valued function syntax
CREATE FUNCTION [ schema_name. ] <function_name> [ (@parameterName datatype)]RETURNS TABLEASRETURN(T-SQL statements);GO
- Scalar Functions
USE HASURA;GOCREATE FUNCTION dbo.getDeptId (@EmpId int)RETURNS INTASBEGINDECLARE @DeptId int;SELECT @DeptId = e.DeptIdFROM dbo.EMPLOYEE eWHERE e.EmpID=@EmpId;RETURN @DeptId;END;GO
Invoke the function as:
SELECT dbo.getDeptId(3);SELECT e.empName, dbo.getDeptId(e.EmpId) AS DepartmentID FROM EMPLOYEE e;
- Table-Valued Functions
CREATE FUNCTION [dbo].[getEmpDetails] (@EmpId int)RETURNS TABLEASRETURN(SELECT e.EmpName, e.EmpID, d.DeptNameFROM EMPLOYEE eLEFT JOIN DEPARTMENT dON e.DeptId=d.DepartmentIdWHERE e.EmpId=@EmpId);GO
Invoke the function as:
SELECT * FROM dbo.getEmpDetails(4);
result set:
EmpName | EmpId | DeptName |
---|---|---|
Musk | 4 | R&D |
Did you find this page helpful?
Start with GraphQL on Hasura for Free
- Build apps and APIs 10x faster
- Built-in authorization and caching
- 8x more performant than hand-rolled APIs