DEV Community

FatimaAlam1234
FatimaAlam1234

Posted on

SQL - Procedures and Functions

A SQL stored procedure is a set of SQL code that can be saved and reused.

CREATE PROCEDURE getEmployeesBySalary
  @minSalary int
AS
BEGIN
  SELECT firstName, lastName
  FROM Employees
  WHERE salary > @minSalary
END
GO
Enter fullscreen mode Exit fullscreen mode

To call this procedure

EXEC getEmployeesBySalary 50000
Enter fullscreen mode Exit fullscreen mode

FUNCTIONS

A SQL function is a set of SQL statements that perform a specific task. Functions must return a value or result. We can use these functions in SELECT, INSERT, DELETE, UPDATE statements.

There are two types of functions in SQL:

Scalar functions, which return a single value and can be used where single expressions are used. For instance:
Enter fullscreen mode Exit fullscreen mode

CREATE FUNCTION addNumbers(@a int, @b int)
RETURNS int 
AS 
BEGIN
   RETURN @a + @b
END
Enter fullscreen mode Exit fullscreen mode
Table-valued functions, which return a table. They can be used in JOIN clauses as if they were a normal table. For example:
Enter fullscreen mode Exit fullscreen mode
CREATE FUNCTION getBooks (@authorID INT)
RETURNS TABLE
AS 
RETURN (
   SELECT books.title, books.publicationYear 
   FROM books 
   WHERE books.authorID = @authorID
)
Enter fullscreen mode Exit fullscreen mode

To call this function

SELECT title, publicationYear 
FROM getBooks(3)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)