0% found this document useful (0 votes)
21 views15 pages

ADVANCED DB Presentation

Uploaded by

Kareem Dwidar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views15 pages

ADVANCED DB Presentation

Uploaded by

Kareem Dwidar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Team members:

1. Kareem Abdullraheem
2. Ahmed Sherif
3. Nour El-Deen Osama

Topics:

● Creating, Altering, and Dropping Rules


● Managing Users (Create, Alter, Drop)
● Granting and Revoking Permissions
● Adding Users to a Rule
● Triggers (What they are, and how to create them)
● Functions

Managing Rules in SQL Server


Concept:

A Rule is a reusable constraint applied to multiple columns to enforce data validation. For
example, a rule might restrict the age of an employee to be between 18 and 65. Unlike
constraints, a rule can be reused on multiple tables.

Scenario:

Goal:

1. Create a rule to ensure employee Age is always between 18 and 65.


2. Apply this rule to the Age column of the Employees table.
3. Test by inserting valid and invalid values.

Step 1: Create the Rule

CREATE RULE rule_EmployeeAge AS @age BETWEEN 18 AND 65;


This rule enforces that the Age must be between 18 and 65.

Step 2: Create the Employees Table

CREATE TABLE Employees (

EmployeeID INT PRIMARY KEY,

Name VARCHAR(50),
Age INT

);

Table Structure:

EmployeeID Name Age

1 Alice 30

2 Bob 16 (Will fail)

3 Charlie 70 (Will fail)

Step 3: Bind the Rule to the Column

EXEC sp_bindrule 'rule_EmployeeAge', 'Employees.Age'


This binds the rule_EmployeeAge to the Age column in the Employees table.

Step 4: Insert Valid and Invalid Values

-- This will succeed

INSERT INTO Employees (EmployeeID, Name, Age)

VALUES (1, 'Alice', 30);

-- This will fail because Age = 16 is outside the range (18-65)

INSERT INTO Employees (EmployeeID, Name, Age)

VALUES (2, 'Bob', 16);

-- This will fail because Age = 70 is outside the range (18-65)


INSERT INTO Employees (EmployeeID, Name, Age)

VALUES (3, 'Charlie', 70);

Expected Output:

EmployeeID Name Age

1 Alice 30

(ERROR) Bob (Age 16, fails)

(ERROR) Charlie (Age 70, fails)

Step 5: View Table Data

SELECT * FROM Employees;

Output:

EmployeeID Name Age

1 Alice 30

Step 6: Drop the Rule

sql

Copy code

EXEC sp_unbindrule 'Employees.Age';


DROP RULE rule_EmployeeAge;

This removes the rule from the Age column and deletes the rule.

2️⃣ Managing Users


Concept:

A User in SQL Server is a person or system that has access to the database. Each user is
linked to a login and can be assigned a default schema.

Scenario: Create a New User

Goal:

1. Create a user JohnD and link it to the JohnDLogin.


2. Rename JohnD to JDoe.
3. Drop the user JDoe.

Step 1: Create the User

CREATE USER JohnD

FOR LOGIN JohnDLogin

WITH DEFAULT_SCHEMA = dbo;

Explanation:
This creates a user JohnD for the JohnDLogin and sets the default schema as dbo.

Step 2: View the User in the Database

SELECT name, default_schema_name

FROM sys.database_principals

WHERE name = 'JohnD';


Output:

Name Default
Schema

JohnD dbo

Step 3: Rename the User

ALTER USER JohnD

WITH NAME = JDoe;

Explanation:
This renames the user JohnD to JDoe.

Step 4: View the Updated User

SELECT name, default_schema_name

FROM sys.database_principals

WHERE name = 'JDoe';

Output:

Name Default
Schema

JDoe dbo

Step 5: Drop the User

DROP USER JDoe;


Explanation:
This deletes the user JDoe from the database.

3️⃣ Granting and Revoking Permissions


Concept:

Permissions control what users can do in the database. You can GRANT a user the ability to
SELECT, UPDATE, DELETE, or INSERT on a table. You can also REVOKE permissions to
take away access.

Scenario: Grant and Revoke Permissions

Goal:

1. Allow JohnD to view (SELECT) the Employees table.


2. Then revoke that permission.

Step 1: Grant SELECT Permission

GRANT SELECT

ON Employees

TO JohnD;

Explanation:
This allows JohnD to view the Employees table.

Step 2: Verify the Permission

As JohnD, run:

SELECT * FROM Employees;

Output:
EmployeeID Name Age

1 Alice 30

Step 3: Revoke SELECT Permission

REVOKE SELECT

ON Employees

FROM JohnD;

Explanation:
This removes JohnD's ability to view the Employees table.

Step 4: Verify the Permission

As JohnD, run:

SELECT * FROM Employees;

Output:

Error: The SELECT permission was denied on the object 'Employees'.

4. Users to a Role

Concept:

A Role is a way to manage user permissions in a database. Instead of assigning


permissions to individual users, you create a role with specific permissions and then add
users to that role. This makes it easier to manage user access.

Key Commands:

● CREATE ROLE: Create a new role.


● GRANT: Grant permissions to a role.
● ALTER ROLE ADD MEMBER: Add users to the role.
● ALTER ROLE DROP MEMBER: Remove users from the role.
● DROP ROLE: Delete the role.

Scenario:
You have a database called SalesDB. You need to create a role called DataEditor that
allows users to SELECT, INSERT, and UPDATE data in the Sales.Orders table. You will
then add two users, Emily and David, to the role. Finally, you will view the role members,
remove David, and drop the role.

Step 1: Create the Role

CREATE ROLE DataEditor;

Creates a role called DataEditor in the database.

Step 2: Grant Permissions to the Role

GRANT SELECT, INSERT, UPDATE ON Sales.Orders TO DataEditor;

Gives SELECT, INSERT, and UPDATE permissions on the Sales.Orders table to the
DataEditor role.

Step 3: Add Users to the Role

ALTER ROLE DataEditor ADD MEMBER Emily;

ALTER ROLE DataEditor ADD MEMBER David;

Adds Emily and David as members of the DataEditor role.

Step 4: View Role Members


SELECT DP1.name AS RoleName,

DP2.name AS MemberName

FROM sys.database_role_members AS DRM

JOIN sys.database_principals AS DP1

ON DRM.role_principal_id = DP1.principal_id

JOIN sys.database_principals AS DP2

ON DRM.member_principal_id = DP2.principal_id

WHERE DP1.name = 'DataEditor';

Lists the members of the DataEditor role.

Expected Output:

RoleName MemberName

DataEditor Emily

DataEditor David

Step 5: Remove David from the Role

ALTER ROLE DataEditor DROP MEMBER David;

Step 6: View Role Members Again

Run the query from Step 4.

Expected Output:
RoleName MemberName

DataEditor Emily

Step 7: Drop the Role

DROP ROLE DataEditor;

Deletes the DataEditor role from the database.

5. Triggers

Concept:

A Trigger is a special kind of stored procedure that runs automatically when certain events
(like INSERT, UPDATE, or DELETE) happen on a table. Triggers are useful for enforcing
rules, auditing changes, or automatically recording updates in other tables.

Key Commands:

● CREATE TRIGGER: Create a trigger.


● FOR INSERT, UPDATE, DELETE: Define which event the trigger responds to.
● inserted/deleted: Temporary tables used in triggers to track old and new values.

Scenario:

You have an Employees table. Every time an employee's salary is updated, you need to log
the change in an EmployeeSalaryAudit table. The audit should store the EmployeeID, the
OldSalary, the NewSalary, and the Date of the change.

Step 1: Create the Audit Table

CREATE TABLE EmployeeSalaryAudit (

AuditID INT IDENTITY(1,1) PRIMARY KEY,

EmployeeID INT,

OldSalary DECIMAL(10,2),
NewSalary DECIMAL(10,2),

ChangeDate DATETIME

);

Creates a table to store information about salary changes for employees.

Step 2: Create the Trigger

CREATE TRIGGER trg_EmployeeSalaryAudit

ON Employees

FOR UPDATE

AS

BEGIN

INSERT INTO EmployeeSalaryAudit (EmployeeID, OldSalary,


NewSalary, ChangeDate)

SELECT

i.EmployeeID,

d.Salary AS OldSalary,

i.Salary AS NewSalary,

GETDATE() AS ChangeDate

FROM

inserted i

JOIN

deleted d ON i.EmployeeID = d.EmployeeID

WHERE i.Salary <> d.Salary;

END;
Creates a trigger that runs automatically every time the salary of an employee is updated. It
records changes in the EmployeeSalaryAudit table.

Step 3: Test the Trigger

UPDATE Employees

SET Salary = 75000

WHERE EmployeeID = 3;

Updates the salary of EmployeeID 3. This change will automatically be logged in


EmployeeSalaryAudit.

Step 4: View the Audit Table

SELECT * FROM EmployeeSalaryAudit;

Shows the records of salary changes.

Expected Output:

AuditID EmployeeID OldSalary NewSalary ChangeDate

1 3 70000 75000 2024-12-09 10:32:00

6. Functions

Concept:

A Function is a block of code that performs a calculation and returns a single result. Unlike
stored procedures, functions can be used in SQL queries like SELECT. Functions are useful
for reusability and encapsulating business logic.

Key Commands:

● CREATE FUNCTION: Create a new function.


● RETURN: Return a single value.
● Parameters: Functions can accept input parameters and return a result.

Scenario:
You want to create a function that takes an EmployeeID as input and returns the Full Name
of the employee by combining their FirstName and LastName. This function will be used to
display employee names in reports.

Step 1: Create the Function

CREATE FUNCTION fn_GetEmployeeFullName (@EmployeeID INT)

RETURNS VARCHAR(100)

AS

BEGIN

DECLARE @FullName VARCHAR(100);

SELECT

@FullName = FirstName + ' ' + LastName

FROM

Employees

WHERE

EmployeeID = @EmployeeID;

RETURN @FullName;

END;

Creates a function that takes EmployeeID as input and returns the Full Name of the
employee.

Step 2: Test the Function


SELECT dbo.fn_GetEmployeeFullName(3) AS FullName;

Tests the function with EmployeeID = 3.

Expected Output:

FullName

Emily Johnson

Step 3: Use the Function in a Query

SELECT

EmployeeID,

dbo.fn_GetEmployeeFullName(EmployeeID) AS FullName,

Salary

FROM

Employees;

This query lists all employees with their EmployeeID, Full Name, and Salary.

Expected Output:

EmployeeID FullName Salary

1 Alice Smith 60000

2 Bob Miller 72000


3 Emily Johnson 75000

4 David Brown 65000

You might also like