Department of Computer Science & Information Technology
Khwaja Fareed University of Engineering & Information Technology
Course: Database Systems
Lab Instructor:
Ms. Hira Kanwal
Student Name
Student Roll #
Department
Batch/Year/Section
For Lab. Instructor
Marks Signature
KFUEIT Department of CS/IT
Lab Manual # 12 Creating & Manipulating Databases
12.1. Objective
a. Back up a Database
b. Restore a Database
c. Database Triggers
12.2. Back up a Database
Backing up your SQL Server database is essential for protecting your data. Syntax for
creating a Backup in SQL Server is as follows:
USE ACDB;
GO
BACKUP DATABASE ACDB
TO DISK = 'F:\BB\ACDB.Bak'
WITH FORMAT,
MEDIANAME = 'F_BB',
NAME = 'Full Backup of ACDB';
GO
12.3. Restore a Database
RESTORE DATABASE ACDB FROM DISK = 'F:\BB\ACDB.Bak'
WITH Replace, recovery
GO
Note: Backups created by more recent version of SQL Server cannot be restored in earlier
versions of SQL Server.
12.4. Database Triggers
Triggers are database operations which are automatically performed when an action such as
Insert, Update or Delete is performed on a Table or a View in database.
Triggers are associated with the Table or View directly i.e. each table has its own Triggers.
Example 1: (After Insert) (A trigger that prints date when a new row in inserted in table.)
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[AfterInsert]
ON [dbo].[NEW1]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
-- Insert statements for trigger here
PRINT GETDATE();
END
KFUEIT Department of CS/IT
89
Lab Manual # 12 Creating & Manipulating Databases
Example 2: (After Insert)
ALTER TRIGGER [dbo].[trgafterinsert]
ON [dbo].[NEW1]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
declare @id int;
select @id= INSERTED.Id from inserted;
-- Insert statements for trigger here
insert into NewLog(ID,Date) values (@id, sysdatetime())
END
Example 3: (After Delete Trigger)
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER AfterDelete
ON New1
AFTER Delete
AS
BEGIN
SET NOCOUNT ON;
Declare @id int
select @id=deleted.id from deleted;
insert into NewLog values (@id,sysdatetime(),'Deleted');
-- Insert statements for trigger here
END
GO
Example 4: (After Update)
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER AfterUpdate
ON New1
AFTER Update
AS
BEGIN
SET NOCOUNT ON;
Declare @id int
select @id=inserted.id from inserted;
insert into NewLog values (@id,sysdatetime(),'Updated');
-- Insert statements for trigger here
END
GO
KFUEIT Department of CS/IT
90