You are on page 1of 3

Database Programming – : PRACTICAL CLASS

Understanding Transactions:

On completion of this practical, students are expected to:


Create tables
Insert into the tables
Code a Transaction using a stored procedure
Test transactions

============================================================================

Task 1: Create the below tables.


Enter the following query:

--STEP 1: Create your own database


Create database Class2022

--Create 2 tables (Person and PersonDetails in your database


create table Person (
PersonID nvarchar(5) primary key not null,
FirstName nvarchar(10) not null,
Company nvarchar(15)
)

create table PersonDetails (


PersonID nvarchar(5) foreign key
references dbo.Person(PersonID),
Address nvarchar(30)
)

Task 2: Insert into the table created


Enter the following query:
--Insert some values into your database
insert into Person
values('Vidvr','Vidya Vrat','Lionbridge Inc'),
('Rupag','Rupali', 'Pearl Solutions')

Insert into PersonDetails


values('Vidvr','Bellevue WA 98007'),
('Rupag', 'Bellevue WA 98007')
Task 3: Code a transaction using a stored procedure.
Enter the following procedure:

-- CREATE a Procedure
create procedure sp_Trans_Test
@newpersonid nvarchar(5),
@newfirstname nvarchar(10),
@newcompanyname nvarchar(15),
@oldpersonid nvarchar(5)
as
declare @inserr int
declare @delerr int
declare @maxerr int
set @maxerr = 0

begin transaction
-- Add a person
insert into person (personid, firstname, company)
values(@newpersonid, @newfirstname, @newcompanyname)

-- Save error number returned from Insert statement


set @inserr = @@error
if @inserr > @maxerr
set @maxerr = @inserr

-- Delete a person
delete from person
where personid = @oldpersonid
set @delerr = @@error -- Save error number returned from Delete statement

if @delerr > @maxerr


set @maxerr = @delerr

-- If an error occurred, roll back


if @maxerr <> 0
begin
rollback
print 'Transaction rolled back'
end
else
begin
commit
print 'Transaction committed'
end
print 'INSERT error number:' + cast(@inserr as nvarchar(8))
print 'DELETE error number:' + cast(@delerr as nvarchar(8))

Run the statement:


exec sp_Trans_Test 'Pearl', 'Vamika ', null,'Agraw'
Enter the following SELECT statement:
Select * from Person

Run the following statement:


exec sp_Trans_Test 'Spark', 'Arshika ', null,'Agarw'

Task 4: What happens?


Enter the following statements:
exec sp_Trans_Test 'Pearl', 'Vamika', null,'Spark'

• Try to insert new person and try to delete a person who has child
records in the PersonDetails table.
exec sp_Trans_Test 'ag', 'Agarwal ',null, 'Vidvr'

• Try to insert an invalid new person, in other words, one with a


duplicate name, and try to delete an undeletable one, in other words,
one that has child records in the PersonDetails table.
exec sp_Trans_Test 'Pearl', 'Vamika', null,'Rupag'

You might also like