Upload
paul-glaeser
View
600
Download
1
Tags:
Embed Size (px)
DESCRIPTION
Sample code from work done in SQL Masters course completed at SetFocus
Citation preview
SQL SQL
PortfolioPortfolio
Paul GlaeserPaul Glaeser
[email protected]@ieee.org610-327-3801610-327-3801
Table of ContentsTable of Contents
Introduction – 3
BlockFlix Movie Rental -4
BlockFlix SSIS – 6
BlockFlix SSRS - 10
Piggy Bank - 14
Shred XML – 16
View - 17
Triggers – 18
Stored Procedure -19
IntroductionIntroduction
This Presentation will illustrate key skills learned in the SQL Masters course such as SSIS,
SSRS,
SQLServer,
T-SQL,
Triggers
and Views
BlockFlix Movie RentalBlockFlix Movie Rental
• Introduction:Introduction:• BlockFlix is a new and upcoming Movie Rental company. They have opened a few BlockFlix is a new and upcoming Movie Rental company. They have opened a few
stores nationwide and are in process of creating a centralized database for stores nationwide and are in process of creating a centralized database for tracking inventory, sales, customers and memberships.tracking inventory, sales, customers and memberships.
• Audience:Audience:• 3C executives to technical level employees.3C executives to technical level employees.
• Project Goals:Project Goals:• Develop the Central Database, Store database and Kiosk Database.Develop the Central Database, Store database and Kiosk Database.• Develop the xml file format for the vendor to use to submit movies as well as the Develop the xml file format for the vendor to use to submit movies as well as the
SSIS package to read and load the data in the file.SSIS package to read and load the data in the file.• Develop the 4 core reports requested in SSRSDevelop the 4 core reports requested in SSRS
– Most Rented Movie in past month, List of Customers and Membership typeMost Rented Movie in past month, List of Customers and Membership type– Most active Customers in past month, Lost/Damaged movies with related TransactionsMost active Customers in past month, Lost/Damaged movies with related Transactions
Database DiagramDatabase Diagram
Transactions
PK TransactionID
FK6 StoreIDFK8 LoanIDFK2 MemberIDFK1 TransactionTypeID TransactionDate TransactionAmount
TransactionType
PK TransactionTypeID
TransactionTypeName
Member
PK MemberID
FName LName MI Street City State ZipCode Email HomePhone WorkPhone CellPhone MemberStatus MembershipType
Movie
PK MovieID
Title Genre PGRating Year
Talent
PK TalentID
FName LName
Queue
PK QueID
ListOrder MovieIDFK1 MemberID
StoreLocations
PK StoreID
StoreName Address1 Address2 City State
Loan
PK LoanID
FK1 DiskID CheckinDate CheckoutDate
MovieTalent
PK MovieTalentID
FK2 MovieIDFK1 TalentID TalentType
Disk
PK DiskID
FK1 MovieID MediaType RentStatus LostDamaged
Sample XML InputSample XML Input
IMPORT XML FILE VIA SSIS AFTER CONTROL FLOW EXECUTION
ADD MOVIE Demonstration
Consisting of 3 linked data flows
IMPORT XML FILE VIA SSIS AFTER MOVIE/TALENT EXECUTION
ADD MOVIE Demonstration
IMPORT XML FILE VIA SSIS AFTER MOVIE/TALENT EXECUTION
ADD MOVIE Demonstration
Most active customers in the past month
Most rented movies in the past month
Lost / damaged movies and their related transactions
Customers and Membership Types
P I G G Y - B A N K• Introduction:• Basic banking application with customers, accounts, transactions, interest , overdraft and
statements
• Audience:• Technical Management , Developers etc.
• Project Goals:• For Customers Create and update the Customer information• Accounts – support Checking and Savings• Overdraft – account specific and general• Transactions – Deposits, Withdrawals/Purchases, Transfers• Interest Rates can be applied• Build view for ATM procedures and search engine queries• Protective Triggers
Database DiagramDatabase Diagram
CustomerAccount
PK CustomerAccountID int identity
FK1 AccountID intFK2 CustomerID int
Account
PK AccountID int identity
FK1 AccountTypeID tinyintFK2 AccountStatusID tinyint CurrentBalance money OverDraftAccountID int GeneralOverdraft bit
Transactions
PK TransactionID int identity
FK1 AccountID intFK2 TransactionTypeID tinyintFK3 CustomerID int TransactionDate datetime TransactionAmount money NewBalance money
AccountStatus
PK AccountStatusID tinyint identity
AccountStatus nvarchar(25)
TransactionType
PK TransactionTypeID tinyint identity
TransactionTypeName varchar(20)
AccountType
PK AccountTypeID tinyint identity
AccountTypeName nvarchar(9) InterestRate decimal(4,2)
Customer
PK CustomerID int identity
CustomerFirstName varchar(20) CustomerLastName varchar(30) CustomerMiddleInitial varchar(1) Street varchar(50) City varchar(20) State char(2) ZipCode char(10) Email varchar(30) HomePhone char(12) WorkPhone char(12) CellPhone char(12)
Shred Xml into Database TableShred Xml into Database Table/* Shred XML Data into appropriate tables *//* Shred XML Data into appropriate tables */-- Declare xml variable to handle xml input-- Declare xml variable to handle xml inputDECLARE @doc xmlDECLARE @doc xmlSET @doc = '<?xml version="1.0" SET @doc = '<?xml version="1.0"
encoding="utf-8"?>encoding="utf-8"?><Bank><Bank>
<Customer ID="1" FirstName="John" <Customer ID="1" FirstName="John" LastName="Doe" Street="123, Fake LastName="Doe" Street="123, Fake Street" City="Anytown" State="NY" Street" City="Anytown" State="NY" Zip="11280" HomePhone="555-123-Zip="11280" HomePhone="555-123-4567" WorkPhone="555-456-7890" 4567" WorkPhone="555-456-7890" MobilePhone="555-111-2345" MobilePhone="555-111-2345" EMail="[email protected]">EMail="[email protected]">
<Accounts><Accounts><Saving <Saving
ID="100000" Balance="548.25" ID="100000" Balance="548.25" Active="1">Active="1">
<Transactions><Transactions>
<Transaction ID="1" Type="Initial <Transaction ID="1" Type="Initial Deposit" Date="4/01/2009" Deposit" Date="4/01/2009" Amount="500.00" Amount="500.00" NewBalance="500.00" />NewBalance="500.00" />
<Transaction ID="5" <Transaction ID="5" Type="Deposit" Date="4/01/2009" Type="Deposit" Date="4/01/2009" Amount="50.00" Amount="50.00" NewBalance="550.00" />NewBalance="550.00" />
</Transactions></Transactions></Saving></Saving>
</Accounts></Accounts></Customer></Customer>
-- Declare variable to handle the xml document in the -- Declare variable to handle the xml document in the sp_xml_preparedocumentsp_xml_preparedocument
DECLARE @docHandle intDECLARE @docHandle int-- Put XML into memory-- Put XML into memoryEXEC sp_xml_preparedocument @docHandle OUTPUT, @docEXEC sp_xml_preparedocument @docHandle OUTPUT, @doc--toggle identity on--toggle identity onSet identity_insert dbo.Transactions onSet identity_insert dbo.Transactions oninsert into dbo.Transactions (TransactionID, AccountID, insert into dbo.Transactions (TransactionID, AccountID,
TransactionTypeID, CustomerID, TransactionDate, TransactionTypeID, CustomerID, TransactionDate, TransactionAmount, NewBalance)TransactionAmount, NewBalance)
SELECT TransactionID, AccountID, SELECT TransactionID, AccountID, CASE CASE
WHEN [Type] = 'Initial Deposit'WHEN [Type] = 'Initial Deposit' THEN 1 THEN 1 WHEN [Type] = 'Deposit'WHEN [Type] = 'Deposit' THEN 2 THEN 2 WHEN [Type] = 'Withdrawal'WHEN [Type] = 'Withdrawal' THEN 3 THEN 3 WHEN [Type] = 'Transfer-Withdrawal' THEN 4WHEN [Type] = 'Transfer-Withdrawal' THEN 4 WHEN [Type] = 'Transfer-Deposit' THEN 5WHEN [Type] = 'Transfer-Deposit' THEN 5 WHEN [Type] = 'Checkcard Purchase' THEN 6WHEN [Type] = 'Checkcard Purchase' THEN 6 ELSE 7 -- [Type] = 'Check'ELSE 7 -- [Type] = 'Check' END,END, CustomerID, TransactionDate, CustomerID, TransactionDate,
TransactionAmount,NewBalanceTransactionAmount,NewBalanceFROM OPENXML (@docHandle, FROM OPENXML (@docHandle,
'/Bank/Customer/Accounts/*/Transactions/Transaction', 1)'/Bank/Customer/Accounts/*/Transactions/Transaction', 1)WITH ( TransactionIDWITH ( TransactionID int '@ID'int '@ID'
, AccountID, AccountID int '../../@ID'int '../../@ID' , [Type], [Type] varchar(20) '@Type'varchar(20) '@Type' , CustomerID, CustomerID int '../../../../@ID'int '../../../../@ID' , TransactionDate, TransactionDate datetime '@Date'datetime '@Date' , TransactionAmount money, TransactionAmount money '@Amount' '@Amount' , NewBalance, NewBalance moneymoney '@NewBalance' ) '@NewBalance' )
-- toggle identity back off-- toggle identity back off Set identity_insert dbo.Transactions offSet identity_insert dbo.Transactions off-- remove xml information from memory-- remove xml information from memoryexecute sp_xml_removedocument @docHandleexecute sp_xml_removedocument @docHandle
Create View for StatementsCreate View for StatementsCREATE VIEW [dbo].[AccountStatement] WITH SCHEMABINDINGASSELECT dbo.Account.CurrentBalance, dbo.Account.AccountID, dbo.TransactionType.TransactionTypeName, dbo.AccountStatus.AccountStatus, dbo.AccountType.AccountTypeName, dbo.AccountType.InterestRate, dbo.Customer.CustomerID, dbo.Customer.CustomerFirstName, dbo.Customer.CustomerLastName, dbo.Customer.CustomerMiddleInitial, dbo.Customer.Street, dbo.Customer.City, dbo.Customer.State, dbo.Customer.ZipCode, dbo.Customer.HomePhone, dbo.Transactions.TransactionDate, dbo.Transactions.TransactionAmount,dbo.Transactions.NewBalanceFROM dbo.Account INNER JOIN dbo.AccountStatus ON dbo.Account.AccountStatusID = dbo.AccountStatus.AccountStatusID INNER JOIN dbo.AccountType ON dbo.Account.AccountTypeID = dbo.AccountType.AccountTypeID INNER JOIN dbo.CustomerAccount ON dbo.Account.AccountID = dbo.CustomerAccount.AccountID INNER JOIN dbo.Customer ON dbo.CustomerAccount.CustomerID = dbo.Customer.CustomerID INNER JOIN dbo.Transactions ON dbo.Account.AccountID = dbo.Transactions.AccountID AND dbo.Customer.CustomerID = dbo.Transactions.CustomerID INNER JOIN dbo.TransactionType ON dbo.Transactions.TransactionTypeID = dbo.TransactionType.TransactionTypeID
Triggers to protect DataTriggers to protect Data
CREATE TRIGGER PreventChange ON DATABASE FOR DROP_TABLE, ALTER_TABLE AS PRINT 'You must disable Trigger "PreventChange" to drop or alter tables!' ROLLBACK
CREATE TRIGGER DelTrans ON [dbo].[Transactions]INSTEAD OF DELETE ASBEGIN Raiserror('Deletes of Transactions not allowed', 13,1); ROLLBACK TRAN;
END
Create Trigger DelAccount on [dbo].[Account]INSTEAD OF DELETE ASBEGIN Raiserror('Deletes of Accounts not allowed', 13,1); ROLLBACK TRAN;
END
CREATE TRIGGER UpdTran ON [dbo].[Transactions]INSTEAD OF UPDATE ASBEGIN Raiserror('Updates of Transactions not allowed', 14,1); ROLLBACK TRAN;
END
Stored Procedures with T-Stored Procedures with T-SQLSQL
CREATE PROCEDURE [dbo].[Deposit]-- Add the parameters for the stored procedure here@CustomerID int = NULL, @AccountID int = NULL,@TransactionAmount money = NULL
ASBEGIN TRY BEGIN TRAN
-- SET NOCOUNT ON added to prevent extra result sets from-- interfering with SELECT statements.SET NOCOUNT ON;
-- Check for null valuesif @AccountID is nullBEGIN
raiserror('Account ID must be provided', 12, 1);ENDif @CustomerID is nullBEGIN raiserror('Customer ID must be provided', 12, 2);END If @TransactionAmount Is Null BEGIN
raiserror('Transaction Amount must be provided', 12, 3);END
--check valid Custid and accountidif @AccountID != (SELECT AccountID FROM Account WHERE
AccountID = @AccountID)BEGIN raiserror('Account ID is invalid', 12, 4);ENDif @CustomerID != (SELECT CustomerID FROM Customer WHERE
CustomerID = @CustomerID)BEGINraiserror('Customer ID is invalid', 12, 5);END
--Fetch current balance to calculate new balanceDECLARE @CURRBAL money = (SELECT CurrentBalance FROM Account WHERE AccountID = @AccountID),
@NewBalance money = NULL,@TransactionTypeID tinyint = 2,@AcctStatID tinyint = 1
SET @NewBalance = @CURRBAL + @TransactionAmount;
-- Insert statements for procedure here-- check account active
if @AcctStatID != (SELECT AccountStatusID FROM Account WHERE AccountID = @AccountID)
BEGINRaiserror('Can not Deposit for Inactive Account', 12, 6);
ENDBEGININSERT INTO [PIGGYBank].[dbo].[Transactions]
([AccountID] ,[TransactionTypeID] ,[CustomerID] ,[TransactionDate] ,[TransactionAmount] ,[NewBalance]) VALUES (@AccountID ,@TransactionTypeID ,@CustomerID ,CURRENT_TIMESTAMP ,@TransactionAmount ,@NewBalance);
UPDATE [PIGGYBank].[dbo].[Account]SET [CurrentBalance] = @NewBalance
WHERE AccountID = @AccountID;END
COMMIT TRANEND TRY
BEGIN CATCH if @@TRANCOUNT > 0 ROLLBACK TRAN DECLARE @ErrorMessage NVARCHAR(4000); DECLARE @ErrorSeverity INT; DECLARE @ErrorState INT; --populate vars with error info SELECT @ErrorMessage = ERROR_MESSAGE(), @ErrorSeverity = ERROR_SEVERITY(), @ErrorState = ERROR_STATE(); -- rethrow pass to front end or another proc RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);END CATCH