You are on page 1of 55

.

SQL Portfolio

Name: Tahir Rizwan


Email: Tahrizwan@yahoo.com
Phone : 484-221-8767

Table of Contents
My Projects
Piggy Bank Project (A dummy back end bank application)
ER Diagram - Stored Procedures - Triggers
County Library Project
ER Diagram - Reports Backup Plan
Movie Rental Company (BlockFlix)
Table Design 2 Stored Procedures SSIS - SSRS

Piggy Bank (Assignment Detail)


To develop a back end banking system used by
Bank Tellers to support
Open new checking/savings accounts.
Deposit, Withdraw and transfer transactions.
Account closing and account access by customers.

ER Diagram (Piggy Bank)

Procedure to add New Customers in the database


****** Object: StoredProcedure [dbo].[Add Customer] Script Date: 10/03/2009 21:29:57 ******/
Use PiggyBank
GO
CREATE PROC [dbo].[AddCustomer]
@firstname varchar(50), @lastname varchar(50), @Middlintl varchar(50),
@street varchar(50), @city varchar(50), @state char(2), @zip char(10), @HmPhn Char(12),
@Wrkphn Char(12), @CellPhn Char(12), @Email Varchar(50),
@CustID int output
AS
-- Validation of Customer Data
if @lastname is null or @lastname = ''
or @firstname is null or @firstname = ''
or @street is null or @street = ''
or @city is null or @city = ''
or @state is null or @state = ''
or @zip is null or @zip = ''
or @HmPhn is null or @HmPhn = '
Begin
Raiserror ('PLEASE ENTER THE LAST NAME, FIRST NAME of the Customer with the Complete address including city, Zip
Code and the Home Phone No',14,1)
Return -1
End
Begin Try
Begin Tran
insert into dbo.Customer(CustomerFirstname,CustomerLastname,CustomerMiddleInitial,Street,
City,State,ZipCode,HomePhone,WorkPhone,CellPhone,Email)
values (@firstname, @lastname,@Middlintl,@street,@city,@state,@zip,@HmPhn,
@WrkPhn,@CellPhn,@Email)
Set @CustID = Scope_Identity()
Commit Tran
End Try
Begin Catch
Rollback Tran
Select Error_number(), Error_Message()
End Catch

To add New Checking account


/****** Object: StoredProcedure [dbo].[NewAcct] Script Date: 10/03/2009 21:48:17 ******/
CREATE Proc [dbo].[NewAcct]
@CustID int, @TransAmt money, @GnrOverDrft bit, @AcctID int output
As
--Validation of Customer ID
if
@CustID NOT IN
(Select CustomerID from Customer)
Begin
Raiserror ('CUSTOMER DOES NOT EXIST IN THE DATABASE',14,1)
Return -1
End
--Validation for Deposit Money, the Initial Deposit should not be less than $50.00
if
@TransAmt<50
Begin
Raiserror ('PLease Enter the Deposit Money not Less than $50.00',14,1)
Return -1
End
Begin Try
Begin Tran
insert into dbo.Account(AccountTypeID,AccountStatusID,
CurrentBalance,GeneralOverDraft)
values (2,1,@TransAmt,@GnrOverDrft)
Set @AcctID = Scope_Identity()

insert into dbo.CustomerAccount(AccountID,CustomerID)


values (@AcctID,@CustID)
insert into dbo.Transactions(AccountID,TransactionTypeID,
CustomerID,TransactionDate,TransactionAmount,NewBalance)
values (@AcctID,1,@CustID,GetDate(),@TransAmt,@TransAmt)
Commit Tran
End Try
Begin Catch
Rollback Tran
Select Error_number(), Error_Message()
End Catch

Deposit Procedure
/****** Object: StoredProcedure [dbo].[Deposit] Script Date: 10/15/2009 19:06:24 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER Proc [dbo].[Deposit]
@CustID int, @AcctID int, @TransAmt money, @TransID int output
As
--Validation of Customer ID and Account ID
if
@CustID NOT IN
(Select CustomerID from Customer)
Begin
Raiserror ('Customer does not Exist in the Database',14,1)
Return -1
End
if
@AcctID NOT IN
(Select AccountID from CustomerAccount where CustomerID=@CustID)
Begin
Raiserror ('Account does not belong to the Customer',14,1)
Return -1
End
Declare @NewBal money,@Currntbalance money, @AcctStatus tinyint, @Genroverdrft bit
-- Validation of Account Status
Select @AcctStatus = AccountStatusID from Account where AccountID=@AcctID
if @AcctStatus = 2
Begin
Raiserror ('ACCOUNT IS INACTIVE, FIRST CHANGE THE ACCOUNT TO ACTIVE STATUS',14,1)
Return -1
End
Set @NewBal=(Select CurrentBalance from Account
where AccountID=@AcctID)+ @TransAmt

Deposit (Cont)
Begin Try
Begin Tran
insert into dbo.Transactions(AccountID,TransactionTypeID,
CustomerID,TransactionDate,TransactionAmount,NewBalance)
values (@AcctID,2,@CustID,GetDate(),@TransAmt,@NewBal)
Update Account
Set CurrentBalance = @NewBal where AccountID = @AcctID
Commit Tran
End Try
Begin Catch
Rollback Tran
Select Error_number(), Error_Message()
End Catch

Transfer Money
/****** Object: StoredProcedure [dbo].[Transfer] Script Date: 10/15/2009 20:12:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROC [dbo].[Transfer]
@FromAccount int, @ToAccount int, @Amount money,
@TransID int output
AS
Declare @CustID1 int, @CustID2 int, @balance money, @ToBalance money,
@AcctStatus tinyint

-- Validation for Account Status

Select @AcctStatus = AccountStatusID from Account where AccountID=@FromAccount


if
@AcctStatus = 2
Begin
Raiserror ('THE ACCOUNT IS INACTIVE, FIRST ACTIVATE THE ACCOUNT TO TRANSFER THE MONEY FROM',14,1)
Return -1
End
Select @AcctStatus = AccountStatusID from Account where AccountID=@ToAccount
if
@AcctStatus = 2
Begin
Raiserror ('ACCOUNT IS INACTIVE, FIRST ACTIVATE THE ACCOUNT TO TRANSER THE MONEY TO',14,1)
Return -1
End

Transfer Money (Cont)


--- Validation to check if both Accounts exists in the database
if @FromAccount NOT IN
(Select AccountID from Account where AccountID = @FromAccount)
Begin
Raiserror ('THE TRANSFERING FROM ACCOUNT DOES NOT EXIST',14,1)
Return -1
End
if @ToAccount NOT IN
(Select AccountID from Account where AccountID = @ToAccount)
Begin
Raiserror ('THE TRANSFERING TO ACCOUNT DOES NOT EXIST',14,1)
Return -1
End
Select @CustID1 = CustomerID from CustomerAccount
where AccountID = @FromAccount
Select @CustID2 = CustomerID from CustomerAccount
where AccountID = @ToAccount
if @CustID1 <> @CustID2
Begin
RAISERROR('Sorry! the funds could not be transfered, the accounts do not belong to the same
customer.',16,1)
Return -1
End

Transfer Money (Cont)


Begin
Select @balance = CurrentBalance from Account where AccountID = @FromAccount
Select @ToBalance = CurrentBalance from Account where AccountID = @ToAccount
If @balance<@Amount
Begin

-- If there are not enough funds in the account


RAISERROR('Sorry there are not enough funds in your account',16,1)

Return -1
End
END
Begin Try
Begin Tran
Insert into Transactions (AccountID, TransactionTypeID, CustomerID, TransactionDate, TransactionAmount, NewBalance)
Values (@FromAccount,4, @CustID1, getdate(), @Amount, @balance-@Amount)
Insert into Transactions (AccountID, TransactionTypeID, CustomerID, TransactionDate, TransactionAmount, NewBalance)
Values (@ToAccount,5, @CustID1, getdate(), @Amount, @ToBalance+@Amount)
Update Account Set CurrentBalance = CurrentBalance - @Amount
where AccountID = @FromAccount
Update Account Set CurrentBalance = CurrentBalance + @Amount
where AccountID = @ToAccount
Commit Tran
End Try
Begin Catch
Rollback Tran
Select Error_number(), Error_Message()
End Catch

Triggers
USE [PiggyBank]
GO
/****** Object: DdlTrigger [Security] Script Date: 06/20/2009 17:34:37 ******/
IF EXISTS (SELECT * FROM sys.triggers WHERE name = N'Security' AND parent_class=0)
DROP TRIGGER [Security] ON DATABASE
USE [PiggyBank]
GO
/****** Object: DdlTrigger [Security] Script Date: 06/20/2009 17:35:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create TRIGGER [Security]
ON DATABASE
FOR DROP_TABLE, ALTER_TABLE
AS
PRINT 'You are not allowed to Drop or Alter table in the database!'
ROLLBACK ;

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
ENABLE TRIGGER [Security] ON DATABASE

/****** Object: Trigger [DelTransact] Script Date: 06/20/2009 17:38:40 ******/


IF EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[DelTransact]'))
DROP TRIGGER [dbo].[DelTransact]
GO
/****** Object: Trigger [UpdateTrans] Script Date: 06/20/2009 17:38:40 ******/
IF EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[UpdateTrans]'))
DROP TRIGGER [dbo].[UpdateTrans]
USE [PiggyBank]
GO
/****** Object: Trigger [dbo].[DelTransact] Script Date: 06/20/2009 17:38:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create Trigger [dbo].[DelTransact] on [dbo].[Transactions]
Instead of Delete not for replication
As
Begin
Set NoCount ON;
Declare @DelCount int;
Select @DelCount = Count(*) FROM Deleted;
If @DelCount>0
Begin
Raiserror ('Transactions can not be deleted',14,1)
If @@Trancount>0
Begin
Rollback Transaction;
End
End
End
GO
/****** Object: Trigger [dbo].[UpdateTrans] Script Date: 06/20/2009 17:38:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Trigger [dbo].[UpdateTrans] on [dbo].[Transactions]
Instead of Update not for replication
As
Begin
Set NoCount ON;
Declare @UpCount int;
Select @UpCount = Count(*) FROM Deleted;
If @UpCount>0
Begin
Raiserror ('Transactions can not be Updated',14,1)
If @@Trancount>0
Begin
Rollback Transaction;
End
End
End

Library Project
Objectives
To create Several Reports to accommodate
business practices of a lending library.
To create a backup schedule for the library
database.

ER Diagram
title
title_no
title
author
synopsis

loan
isbn
copy_no

member

loanhist

title_no

member_no

member_no

lastname

out_date

firstname

due_date

isbn
copy_no

copy

out_date

middleinitial

isbn

title_no

photograph

copy_no

member_no

title_no

due_date

on_loan

in_date
fine_assessed
fine_paid

reservation
isbn
member_no
log_date
remarks

adult
member_no

juvenile

street

member_no

city

adult_member_no

state

birth_date

zip
phone_no
expr_date

item
isbn
title_no
translation
cover
loanable

fine_waived
remarks

A drill-down report that provides additional detail about a book.

List of checked out Books order by ISBN, Copy Number (include member name)

Adult Member detail report. Details about adult members: name, address, total number of active
checkouts (loan table), with a drill down option for total fines assessed, total fines paid, total fines
waived, and total due. Also a second report displays each juveniles checkout/fine information

Kids Club report. There is a special reading club for Kids.


Design a report that displays all juvenile library members that belong to 7 year olds, 8 year old, and 9 year old age
groups. Please distinguish between the three groups on the report by utilizing conditional expressions to implement
an appropriate color scheme, and be sure to explain this scheme to the user in a legend.

Total Fines by Member: Design a report, ordered by member name that will accommodate the fine
information from Current Fines for Overdue Books and combine this with the historical fine
information in the Loan History table.

Expired Memberships. A complete list of expired memberships, organized by adult members with a drill
down to all dependant juvenile memberships.

Operating Schedule of the Library


The Library experiences
medium-heavy traffic on
weekends and evenings
and fairly light traffic
during the days and
mornings. The library
closes at 9pm each
week night and opens at
7am each morning
Sunday-Saturday. Over
the weekends it closes
at 5pm.

Proposed Backup Schedule for the


Library Database

Proposed Backup Schedule (Cont)

Proposed Backup Schedule (Cont)

Proposed Backup Schedule (Cont)

Proposed Backup Schedule (Cont)

Proposed Backup Schedule (Cont)

Proposed Backup Schedule (Cont)

Proposed Backup Schedule (Cont)

Proposed Backup Schedule (Cont)

Proposed Backup Schedule (Cont)

Proposed Backup Schedule (Cont)

BlockFlix: Objective
A fully functional movie database
Track:
Inventory of Movies
Customer Information
Sales / Checkout
Payment & Fees

Service Outlets:
Online Stores
Local Branches
Kiosk

Table Design:

Customers (7)
Media/Rentable Items (8)
Products/Stores (4)
Transactions/History (8)

(27 tables)

ER Diagram

Procedure: To add New Customer


Create Proc addCustomer
@firstName varchar(25) = NULL,
@lastName varchar(25) = NULL,
@address varchar(50) = NULL,
@city varchar(25) = NULL,
@state char(2) = NULL,
@zip int = NULL,
@phone char(12)=NULL,
@membershipTypeID int = NULL,
@paymentTypeID int = NULL,
@months_purchased int = NULL,
@subscription bit = 0,
@cardNumber int = NULL,
@cardTypeID int = NULL,
@authorizationCode int = NULL,
@card_expr_date datetime = NULL
AS
Begin
--Define errors that can be raised
Declare @Error_NULL varchar(75),
@Error_White varchar(75),
@Error_BadPhone# varchar(85),
@Error_MemberType varchar(75),
@Error_UniqueID varchar(75),
@Error_CardType varchar(75),
@findMembership int,
@findCustomer int,
@customerID int,
@statusID int,
@findCardType int,
@monthly_price money
Set @Error_NULL = 'Error: Null value found in required input'
Set @Error_White = 'Error: Whitespace found in required input'
Set @Error_BadPhone# = 'Error: One or more of the phone #s provided is in an invalid format'
Set @Error_MemberType = 'Error: Invalid membersip type provided'
Set @Error_UniqueID = 'Error: Customer is already a member'
Set @Error_CardType = 'Erroe: Invalid Card Type ID'

Procedure: To add New Customer (Cont)


--Check for NULL values on input paramemters
If (@firstName IS NULL
OR @lastName IS NULL
OR @address IS Null
OR @city IS NULL
OR @state IS NULL
OR @zip IS NULL
OR @MembershipTypeID IS NULL)
Begin
RAISERROR(@Error_NULL,10,1)
Return
End
--Check for whitespace
If(LTRIM(RTRIM(@firstName))=''
OR LTRIM(RTRIM(@lastName))=''
OR LTRIM(RTRIM(@address))=''
OR LTRIM(RTRIM(@city))=''
OR LTRIM(RTRIM(@state))='')
Begin
RAISERROR(@ERROR_White,10,1)
Return
End
--Check that the phone numbers are in the proper format
If ((@phone IS NOT NULL) AND (@phone NOT Like '___-___-____'))
Begin
RAISERROR(@ERROR_BadPhone#,10,1)
Return
End
--Check that the membershipID Exist in the database
Set @findMembership = (Select membershipTypeID From dbo.Memberships
Where membershipTypeID = @membershipTypeID)
If (@findMembership IS NULL)
Begin
RAISERROR(@Error_MemberType,10,1)
Return
End

Procedure: To add New Customer (Cont)


--Check that the customer does not currently Exist in the database
Set @findCustomer = (Select customerID
From Customers
Where firstName = @firstName AND lastName =
@lastName AND address = @address)
If (@findCustomer IS NOT NULL)
Begin
RAISERROR(@Error_UniqueID,10,1)
Return
End
--Check that CardType is not Null and Exists in the database
Set @findCardType=(Select cardTypeID from CardTypes where cardTypeID=@cardTypeID)
If (@findCardType IS NULL)
Begin
RAISERROR(@Error_CardType,10,1)
Return
End
--Chect that Payment Type ID is valid
If not exists (Select PaymentTypeID from PaymentTypes
where PaymentTypeID=@paymentTypeID)
Begin
Raiserror ('Payment Type ID is Invalid',14,1)
Return -1
End

Procedure: To add New Customer (Cont)


Begin Try
Begin Tran
--update customers table
Insert into dbo.Customers(firstName,lastName, address, city, state, zip, phone)
Values(@firstName,@lastname,@address,@city,@state,@zip,@phone)
Set @customerID = SCOPE_IDENTITY()
Set @statusID = 1
--update customerAccount table
Insert into dbo.CustomerAccount(customerID, membershipID,statusID,expr_date,num_checked_out, subscription)
Values(@customerID,@membershipTypeID,@statusID,DateAdd(m,@months_purchased,GetDate()),0,@subscription)
--Update customerCreditInfo table if subscription is turned on
IF(@subscription = 1)
Insert into
dbo.CustomerCreditInfo(customerID,cardNumber,cardTypeID,expr_date,authorizationCode)Values(@customerID,@cardNumber,@cardTypeI
D,@card_expr_date,@authorizationCode)
Set @monthly_price = (Select monthly_price From memberships Where membershipTypeID = @membershipTypeID)
--Update paymentHistory
Insert into dbo.MemberPaymentHistory(customerID,date_paid,paymentTypeID, membershipID,monthly_price,quantity)
Values(@customerID,GetDate(),@paymentTypeID,@membershipTypeID,@monthly_price,@months_purchased)
Commit Tran
End Try
Begin Catch
Rollback Tran
Declare @ErrorMessage varchar(85)
Declare @ErrorSeverity int
Declare @ErrorState int
Set @ErrorMessage = Error_Message()
Set @ErrorSeverity = Error_Severity()
Set @ErrorState = Error_State()
RAISERROR(@ErrorMessage,@ErrorSeverity,@ErrorState)
Return
End Catch
End

Procedure: To Check Customers Status


/* CustomerStatusCheck:
This procedure will check for any customer accounts that have expired and set their status to inactive
Task:
- Update the statusID to = 2 if any CustomerAccount is expired + 7days
*/

Create Proc CustomerStatusCheck


AS
Begin
Begin Try
Begin Tran
--If expr_date is more then 1 month and 7 days delinquent
Update CustomerAccount SET statusID=2 WHERE DateDiff(m,expr_date,GetDate())>1 OR
(DateDiff(m,expr_date,GetDate())=1 AND DatePart(d,GetDate())-DatePart(d,expr_date)>7) AND statusID<>2
Commit Tran
End Try
Begin Catch
Rollback Tran
Declare @ErrorMessage varchar(85)
Declare @ErrorSeverity int
Declare @ErrorState int

Set @ErrorMessage = Error_Message()


Set @ErrorMessage = Error_Severity()
Set @ErrorMessage = Error_State()
RAISERROR(@ErrorMessage,@ErrorSeverity,@ErrorState)
Return
End Catch
End

SSIS Package to track sales of Store1 and


dump into the main database.
SSIS package of Store1 as the Source and BlockFlix as the Destination.
Once the package is run, data in Store1 will be dumped into the BlockFlix
Database to the necessary tables that needs to be monitored.

This is the Sales Table from BlockFlix with no data before the
package is executed.

This is Store1 Sales Table with some dummy data already


entered in it.

Here is the SSIS Package that has been Executed and the Rows being
added to the BlockFlix Database to the corresponding tables.

After the InStore package ran successfully, BlockFlix database Sales table is
populated with data that was in Store1 database Sales Table.

Reports for the Management


A Report that shows Lost/Damaged movies and their related transactions.

A Report that shows the most Rented Movies in the past month.
A Report that shows the most active customers in the past month.

A Report that shows List of Customers in each Membership

You might also like