DBMS)
DBMS)
Lab 9:
OBJECTIVE:
Functions in SQL are predefined operations or expressions that can be used to perform computations
on data, manipulate strings, numbers, dates, or even return aggregated values. They help simplify
and streamline queries, making them more efficient and readable. SQL functions are typically
divided into two categories
Aggregate Functions: These operate on a set of values and return a single result for the entire set.
Aggregate Functions
Aggregate functions perform calculations on multiple rows of a table and return a single result. They
are often used with the GROUP BY clause to perform calculations for specific groups of data.
User Defined Functions: Allow users to create their own logic for specific needs that cannot be
fulfilled by standard SQL functions. UDFs can be written to perform operations like mathematical
calculations, data transformations, or complex business logic.
-- Create tables
CREATE TABLE dept (
deptno INT,
dname VARCHAR(14),
loc VARCHAR(13),
CONSTRAINT pk_dept PRIMARY KEY (deptno)
);
-- Insert statements
INSERT INTO dept VALUES
(10, 'ACCOUNTING', 'NEW YORK'),
(20, 'RESEARCH', 'DALLAS'),
(30, 'SALES', 'CHICAGO'),
(40, 'OPERATIONS', 'BOSTON'),
(50, 'MARKETING', 'LOS ANGELES'),
(60, 'HR', 'NEW YORK'),
(70, 'IT', 'SEATTLE');
Tasks:
Task 2: UDF
a. Create a function to get current date.
b. Capitalize first letter of employee name and lowercase remaining characters.
c. Create a scalar Function to Calculate Employee's Annual Salary.
d. Create a scalar Function to Check If an Employee is a manager.
e. Check if an employee's salary is above 3000.
f. Find number of employees in each department. (without function)
g. Create a Table-Valued Function to Get Employees in each Department.
h. Table-Valued Function to Get Employees in a Specific Location.
Code:
CREATE FUNCTION GetCurrentDate()
RETURNS DATE
AS
BEGIN
RETURN GETDATE();
END;
Task 3: Homework:
Learn and implement the following built-in functions:
a. String functions: Upper(), Lower(), Concat(),
b. Date-Difference: DATEDIFF()
c. Round()
Code:
SELECT
UPPER(employee_name) AS UpperCaseName,
LOWER(employee_name) AS LowerCaseName,
CONCAT('Employee: ', employee_name) AS FullName
FROM employees;