SQL Server 2008 Portfolio

32
SQL Portfolio Anthony Feliciano Anthony.Feliciano@setfo cus.com (831) 295-4440

description

SQL Server 2008 Portfolio

Transcript of SQL Server 2008 Portfolio

Page 1: SQL Server 2008 Portfolio

SQL Portfolio

Anthony [email protected](831) 295-4440

Page 2: SQL Server 2008 Portfolio

Table of Contents

• What is SetFocus ?• Transact-SQL samples: Pivot and CTE• SSMS Project “Piggy Bank”• Diagram and Withdrawal Stored Procedure

• SSIS /SSRS Project “MiniAdventureWorks”• Data and Control Flows, Matrix Report• SSRS Report with Gauge

• Final Project “BlockFlix”• Database Diagram, Control and Data Flows, Stored

Procedures and Streaming Video Proposal

Page 3: SQL Server 2008 Portfolio

What is SetFocus?• The SetFocus SQL Master’s Program is an intensive, hands–

on, project-oriented program that combines knowledge and valuable experience in putting the SQL skill set to use in a simulated work environment.

• I received almost 320 hours of in-depth hands on

experience which focused on T-SQL Development, SSIS and SSRS Packages.

• SetFocus projects are real world projects that are just like those I would receive in a position. I received project specifications and was expected to identify best courses of action within very tight deadlines for completion.

Page 4: SQL Server 2008 Portfolio

Transact-SQL: A Pivot Sample• use AdventureWorks2008• GO• -- We want to take the orders in 2003, group them by Vendor and by Month• -- We can use the PIVOT statement to convert rows to analytic columns

• -- First we'll retrieve Orders from 2003 and place into a CTE• WITH OrdCTE AS (• SELECT VendorID, Name As VendorName, DatePart(m,OrderDate) AS OrderMonth, POHdr.TotalDue• FROM Purchasing.PurchaseOrderHeader POHdr• join Purchasing.Vendor ON Vendor.BusinessEntityID = POHdr.VendorID• where YEAR(OrderDate) = 2003 )• • -- Now we'll query the CTE, and use a PIVOT statement • SELECT VendorID, VendorName, [1] AS Jan, [2] AS Feb, [3] AS Mar, [4] AS Apr, [5] AS May, [6] AS June, [7] AS July, [8] AS Aug, [9] AS Sep, [10] AS Oct,

[11] AS Nov, [12] AS Dec FROM OrdCTE• -- we take each of the 12 possible values and associate them with 12 buckets• PIVOT (SUM(TotalDue) FOR OrderMonth IN ( [1],[2],[3],[4],•

[5], [6], [7], [8], -- Note, these 12 values are static•

[9], [10], [11], [12] ) ) as TempList -- We'd need to use dynamic SQL if they weren't• •

Page 5: SQL Server 2008 Portfolio

Transact-SQL: CTE exampleA Common Table Expression is a temporary named result set which is later used in a queryOnce it’s used, it’s gone

• USE AdventureWorks2008• GO

• -- Put all vendors with a Credit Rating of 2 into one CTE• -- Put all orders with a line item unit price > 25 in another CTE

• ;WITH VendorCTE AS • (SELECT Vendor.AccountNumber, Vendor.BusinessEntityID, Vendor.Name• FROM Purchasing.Vendor WHERE CreditRating = 2) , • OrderCTE AS • (SELECT VendorID, SUM(TotalDue) AS SumTotalDue • FROM Purchasing.PurchaseOrderHeader POH• JOIN Purchasing.PurchaseOrderDetail POD ON POH.PurchaseOrderID = POD.PurchaseOrderID• WHERE UnitPrice > 25.00• GROUP BY VendorID)

• -- And then query against them • SELECT VendorCTE.AccountNumber, VendorCTE.Name, SumTotalDue • FROM VendorCTE• JOIN OrderCTE ON VendorCTE.BusinessEntityID = OrderCTE.VendorID• ORDER BY SumTotalDue DESC

Page 6: SQL Server 2008 Portfolio

Bookstore Database Diagram

Page 7: SQL Server 2008 Portfolio

User Defined Function sample using Cross Apply

• -- Create a User Defined Function that gets the top N books for a customer for a year (2007)• -- First, create a Table-Valued Function GetTopNBooksByCustomer that would perform the RANKING on the inside...just for the one customer• -- We could do a TOP N and A RANK in the TVF...just for one customer• -- Run that TVF and apply it to every customer by using a CROSS APPLY against DimCustomers BookSales;• use BookSales• GO• ALTER FUNCTION dbo.TopNSalesbyCustomer• (@CustomerPk int,@N int)• RETURNS TABLE• AS• RETURN• • SELECT TOP (@N) C.CustomerName as Customer, B.BookName as BookName, SUM(FSB.SalesDollars) TotalDollars• from DimCustomers C, FactBookSales FSB, DimDates D, DimBooks B, DimBookPrice P• where D.DatePK = FSB.DatePK and• FSB.CustomerPK = C.CustomerPK and• FSB.BookPricePK = P.BookPricePK and • P.BookTitlePK = B.BookTitlePK • and DATEPART(YEAR, ActualDate) = 2007• and C.CustomerPk = @CustomerPK• group by C.CustomerName, B.BookName• GO• SELECT CustomerName, X.Bookname, X.TotalDollars• from DimCustomers• cross apply dbo.TopNSalesbyCustomer(DimCustomers.CustomerPK,5) as X• ORDER BY CustomerName, TotalDollars desc;

Page 8: SQL Server 2008 Portfolio

“PiggyBank” Project

• Introduction: A real world, transaction-based application where T-SQL and SSMS are used extensively to carry out a retail bank’s mission-critical operations, among others

• Project Goal: Build a retail banking applicationusing the tools available in SQL Server 2008

• Audience: Bank President, Vice-Presidents, Managers and Tellers, Security Administrators

Page 9: SQL Server 2008 Portfolio

Database Diagram for PiggyBank

AccountAccountID

AccountStatusId

AccountTypeID

CurrentBalance

OverdraftAccountID

GeneralOverdraft

AccountStatusAccountStatusID

AccountStatus

AccountTypeAccountTypeId

AccountTypeName

InterestRate

CustomerCustomerID

CustomerFirstName

CustomerLastname

CustomerMiddleInitial

Street

City

State

ZipCode

Email

Homephone

Workphone

Cellphone

TransactionsTransactionID

AccountID

TransactionTypeID

CustomerId

TransactionDate

TransactionAmount

NewBalance

TransactionTypeTransactionTypeID

TransactionTypeName

CustomerAccountCustomerAccountID

AccountID

CustomerID

MaintenanceLogTransactionId

AccountId

MaintenanceType

CustomerID

TransactionDate

TransactionAmount

NewBalance

Page 10: SQL Server 2008 Portfolio

Stored Procedure: Withdrawal transaction

• -- Author: <Anthony Feliciano>• -- Create date: <26-July.2010>• -- Description: <Withdrawal Procedure>• --Applicable for:• -- Cash Withdrawals <Transaction 3>• -- Transfer Withdrawals <Transaction 4>• -- Debit Purchases <Transaction 6>• -- Checks <Transaction 7>• -- =============================================• -- ================================================• -- =============================================• -- Withdrawal business rules Procedure for PIGGY BANK, N. A. application• -- 1. Upon presentation of a valid ATM card the procedure will validate the amount requested for withdrawal.• -- 2. When prompted, the customer will indicate whether the WITHDRAWAL is meant for checking or savings.• -- 3. The procedure will check if the customer has an active account. • -- 4. If the requested target account is active, the transaction amount will be compared against the available balance.• -- 5. If deducting the requested withdrawal amt results in a negative balance the procedure will check see if there is enough money• -- in the linked account to accommodate the withdrawal.• -- 6. If there are available funds in the linked account, and the resulting balance does not go below 0.00 in the linked account,• -- the withdrawal will go through and a fee of $10.00 will be assessed to the originating account. • -- 7. If there are no linked accounts, the procedure will verify if the account has a general overdraft "credit line". • -- If this General Overdraft account is present, and the resulting balance in the General Overdraft does not go below -400.00, the withdrawal will

----- be allowed. For this type of coverage, a $30 fee will be assessed.• -- 8. In either type of overdraft coverage, the fee will appear as a separate transaction.• -- 9. NOTE: For this project, all transactions that withdraw money from an account (i.e.,• --- Cash at an ATM, Debit Purchase or Check - will be treated the same. • -- =============================================

Page 11: SQL Server 2008 Portfolio

Withdrawal transaction: p.2• CREATE PROCEDURE dbo.Withdrawal• -- All these parameters can be supplied in just one data entry screen --• @CustomerId int = NULL,• @AccountID int = NULL,• @AccountTypeId tinyint = NULL,• @TransactionType tinyint = NULL,• @TransactionAmount money = NULL• AS• SET NOCOUNT ON• BEGIN TRY• -- Validate the CustomerAccountId first• if NOT EXISTS (SELECT * FROM dbo.CustomerAccount• WHERE CustomerID = @CustomerId• and AccountID = @AccountID)• BEGIN• raiserror('CustomerId and Account Invalid',11,1)• END• • -- Check to see if AccountTypeId exists in the Account Table• if NOT EXISTS (SELECT * FROM dbo.Account• WHERE AccountID = @AccountID • AND AccountTypeId = @AccountTypeId)• BEGIN• raiserror ('Invalid Account Type',11,2)• END•

Page 12: SQL Server 2008 Portfolio

Transaction Withdrawal: p.3• -- Check to see if Account is Active and allows withdrawals --• if (SELECT AccountStatusId FROM dbo.Account• WHERE AccountID = @AccountID) = 2• BEGIN• raiserror ('Withdrawal not allowed for this account',11,3)• END

-- Check to see if there are available funds in the Primary Account --• declare @resulting_bal money• declare @current_bal money• set @current_bal = (SELECT CurrentBalance from dbo.Account• WHERE AccountID = @AccountID)• set @resulting_bal = @current_bal - @TransactionAmount• if @resulting_bal < 0.00• BEGIN• declare @OD_Account int• set @OD_Account = (SELECT OverdraftAccountID from dbo.Account • where AccountID = @AccountID)• if @OD_Account IS NULL• BEGIN --do this• if (SELECT GeneralOverdraft from dbo.Account• where AccountID = @AccountID) = 0 /* 0 = no General Overdraft• 1 there is $400 credit */• BEGIN• raiserror ('No Linked Account NOR General Overdraft Account',11,4)• raiserror ('Withdrawal Refused',11,5)• END• else

Page 13: SQL Server 2008 Portfolio

Transaction withdrawal: p.4• BEGIN• set @resulting_bal = 400.00 - @TransactionAmount• if @resulting_bal < 0.00 • BEGIN• raiserror ('Not enough money to cover

withdrawal',11,5)• END• else• BEGIN• INSERT INTO dbo.Transactions

• (AccountId,• TransactionTypeID,• CustomerId,• TransactionDate,• TransactionAmount,• NewBalance)• VALUES• (@AccountID,• @TransactionType,• @CustomerId,• GETDATE(),• @TransactionAmount,• @resulting_bal)• • declare @NewBalance money• declare @GeneralOverdraftFee money = 30.00• set @NewBalance = @current_bal - @GeneralOverdraftFee

Page 14: SQL Server 2008 Portfolio

Withdrawal Transaction: p.5• INSERT into dbo.Transactions • (AccountId,• TransactionTypeID, • CustomerId,• TransactionDate,• TransactionAmount,• NewBalance)•

• VALUES• (@AccountID,• @TransactionType,• @CustomerId,• GETDATE(),• @GeneralOverdraftFee,• @NewBalance)• UPDATE dbo.Account • set CurrentBalance = CurrentBalance -

@GeneralOverdraftFee• where AccountID = @AccountID• END• END• END• else

Page 15: SQL Server 2008 Portfolio

Withdrawal Transaction: p.6• BEGIN• declare @OverdraftAccountBalance money• declare @OverdraftAccountResultingBal money• declare @OverdraftAccountId int• set @OverdraftAccountId = (SELECT OverdraftAccountID from dbo.Account• WHERE AccountID = @AccountID)• set @OverdraftAccountBalance = (SELECT CurrentBalance from dbo.Account• WHERE AccountID = @OverdraftAccountId)• set @OverdraftAccountResultingBal = @OverdraftAccountBalance - @TransactionAmount• if @OverdraftAccountResultingBal < 0.00• BEGIN• raiserror ('Amount Insufficient for Withdrawal,',11,6)• raiserror ('Debit Purchases or Checks',11,7)• END• else• BEGIN • UPDATE dbo.Account • set CurrentBalance = CurrentBalance - @TransactionAmount• where AccountID=@OverdraftAccountId• INSERT INTO dbo.Transactions• (AccountId,• TransactionTypeID,• CustomerId,• TransactionDate,• TransactionAmount,• NewBalance)

Page 16: SQL Server 2008 Portfolio

Withdrawal Transaction: p.7• VALUES• (@OverdraftAccountId, /* NOT the Primary Account! */• @TransactionType,• @CustomerId, • GETDATE(),• @TransactionAmount,• @OverdraftAccountResultingBal)• declare @OverdraftFee money = 10.00• set @NewBalance = @current_bal - @OverdraftFee

• INSERT into dbo.Transactions • (AccountId,• TransactionTypeID, • CustomerId,• TransactionDate,• TransactionAmount,• NewBalance)• VALUES• (@AccountID,• @TransactionType,• @CustomerId,• GETDATE(),• @OverdraftFee,• @NewBalance)• UPDATE dbo.Account • set CurrentBalance = CurrentBalance - @OverdraftFee

where AccountID = @AccountID• END • END• END• •

Page 17: SQL Server 2008 Portfolio

Withdrawal Transaction: p.8• else• BEGIN• INSERT INTO dbo.Transactions• (AccountId,• TransactionTypeID,• CustomerId,• TransactionDate,• TransactionAmount,• NewBalance)• VALUES• (@AccountID,• @TransactionType,• @CustomerId,• GETDATE(),• @TransactionAmount,• @resulting_bal)• UPDATE dbo.Account • set CurrentBalance = CurrentBalance - @TransactionAmount• where AccountID = @AccountID• END • END TRY• BEGIN CATCH• DECLARE @ErrorMessage NVARCHAR(4000);• DECLARE @ErrorSeverity INT;• DECLARE @ErrorState INT;• SELECT @ErrorMessage = ERROR_MESSAGE(), @ErrorSeverity = ERROR_SEVERITY(),• @ErrorState = ERROR_STATE();• -- rethrow goes to front end c#• RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);• END CATCH

Page 18: SQL Server 2008 Portfolio

SSIS/SSRS Project: MiniAdventureWorks

• Specifications: Import .csv data into tables for Purchase Header Orders and Purchase Details

• Aggregate the PO Details by PO Header No.• Build SSIS Packages with Control and Data Flows

showing the importation/aggregation processes• Build Matrix and Table reports using SSRS• Deploy packages and create data subscriptions

Page 19: SQL Server 2008 Portfolio

Control Flow: Import Purchase Header Order Package

Page 20: SQL Server 2008 Portfolio

Data Flow: Purchase Header Order Package

Page 21: SQL Server 2008 Portfolio

SSRS Matrix Report

Page 22: SQL Server 2008 Portfolio

SSRS Matrix Report with Gauge

Page 23: SQL Server 2008 Portfolio

SSRS Table Report

Page 24: SQL Server 2008 Portfolio
Page 25: SQL Server 2008 Portfolio

Final Project Blockflix:Specifications in a nutshell

• Design a business model patterned after Netflix and Blockbuster

• Members can rent a movie online, or through a retail store in their neighborhood

• Use XML to introduce movies into the catalog• Create procedures to handle all transactions• Create packages in SSIS for nightly batch runs• Create reports in SSRS for management use

Page 26: SQL Server 2008 Portfolio

AddMovieMaster Package Control Flow

Page 27: SQL Server 2008 Portfolio

AddMovieMaster PackageData Flow

Page 28: SQL Server 2008 Portfolio

XML to add a movie to the catalog• <?xml version="1.0"?>• <xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">• <xs:element name="List">• <xs:complexType>• <xs:sequence>• <xs:element minOccurs="0" maxOccurs="unbounded" name="row">• <xs:complexType>• <xs:attribute name="Movie_ID" type="xs:unsignedInt" use="optional" />• <xs:attribute name="Disk_ID" type="xs:unsignedByte" use="optional" />• <xs:attribute name="Title" type="xs:string" use="optional" />• <xs:attribute name="Genre" type="xs:string" use="optional" />• <xs:attribute name="Rating" type="xs:string" use="optional" />• <xs:attribute name="Year" type="xs:unsignedShort" use="optional" />• <xs:attribute name="MediaType" type="xs:string" use="optional" />• <xs:attribute name="D1FirstName" type="xs:string" use="optional" />• <xs:attribute name="D1LastName" type="xs:string" use="optional" />• <xs:attribute name="A1FirstName" type="xs:string" use="optional" />• <xs:attribute name="A1LastName" type="xs:string" use="optional" />• <xs:attribute name="D2FirstName" type="xs:string" use="optional" />• <xs:attribute name="D2LastName" type="xs:string" use="optional" />• <xs:attribute name="P1FirstName" type="xs:string" use="optional" />• <xs:attribute name="P1LastName" type="xs:string" use="optional" />• </xs:complexType>• </xs:element>• </xs:sequence>• </xs:complexType>• </xs:element>• </xs:schema>

Page 29: SQL Server 2008 Portfolio

Add a member Transaction• USE [BlockFlix]• GO

• DECLARE @return_value int,• @member_id int

• EXEC @return_value = [dbo].[CreateMember]• @membership_type_id = 2,• @first_name = N'David',• @middle_initial = NULL,• @last_name = N'Jaciow',• @street_address = N‘1600 Pennsylvania Avenue',• @city = N‘Washington',• @state = N‘DC',• @zip_code = N'02001',• @phone_number = N'555-123-1234',• @email = N'[email protected]',• @payment_type_id = 1,• @payment_amt = 8.99,• @credit_card_number = N'0000-0000-0000-0000',• @member_id = @member_id OUTPUT

• SELECT @member_id as N'@member_id'• SELECT 'Return Value' = @return_value

• GO•

Page 30: SQL Server 2008 Portfolio

SSRS Report rendered in PDF

Page 31: SQL Server 2008 Portfolio

SSRS Report rendered in Excel

Page 32: SQL Server 2008 Portfolio

Streaming Video (VOD) Proposal• BlockFlix Entertainment, Inc.• Streaming Video Proposal• September 3, 2010

• What’s needed from BlockFlix: A cluster of 24 x 7 high-availability media player servers is absolutely necessary. An upload speed of 100 megabits/second will assure the best video quality. At any time during the day, as many as 1,000 members can be logged on. Ideally, BlockFlix should be ready to “deliver” a movie online to each and every one of those members. A video streaming licensing agreement should have to be written up between the movie studio and BlockFlix, much like a DVD/Blu-Ray licensing agreement. The movie studio will charge a royalty fee to BlockFlix for every viewing of a movie title. BlockFlix gets billed every time a member requests to view the movie online. Details are described below.

• What’s needed from the Member: A high-speed internet connection capable of at least T1 speed, or 1.5 Megabytes (not megabits) per second is required for best video quality. The faster the download speed, the better. The member can view the movie straight through a PC with a processor speed of at least 1.5 GHz with an Nvidia Video Card issued in 2004 or later, or a video box that can be purchased directly from BlockFlix for $199. (A similar box can be purchased at Best Buy for about $249). For true stereophonic quality, the PC or box will need a special sound card.

• How it works: A member, whose account is up to date, decides to watch a movie online instead of waiting one more day (maybe even two) for a DVD in the mail. He goes into his Blockflix account online, and chooses one of the 200+ selections available. A request emanates from the BlockFlix website that sends a request to the movie studio’s server. The movie studio’s server issues an invoice to Blockflix and sends a copy of an .asx file with that invoice. (.ASX is a streaming video file extension). BlockFlix then bills the member $4.99 for the movie, the member accepts the charges in a pop-up window, and a “movie viewer” opens up in the member’s PC or video box. The movie viewer has rewind/fast forward and pause capabilities, however it cannot stop at the end of a chapter, or resume playing (after a full stop) at the beginning of a chapter the way a DVD can. Just like in a movie theater, the member has to pretty much view the whole movie in one sitting. The movie studios that are offering streaming videos have gone to great lengths in preventing members from copying their movies. This is of course is piracy, and is a federal offense in addition to carrying huge penalties. A warning to this effect is displayed at the beginning of the movie.

• Initial Rollout and future expansion: At the outset, only 200 of the most popular titles in BlockFlix’s DVD inventory will be made available in the streaming catalog. Depending on the popularity of this delivery method, the streaming catalog will expand to 500 titles in six months and about 1,000 titles in twelve months. In the future, platinum members with excellent payment records can view up to 10 streaming videos a month without paying a fee. Basic members can view up to 2 streaming videos a month without paying a fee.