Sql Projects-Detail

55
.SQL Portfolio Name: Tahir Rizwan Email: Tahrizwan@yahoo.com Phone : 484-221-8767

description

My Projects detail during the study of SQL server at SetFoucs

Transcript of Sql Projects-Detail

Page 1: Sql Projects-Detail

.SQL Portfolio

Name: Tahir Rizwan

Email: [email protected]

Phone : 484-221-8767

Page 2: Sql Projects-Detail

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

Page 3: Sql Projects-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.

Piggy Bank (Assignment Detail)

Page 4: Sql Projects-Detail

ER Diagram (Piggy Bank)

Page 5: Sql Projects-Detail

****** Object: StoredProcedure [dbo].[Add Customer] Script Date: 10/03/2009 21:29:57 ******/Use PiggyBankGOCREATE 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 outputAS-- Validation of Customer Dataif @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 = '‘

BeginRaiserror ('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 -1End

Begin TryBegin 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 TranEnd TryBegin CatchRollback TranSelect Error_number(), Error_Message() End Catch

Procedure to add New Customers in the database

Page 6: Sql Projects-Detail

/****** Object: StoredProcedure [dbo].[NewAcct] Script Date: 10/03/2009 21:48:17 ******/CREATE Proc [dbo].[NewAcct]@CustID int, @TransAmt money, @GnrOverDrft bit, @AcctID int outputAs--Validation of Customer IDif@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.00if @TransAmt<50BeginRaiserror ('PLease Enter the Deposit Money not Less than $50.00',14,1)Return -1EndBegin TryBegin 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 TranEnd TryBegin CatchRollback TranSelect Error_number(), Error_Message() End Catch

To add New Checking account

Page 7: Sql Projects-Detail

/****** Object: StoredProcedure [dbo].[Deposit] Script Date: 10/15/2009 19:06:24 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOALTER Proc [dbo].[Deposit]@CustID int, @AcctID int, @TransAmt money, @TransID int outputAs--Validation of Customer ID and Account IDif@CustID NOT IN(Select CustomerID from Customer)

BeginRaiserror ('Customer does not Exist in the Database',14,1)Return -1

Endif@AcctID NOT IN(Select AccountID from CustomerAccount where CustomerID=@CustID)

BeginRaiserror ('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

BeginRaiserror ('ACCOUNT IS INACTIVE, FIRST CHANGE THE ACCOUNT TO ACTIVE STATUS',14,1)Return -1End

Set @NewBal=(Select CurrentBalance from Account where AccountID=@AcctID)+ @TransAmt

Deposit Procedure

Page 8: Sql Projects-Detail

Deposit (Cont)Begin TryBegin Tran

insert into dbo.Transactions(AccountID,TransactionTypeID,CustomerID,TransactionDate,TransactionAmount,NewBalance)

values (@AcctID,2,@CustID,GetDate(),@TransAmt,@NewBal) Update AccountSet CurrentBalance = @NewBal where AccountID = @AcctIDCommit TranEnd TryBegin CatchRollback TranSelect Error_number(), Error_Message() End Catch

Page 9: Sql Projects-Detail

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

-- Validation for Account Status

Select @AcctStatus = AccountStatusID from Account where AccountID=@FromAccountif @AcctStatus = 2

BeginRaiserror ('THE ACCOUNT IS INACTIVE, FIRST ACTIVATE THE ACCOUNT TO TRANSFER THE MONEY FROM',14,1)Return -1End

Select @AcctStatus = AccountStatusID from Account where AccountID=@ToAccountif @AcctStatus = 2

BeginRaiserror ('ACCOUNT IS INACTIVE, FIRST ACTIVATE THE ACCOUNT TO TRANSER THE MONEY TO',14,1)Return -1

End

Page 10: Sql Projects-Detail

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

Page 11: Sql Projects-Detail

Transfer Money (Cont)Begin

Select @balance = CurrentBalance from Account where AccountID = @FromAccount

Select @ToBalance = CurrentBalance from Account where AccountID = @ToAccount

If @balance<@Amount -- If there are not enough funds in the account

Begin

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

Page 12: Sql Projects-Detail

TriggersUSE [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 ONGOSET QUOTED_IDENTIFIER ONGOCreate TRIGGER [Security]ON DATABASE FOR DROP_TABLE, ALTER_TABLEAS PRINT 'You are not allowed to Drop or Alter table in the database!' ROLLBACK ;

GOSET ANSI_NULLS OFFGOSET QUOTED_IDENTIFIER OFFGOENABLE TRIGGER [Security] ON DATABASE

Page 13: Sql Projects-Detail

/****** 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 ONGOSET QUOTED_IDENTIFIER ONGOCreate Trigger [dbo].[DelTransact] on [dbo].[Transactions] Instead of Delete not for replicationAsBeginSet NoCount ON;Declare @DelCount int;Select @DelCount = Count(*) FROM Deleted;If @DelCount>0

BeginRaiserror ('Transactions can not be deleted',14,1)If @@Trancount>0

Begin Rollback Transaction;End

EndEndGO/****** Object: Trigger [dbo].[UpdateTrans] Script Date: 06/20/2009 17:38:51 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE Trigger [dbo].[UpdateTrans] on [dbo].[Transactions] Instead of Update not for replicationAsBeginSet NoCount ON;Declare @UpCount int;Select @UpCount = Count(*) FROM Deleted;If @UpCount>0

BeginRaiserror ('Transactions can not be Updated',14,1)If @@Trancount>0

Begin Rollback Transaction;End

EndEnd

Page 14: Sql Projects-Detail

Library Project

Objectives• To create Several Reports to accommodate

business practices of a lending library. • To create a backup schedule for the library

database.

Page 15: Sql Projects-Detail

ER Diagram

adultmember_no

street

city

state

zip

phone_no

expr_date

copyisbn

copy_no

title_no

on_loan

itemisbn

title_no

translation

cover

loanable

juvenilemember_no

adult_member_no

birth_date

loanisbn

copy_no

title_no

member_no

out_date

due_date

loanhistisbn

copy_no

out_date

title_no

member_no

due_date

in_date

fine_assessed

fine_paid

fine_waived

remarks

membermember_no

lastname

firstname

middleinitial

photograph

reservationisbn

member_no

log_date

remarks

titletitle_no

title

author

synopsis

Page 16: Sql Projects-Detail

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

Page 17: Sql Projects-Detail

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

Page 18: Sql Projects-Detail

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 juvenile’s checkout/fine information

Page 19: Sql Projects-Detail

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.

Page 20: Sql Projects-Detail

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.

Page 21: Sql Projects-Detail

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

Page 22: Sql Projects-Detail

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.

Page 23: Sql Projects-Detail

Proposed Backup Schedule for the Library Database

Page 24: Sql Projects-Detail

Proposed Backup Schedule (Cont)

Page 25: Sql Projects-Detail

Proposed Backup Schedule (Cont)

Page 26: Sql Projects-Detail

Proposed Backup Schedule (Cont)

Page 27: Sql Projects-Detail

Proposed Backup Schedule (Cont)

Page 28: Sql Projects-Detail

Proposed Backup Schedule (Cont)

Page 29: Sql Projects-Detail

Proposed Backup Schedule (Cont)

Page 30: Sql Projects-Detail

Proposed Backup Schedule (Cont)

Page 31: Sql Projects-Detail

Proposed Backup Schedule (Cont)

Page 32: Sql Projects-Detail

Proposed Backup Schedule (Cont)

Page 33: Sql Projects-Detail

Proposed Backup Schedule (Cont)

Page 34: Sql Projects-Detail

BlockFlix: Objective

• A fully functional movie database• Track:

– Inventory of Movies– Customer Information– Sales / Checkout– Payment & Fees

Page 35: Sql Projects-Detail

Service Outlets:

• Online Stores

• Local Branches

• Kiosk

Page 36: Sql Projects-Detail

Table Design: (27 tables)

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

Page 37: Sql Projects-Detail

ER Diagram

Page 38: Sql Projects-Detail

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

ASBegin

--Define errors that can be raisedDeclare @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

Page 39: Sql Projects-Detail

--Check for NULL values on input paramemtersIf (@firstName IS NULL

OR @lastName IS NULL OR @address IS Null OR @city IS NULL OR @state IS NULL OR @zip IS NULLOR @MembershipTypeID IS NULL)

BeginRAISERROR(@Error_NULL,10,1)Return

End--Check for whitespaceIf(LTRIM(RTRIM(@firstName))=''

OR LTRIM(RTRIM(@lastName))='' OR LTRIM(RTRIM(@address))='' OR LTRIM(RTRIM(@city))='' OR LTRIM(RTRIM(@state))='')

BeginRAISERROR(@ERROR_White,10,1)Return

End--Check that the phone numbers are in the proper formatIf ((@phone IS NOT NULL) AND (@phone NOT Like '___-___-____'))Begin

RAISERROR(@ERROR_BadPhone#,10,1)Return

End

--Check that the membershipID Exist in the databaseSet @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)

Page 40: Sql Projects-Detail

--Check that the customer does not currently Exist in the databaseSet @findCustomer = (Select customerID

From CustomersWhere 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 databaseSet @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 validIf not exists (Select PaymentTypeID from PaymentTypes where PaymentTypeID=@paymentTypeID)BeginRaiserror ('Payment Type ID is Invalid',14,1) Return -1

End

Procedure: To add New Customer (Cont)

Page 41: Sql Projects-Detail

Begin TryBegin 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 tableInsert 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 onIF(@subscription = 1)Insert into

dbo.CustomerCreditInfo(customerID,cardNumber,cardTypeID,expr_date,authorizationCode)Values(@customerID,@cardNumber,@cardTypeID,@card_expr_date,@authorizationCode)

Set @monthly_price = (Select monthly_price From memberships Where membershipTypeID = @membershipTypeID)--Update paymentHistoryInsert into dbo.MemberPaymentHistory(customerID,date_paid,paymentTypeID, membershipID,monthly_price,quantity)Values(@customerID,GetDate(),@paymentTypeID,@membershipTypeID,@monthly_price,@months_purchased)

Commit TranEnd TryBegin Catch

Rollback TranDeclare @ErrorMessage varchar(85)Declare @ErrorSeverity intDeclare @ErrorState int

Set @ErrorMessage = Error_Message()Set @ErrorSeverity = Error_Severity()Set @ErrorState = Error_State()

RAISERROR(@ErrorMessage,@ErrorSeverity,@ErrorState)Return

End CatchEnd

Procedure: To add New Customer (Cont)

Page 42: Sql Projects-Detail

/* 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 CustomerStatusCheckAS Begin

Begin TryBegin Tran

--If expr_date is more then 1 month and 7 days delinquentUpdate 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 TranEnd TryBegin Catch

Rollback Tran

Declare @ErrorMessage varchar(85)Declare @ErrorSeverity intDeclare @ErrorState int

Set @ErrorMessage = Error_Message()Set @ErrorMessage = Error_Severity()Set @ErrorMessage = Error_State()

RAISERROR(@ErrorMessage,@ErrorSeverity,@ErrorState)Return

End CatchEnd

Procedure: To Check Customer’s Status

Page 43: Sql Projects-Detail

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.

Page 44: Sql Projects-Detail

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

Page 45: Sql Projects-Detail

• This is Store1 Sales Table with some dummy data already entered in it.

Page 46: Sql Projects-Detail

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

Page 47: Sql Projects-Detail

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

Page 48: Sql Projects-Detail

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

Page 49: Sql Projects-Detail
Page 50: Sql Projects-Detail
Page 51: Sql Projects-Detail
Page 52: Sql Projects-Detail
Page 53: Sql Projects-Detail
Page 54: Sql Projects-Detail
Page 55: Sql Projects-Detail