Lab_7
Lab_7
Tags
1. Introduction to Functions
What is a Function?
A Transact-SQL routine that:
Accepts parameters
Lab 7 1
Adds a specified interval to a date, reuturns
DATEADD (datepart , number, date )
a datetime
( datepart , startdate ,
DATEDIFF Returns the difference between two dates
enddate )
Examples:
Mathematical Functions
Lab 7 2
String Functions
Function Description
ASCII() ASCII code of the first character
LEN() Number of characters in a string
LOWER() Converts text to lowercase
SUBSTRING() Returns part of a string
Restrictions:
Cannot return multiple result sets
1. Scalar Functions
Return a single value (e.g., integer, string, date)
Syntax:
Lab 7 3
SET @Result = (expression);
RETURN @Result;
END;
Example:
Return @TotalSales;
END;
Calling:
Used directly in SELECT , WHERE , etc.
Syntax:
Lab 7 4
CREATE FUNCTION function_name (@param1 DataType)
RETURNS TABLE
AS
RETURN (
SELECT column1, column2
FROM TableName
WHERE condition
);
Example:
Calling:
Called like a table:
--Syntax
SELECT * FROM dbo.function_name(param);
--Example
SELECT * FROM dbo.GetCustomersOrders(5);
Lab 7 5
Format and structure of the table must be defined inside the RETURNS clause
Syntax:
RETURN;
END;
Example:
Lab 7 6
FROM Employees;
RETURN;
END;
Calling:
Used in FROM clause:
--Syntax
SELECT * FROM dbo.function_name(param);
--Example
SELECT * FROM dbo.GetEmployeesNames('Short Name');
Drop Function:
Lab 7 7