SlideShare a Scribd company logo
Susan WhitfieldMSSQL Server 2008 PortfolioEmail: lilredlokita@gmail.com
IntroductionGood day… My name is Susan Whitfield and I set out on a journey to augment my IT skills. This led me to SetFocus, LLC. and their SQL Masters Program. The goal of this program is to provide trainees with the skills necessary to become SQL Server 2008 experts, and to utilize the knowledge learned, in a real world setting within a short amount of time. SetFocus is a certified Microsoft Gold partner and uses Microsoft certified courses to accomplish this goal. The course was a very intense 13 weeks long, which showed the database administration side as well as the development side of SQL Server 2008. Included in this presentation are examples from projects completed during the 13 weeks. We utilized; SSMS (SQL Server Management Studio), SSIS (SQL Server Integration Studio), SSRS (SQL Server Report Studio), Visio, and BIDS (Business Intelligence Development Studio), in order to develop T-SQL code, create: packages, reports, database diagrams, as well as administer: security, mirroring, clustering, replication,  snapshots, isolation levels, jobs, and other administration tasks.Enjoy the presentation and if you have any questions please feel free to contact me at the email included.	Susan Whitfield
Table of ContentsIntroduction		.	.	.	.	.	.	.	.	.	.	.	.	2Piggy Bank 1 Project:.	.	.	.	.	.	.	.	.	.	.	4Designing databaseTSQL Assignment:		.	.	.	.	.	.	.	.	.	.	.	8Designing database and utilizing T-SQL skillsPiggy Bank 2 Project:.	.	.	.	.	.	.	.	.	.	.	24Designing database, creating: views, triggers, and robust stored procedures, shredding XMLDBA Practical’s:	.	.	.	.	.	.	.	.	.	.	.	.	38Adventure Works Repair Project: 	.	.	.	.	.	.	.	.	.	44T-SQL practiceMini Adventure Works Project:	.	.	.	.	.	.	.	.	.	50Table creation, triggers, stored procedures, user defined function, and SSIS packagesBlockFlix Project (Final Project: showing portions I completed):		.	.	.74Stored procedures , XML Source Files, SSIS packagesEvaluation Application (Mini-Final Project: showing portions I completed):	.	93Instructor Results Report examples
Project SpecificationsER DiagramDiagram 0Piggy Bank Project
Project SpecificationsCreate a database for Piggy Unlimited. We were given a list of columns and were asked to create tables, establish relationships via primary key constraints and foreign key constraints and choose most appropriate data types. After database/table creation we were asked to backup the database and send that backup to the instructor. We were required to denormalize to 3rd NF, and to justify use of denormalization.
SQL Server 2008 Portfolio
SQL Server 2008 Portfolio
DB CreationDiagram 0QueriesT-SQL Project
Database CreationUSE [JungleBooks]GO/****** Object:  Table [dbo].[Orders]    Script Date: 10/07/2009 00:01:16 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE TABLE [dbo].[Orders](	[OrderID] [int] NOT NULL,	[CustomerID] [int] NOT NULL,	[OrderDate] [smalldatetime] NOT NULL, CONSTRAINT [PK_Orders] PRIMARY KEY CLUSTERED (	[OrderID] ASC)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]) ON [PRIMARY]GO/****** Object:  Table [dbo].[OrderItems]    Script Date: 10/07/2009 00:01:16 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOSET ANSI_PADDING ONGOCREATE TABLE [dbo].[OrderItems](	[OrderItemID] [int] NOT NULL,	[OrderID] [int] NOT NULL,	[ISBN] [char](20) NOT NULL,	[QuantityOrdered] [int] NOT NULL,	[QuantityDispatched] [int] NOT NULL,	[UnitPrice] [money] NOT NULL, CONSTRAINT [PK_OrderItems] PRIMARY KEY CLUSTERED (	[OrderItemID] ASC)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]) ON [PRIMARY]
GOSET ANSI_PADDING OFFGO/****** Object:  Table [dbo].[Customers]    Script Date: 10/07/2009 00:01:16 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOSET ANSI_PADDING ONGOCREATE TABLE [dbo].[Customers](	[CustomerID] [int] NOT NULL,	[Name] [varchar](80) NOT NULL,	[Address] [varchar](255) NOT NULL,	[CardType] [char](20) NOT NULL,	[CardNumber] [char](20) NOT NULL,	[ExpiryDate] [smalldatetime] NOT NULL, CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED (	[CustomerID] ASC)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]) ON [PRIMARY]GOSET ANSI_PADDING OFFGO/****** Object:  Table [dbo].[Books]    Script Date: 10/07/2009 00:01:16 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOSET ANSI_PADDING ONGOCREATE TABLE [dbo].[Books](	[ISBN] [char](20) NOT NULL,	[Publisher] [varchar](50) NOT NULL,	[Title] [varchar](128) NOT NULL,	[UnitPrice] [money] NOT NULL,	[Abstract] [varchar](255) NOT NULL,	[Pages] [smallint] NOT NULL,	[Published] [smalldatetime] NOT NULL,	[Stock] [int] NOT NULL, CONSTRAINT [PK_Books] PRIMARY KEY CLUSTERED (
	[ISBN] ASC)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]) ON [PRIMARY]GOSET ANSI_PADDING OFFGO/****** Object:  Table [dbo].[BookAuthors]    Script Date: 10/07/2009 00:01:16 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOSET ANSI_PADDING ONGOCREATE TABLE [dbo].[BookAuthors](	[BookAuthorID] [int] NOT NULL,	[ISBN] [char](20) NOT NULL,	[AuthorID] [int] NOT NULL, CONSTRAINT [PK_BookAuthors] PRIMARY KEY CLUSTERED (	[BookAuthorID] ASC)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]) ON [PRIMARY]GOSET ANSI_PADDING OFFGO/****** Object:  Table [dbo].[Authors]    Script Date: 10/07/2009 00:01:16 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOSET ANSI_PADDING ONGOCREATE TABLE [dbo].[Authors](	[AuthorID] [int] NOT NULL,	[Name] [varchar](120) NOT NULL, CONSTRAINT [PK_Authors] PRIMARY KEY CLUSTERED (	[AuthorID] ASC)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]) ON [PRIMARY]GOSET ANSI_PADDING OFFGO
SQL Server 2008 Portfolio
Problem 1The Cheap Books form displays available books below a certain price.  The user enters 15 in the txtUnitPrice form field.  Return ISBN, title and publisher in order by title.Statement1Write a query that displays ISBN, title, publisher having books that are priced less than $15, ordered by the title.T-SQL1SELECT ISBN, Title, PublisherFROM BooksWHEREUnitPrice< 15ORDERBY TitleProblem 2The Search For Authors form displays a list of author names which contains a string which is input by the user.  The user enters ‘pet’ in the txtName form field.  Display author names in alphabetical order.  Use the alias ‘Search Results’ for the author name data.Statement2Write a query that displays author names having the name ‘pet’, displayed in alphabetical order. Use heading: ‘Search Results’.T-SQL2SELECT Name AS'Search Results'FROM AuthorsWHERE Name like'%pet%'ORDERBY Name
Problem 3The Range of Customers form allows the user to view orders placed within a given range of customer IDs.  The user enters 6 in the txtIDStart form field and 15 in txtIDEnd form field.  Display all columns of data in order by Customer ID.   Alias the columns in the result set as:  ‘Order #’, ‘Cust ID’, ‘Order Date’.Statement3Write a query to display order number, customer id, and order date ordered by customer id having customer ids in the range between 6 and 15. Use headings: ‘Order#’, ‘Cust ID’, and ‘Order Date’.T-SQL3SELECTOrderID'Order#',CustomerID'Cust ID',OrderDate'Order Date'FROM OrdersWHERECustomerIDbetween 6 and 15ORDERBYCustomerIDProblem 4The Large Orders page is a report displaying the largest number of items sold per order.  Display the Order ID, Customer ID and Name along with the total number of items they ordered.  Display the record with the largest quantity first.  Alias as:  “Order ID’, ‘Cust ID’, ‘Customer’ and ‘# of items’.Statement4Write a query that displays order id, customer id, name and quantity of ordered items, showing the largest quantity first. Use Headings: ‘Order ID’, ‘Cust ID’, ‘Customer’ and ‘# of items’.T-SQL4SELECTO.OrderID'Order ID',O.CustomerID'Cust ID',	Name 'Customer',SUM(QuantityOrdered)'# of items'FROM Customers C JOIN Orders O ONC.CustomerID=O.CustomerIDJOINOrderItems OI ONO.OrderID=OI.OrderIDGROUPBYO.OrderID,O.CustomerID, NameORDERBYSUM(QuantityOrdered)DESC
Problem 5The Available Books page is a report listing the publishers and the books they offer.  Output a list of publishers, the books they publish and each book’s ISBN.  Ensure the output lists the Publishers in alphabetical order and the titles in alphabetical order.Statement5Write a query to display publishers, books they publish and the ISBN for each book, displaying in alphabetical orderT-SQL5SELECT Publisher, Title, ISBNFROM BooksORDERBY Publisher, TitleProblem 6The Expired Cards page is a report on credit cards that have expired and credit cards that will expire soon.  Output the customer ID, customer name and expiry date of the card for records with an expiry date prior to 30 days after the current date (today).  Display the records by expiry date in descending order.  Alias as:  ‘ID’, ‘Name’, ‘Expires’.Statement6Write a query to display customer ID, customer name, expiry date for records that are expiring within the next thirty days in descending order. Use headings: ‘ID’, ‘Name’, ‘Expires’T-SQL6SELECTCustomerID'ID', Name 'Name',ExpiryDate'Expires'FROM CustomersWHEREExpiryDate < Getdate()+30ORDERBYExpiryDateDESC
Problem 7The Author and Books page is a report which lists the author name, book title and ISBN.  The list is to be output in order by author name and title.Statement7Write a query to display the author name, book title and ISBN, displayed in order by author name and title.T-SQL7SELECT Name, Title, BA.ISBNFROM Authors A JOINBookAuthors BA ONA.AuthorID=BA.AuthorIDJOIN Books B ON	B.ISBN = BA.ISBNORDERBY Name, TitleProblem 8The Hot Items page is a report of popular items.  The user will input 5 in the txtMinimumTotal form field.  Display ISBN, Title and the total number of items ordered.  The total is to represent the sum of all quantity ordered amounts per ISBN.  Display all records with a total greater than or equal to 5.  The hottest items should be listed first.  Alias as:  ‘ISBN’, ’Title’ , ’Total’.Statement8Write a query that displays ISBN, Title, total number of items ordered where the total is greater or equal to 5, with the output ordered by total descending. Use headings ‘ISBN’, ‘Title’ and ‘Total’. T-SQL8SELECT OI.ISBN 'ISBN', Title 'Title',SUM(QuantityOrdered)'Total'FROMOrderItems OI JOIN Books B ON	OI.ISBN = B.ISBNGROUPBY OI.ISBN, TitleHAVINGSUM(QuantityOrdered)>= 5ORDERBYSUM(QuantityOrdered)DESC
Problem 9The Search For Customers by Credit Card page also allows the user to search for Customers by the last four digits of their credit card number.  The user inputs ‘’7889” in the txtLastFourDigits form field.  Return all information from the Customer table. Alias as:  ‘ID’, ‘Name’, ‘CurrentAddress’, ’CardType’, ‘CardNumber’, ‘Expires’. In case you have different customers using the same credit card, order by Customer ID in ascending order.Statement9Write a query to display customer id, name, address, cardtype, cardnumber, and expirydate using the last four digits in the credit card number. Use headings: ‘ID’, ‘Name’, ‘CurrentAddress’, ‘CardType’, ‘CardNumber’, and ‘Expires’.T-SQL9SELECTCustomerID'ID', Name 'Name',Address'CurrentAddress',CardType'CardType',CardNumber'CardNumber',ExpiryDate'Expires'FROM CustomersWHERECardNumberlike'%7889'ORDERBYCustomerIDProblem 10Write and execute a query on the Member and Adult tables in the Library database that returns the firstname, middleinitial, lastname, street, city, state and zip.  Concatenate the firstname, middleinitial and lastname columns into one string and alias as Name.  Make sure that the spacing is appropriate when there is no middle initial due to a NULL or empty string value.  Display records in order by lastname and firstname.Statement10Write a query to display firstname, middleinitial, lastname, street, city, state and zip. Should be displayed in order by the lastname and firstname.T-SQL10SELECT (firstname+' '+isnull(middleinitial+' ','')+lastname) AS'Name', 	street, city,state, zip FROM adult a JOIN member m ONa.member_no=m.member_no ORDERBYlastname,firstname
Problem 11Write and execute a query on the Title, Item and Copy tables that returns the ISBN, copy_no, on_loan, title, translation, and cover for rows in the copy table with an ISBN of 500 or 1000.  Only available books should be displayed and hardback copies should be listed first.Statement11Write a query that displays the ISBN, copy_no, on_loan, title, translation, and cover where the ISBN is 500 or 1000 and the books are available and order it by cover.T-SQL11SELECTc.isbn,copy_no,on_loan, title, translation, cover FROM title t JOIN item iONt.title_no=i.title_noJOIN copy c ONc.isbn=i.isbnWHERE(c.ISBN= 500 ORc.ISBN= 1000) AND on_loan='N'ORDERBY coverProblem 12Write and execute a query to retrieve the member’s full name and member_no from the Member table and the ISBN and log_date values from the Reservation table for member numbers 250, 341, and 1675.  Order the results by member_no and log_date.  You should show information for these members, even if they have no books on reserve.Statement12Write a query to display firstname, middleinitial, lastname, member_no, ISBN, log_date for members with 250, 341 and 1675 member numbers. Order results by member_no and log_date. Members who do not have books on reserve should be included in the output.T-SQL12SELECTfirstname,middleinitial,lastname,m.member_no,isbn,log_dateFROM member m LEFTOUTERJOIN reservation r ONm.member_no=r.member_noWHEREm.member_noin(250, 341, 1675)ORDERBYm.member_no,log_date
Problem 13Using joins and a UNION clause, write a query to retrieve a single list of members both adult and juvenile, who have reserved ISBN number 288.  The list must include the ISBN, title, member_no and name (i.e.: Smith, John) of each member who has the reservation.  Additionally, the list should indicate whether the member is an adult or a juvenile.  Output the records by name.Statement13Write a query that displays ISBN, title, member_no, name of each member (adult/juvenile) who has the book with ISBN number 288 reserved; indicate whether member is adult/juvenile and output records by name.T-SQL13 (Query #1 in problem #14)SELECTc.isbn, title,a.member_no,lastname+', '+firstnameas'name','Adult'as'Adult / Juvenile'FROM adult a JOIN reservation r ONa.member_no=r.member_noJOIN copy c ONr.isbn=c.isbnJOIN title t ONc.title_no=t.title_noJOIN member m ONm.member_no=a.member_noWHEREc.ISBN= 288UNIONSELECTc.isbn, title,j.member_no,lastname+', '+firstnameas'name','Juvenile'as'Adult / Juvenile'FROM juvenile j JOIN reservation r ONj.member_no=r.member_noJOIN copy c ONr.isbn=c.isbnJOIN title t ONc.title_no=t.title_noJOIN member m ONm.member_no=j.member_noWHEREc.ISBN= 288ORDERBY'name'
Problem 14Write the above statement again using a CASE statement.  You cannot JOIN to the Adult or Juvenile tables.  Compare the two versions and determine which one is more efficient.  Cut and paste the proof of your research.  (No need to copy the output of records)Statement14Write the query from problem 13 using a CASE statement. Compare each version and determine which one is more efficient.T-SQL14 (Query #2)SELECTi.isbn, title,m.member_no,lastname+', '+firstname'name','Adult/Juvenile'=CASEWHENEXISTS(SELECTmember_noFROM juvenile jWHEREj.member_no=m.member_no)THEN'Juvenile'ELSE'Adult'ENDFROM member m JOIN reservation r ONm.member_no=r.member_noJOIN item iONi.isbn=r.isbnJOIN title t ONt.title_no=i.title_noWHEREi.isbn= 288ORDERBY'name'Output14Viewing the Execution plan in SSMS, we find this:	Query 1: Query cost (relative to the batch: 65%	Query 2: Query cost (relative to the batch: 35%The above indicates that Query 2, using the CASE statement, was more efficient.
Problem 15Write and execute a query that returns the member_no, full name, out_date, due_date, and title columns from the Loan, Member, and Title tables.  Convert the datetime values from the out_date and due_date columns to char(12), format 101.  Restrict the results to books which were due prior to the current date.  Load the records into a temporary table called #overdue.  Leave the query window open after you create the temporary table.Statement15Write a query to display member_no, full name, out_date, due_date, and title. Datetime values should be converted to specified format and only books that were due before today’s date should be returned. Load all returned records into a temp table.T-SQL15CREATETABLE #overdue(member_nosmallintNOTNULL,fullnamevarchar(35)NOTNULL,out_datechar(12)NOTNULL,due_datechar(12)NOTNULL,	title varchar(63)NOTNULL) INSERTINTO #overdue (member_no,fullname,out_date,due_date, title)SELECTm.member_no,firstname+' '+ISNULL(SUBSTRING(middleinitial,1,1),'')+' '+lastname,CONVERT(char(12),out_date, 101)ASout_date,CONVERT(char(12),due_date, 101)ASdue_date, titleFROM loan l JOIN title t ONl.title_no=t.title_noJOIN member m ONm.member_no=l.member_noWHEREdue_date<GETDATE()
Problem 16Write and execute a query that returns the member number, member name and number of past due loans of each member from the #overdue table in a column called ‘# Overdue’.  Use the same query window that you used to create the temporary table.  Display by the number outstanding and the member name.Statement16Write a query to display the member number, member name, number of past due loans in a specific column. Oder by number outstanding and the member name. Use heading: ‘# Overdue’.T-SQL16SELECTmember_no,fullname,COUNT(due_date)AS'# Overdue'FROM #overdueGROUPBYmember_no,fullnameORDERBY'# Overdue'DESC,fullnameProblem 17Write and execute a query that returns member_no, firstname, lastname and sum of fine_paid for members who have paid the highest fines to date.  Members should only appear once in the list.  Display the highest fine first.  If more than one member has paid the same amount display the records in order by member_no.Statement17Write a query to display member_no, firstname, lastname, and sum of fine-paid for members who have paid the highest fines to date. Order by fine_paid, if more than one member has paid the same amount display in order by member_no.T-SQL17SELECTlh.member_no,firstname,lastname,SUM(fine_paid)AS'Paid Fines'FROMloanhistlhJOIN member m ONlh.member_no=m.member_noWHEREfine_paidISNOTNULLGROUPBYlh.member_no,firstname,lastnameORDERBY'Paid Fines'DESC,lh.member_no
Problem 18Write and execute a query on the Reservation table that returns the ISBN, title and Total.  The Total column is a calculated column which represents the number of members wishing to reserve a particular book.Statement18Write a query that displays ISBN, title, and total (calculated column).T-SQL18SELECTr.isbn, title,Count(member_no)AS'Total'FROM reservation r JOIN item iONr.isbn=i.isbnJOIN title t ONt.title_no=i.title_noGROUPBYr.isbn, title
Diagram 0ViewsTriggersStored procedures (code snippets of a few sp’s)XML shred snippetPiggy Bank 2 Project
SQL Server 2008 Portfolio
Views/****** Object:  View [dbo].[v_CurrentMonthStatement]    Script Date: 10/17/2009 00:43:55 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE VIEW [dbo].[v_CurrentMonthStatement] WITH SCHEMABINDINGAS	SELECT CustomerFirstName, CustomerMiddleInitial, CustomerLastName,			Street, City, State, ZipCode, TransactionID, AccountID, TransactionTypeID, T.CustomerID, TransactionDate, TransactionAmount, NewBalance	FROM dbo.Transactions T JOIN dbo.Customer C ONT.CustomerID = C.CustomerIDGO/****** Object:  View [dbo].[v_GetBalance]    Script Date: 10/17/2009 00:43:55 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE VIEW [dbo].[v_GetBalance] WITH SCHEMABINDINGAS			SELECT TransactionID, AccountID, T.TransactionTypeID, CustomerID, TransactionDate, TransactionAmount, TransactionTypeName,NewBalance			FROM dbo.Transactions T JOIN dbo.TransactionType TT ONT.TransactionTypeID = TT.TransactionTypeIDGO
/****** Object:  View [dbo].[v_GetHistoricalStatement]    Script Date: 10/17/2009 00:43:55 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE VIEW [dbo].[v_GetHistoricalStatement] WITH SCHEMABINDINGAS	SELECT CustomerFirstName, CustomerMiddleInitial, CustomerLastName,		Street, City, State, ZipCode, TransactionID, AccountID,TransactionTypeID, T.CustomerID, TransactionDate,TransactionAmount, NewBalance	FROM dbo.Transactions T JOIN dbo.Customer C ONT.CustomerID = C.CustomerIDGO/****** Object:  View [dbo].[v_GetTransactions]    Script Date: 10/17/2009 00:43:55 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE VIEW [dbo].[v_GetTransactions] WITH SCHEMABINDINGAS	SELECT TransactionID, AccountID, TransactionTypeID,CustomerID, TransactionDate, TransactionAmount,NewBalance	FROM dbo.TransactionsGO
/****** Object:  View [dbo].[v_ListCustomerAccounts]    Script Date: 10/17/2009 00:43:55 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE VIEW [dbo].[v_ListCustomerAccounts] WITH SCHEMABINDINGAS	SELECT CustomerFirstName, CustomerMiddleInitial, CustomerLastName,		Street, City, State, ZipCode, CA.AccountID, CA.CustomerID	FROM dbo.CustomerAccount CA JOIN dbo.Customer C ONC.CustomerID = CA.CustomerIDGO
TriggersUSE [PiggyBankWk4]GO/****** Object:  DdlTrigger [NoUnwantedChanges]    Script Date: 10/17/2009 00:50:48 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE TRIGGER [NoUnwantedChanges] ON DATABASE FOR DROP_TABLE, ALTER_TABLE AS    PRINT 'You must disable Trigger "NoUnwantedChanges" to drop or alter tables!' ROLLBACK;GO/****** Object:  Trigger [dbo].[NoAccountDeletions]    Script Date: 10/17/2009 00:51:09 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE TRIGGER [dbo].[NoAccountDeletions]ON [PiggyBankWk4].[dbo].[Account]FOR DELETE AS    PRINT 'You cannot delete accounts from the Account table, you may however disable the account.'    ROLLBACKGO
SP’sAdd Account Stored Proc Code Snippet
Deposit Transaction Stored Proc Code Snippet
Deposit Transfer Stored Proc Code Snippet
Insert Customer Stored Proc Code Snippet
Close Account Stored Proc Code Snippet
Reopen Account Stored Proc Code Snippet
Withdrawal Transfer Stored Proc Code Snippet
XML shred
Backup/Restore Disaster Recovery Mini-SimulationSnapshot Creation and UsageWorking With SchemasResource Governor Configuration & UsageOwnership ChainingDBA Practical’s
Backup & Restore: Disaster Recovery Mini-Simulation--primary file group backupBACKUP DATABASE [AdventureWorks2008] FILEGROUP = N'PRIMARY' TO  [Adventureworks2008Backups] WITH NOFORMAT, INIT,  	NAME = N'AdventureWorks2008-Full Primary Filegroup Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10GO--secondary file group backupBACKUP DATABASE [AdventureWorks2008] FILEGROUP = N'EmployeeWorkHistoryFG' TO  [Adventureworks2008Backups] WITH NOFORMAT, NOINIT,  	NAME = N'AdventureWorks2008-Full Secondary Filegroup Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10GO--Update the ClockOutTime for the only record in the EmployeeWorkHistoryTable.  The current value is NULLUSE AdventureWorks2008GOUPDATE HumanResources.EmployeeWorkHistorySET ClockOutTime= GETDATE() WHERE BusinessEntityID= 1--log file backupBACKUP LOG [AdventureWorks2008] TO  [Adventureworks2008Backups] WITH NOFORMAT, NOINIT,  	NAME = N'AdventureWorks2008-Transaction Log  Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10GO--Simulate accidental deletion of a table by executing the following statements:DROP TABLE HumanResources.EmployeeWorkHistory--secondary filegroup with norecovery, the transaction log backup with RECOVERYRESTORE HEADERONLY FROM Adventureworks2008Backups--AdventureWorks2008-Full Primary FilegroupBackup,AdventureWorks2008-Full Secondary FilegroupBackup, AdventureWorks2008-Transaction Log  BackupRESTORE FILELISTONLY FROM Adventureworks2008Backups--AdventureWorks2008_Data , EmpWorkHist, AdventureWorks2008_Log, -FileStreamDocumentsUse masterGORESTORE DATABASE AdventureWorks2008 FROM Adventureworks2008Backups WITH FILE = 1, NORECOVERY--Processed 8 pages for database 'AdventureWorks2008', file 'EmpWorkHist' on file 2.--RESTORE DATABASE ... FILE=<name> successfully processed 8 pages in 0.134 seconds (0.466 MB/sec).RESTORE LOG AdventureWorks2008 FROM Adventureworks2008Backups WITH RECOVERY--Processed 0 pages for database 'AdventureWorks2008', file 'EmpWorkHist' on file 3.--The roll forward start point is now at log sequence number (LSN) 47000000029200001. Additional roll forward past LSN 47000000031500001 is required to complete the restore sequence.--RESTORE LOG successfully processed 0 pages in 0.060 seconds (0.000 MB/sec).
Snapshot Creation and Usage/* Author:	Susan WhitfieldDate:		Friday, November 6, 2009Purpose:	To show database snapshot creation and usage.*/--creation of db snapshotUSE masterGOCREATE DATABASE AdventureWorks_snapshot1420 ON(NAME = AdventureWorks_Data,FILENAME= 'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\AdventureWorks_1420.ss')AS SNAPSHOT OF AdventureWorks--insertion of recordUSE AdventureWorksGOINSERT INTO Production.ProductCategory(Name, ModifiedDate) VALUES ('Test Category', GETDATE())--making sure record existsselect * FROM Production.ProductCategoryWHERE Name = 'Test Category'--ProductCategoryID	Name	rowguidModifiedDate--7		Test Category	E597E244-E10E-4222-9F4D-9B14291AC41C	2009-11-06 15:19:07.603--revert back to snapshotUSE masterGORESTORE DATABASE AdventureWorks FROM DATABASE_SNAPSHOT = 'AdventureWorks_snapshot1420'--testing to see if record is still thereUSE AdventureWorksGOselect * FROM Production.ProductCategoryWHERE Name = 'Test Category'--nothing is there with that name
Working With Schemas/* Author:	Susan WhitfieldDate:		Friday, November 6, 2009Purpose:	Schema work: Working With Schemas.*/--creating loginUSE masterGOCREATE LOGIN Michael WITH PASSWORD = 'P@$$w0rd'USE Adventureworks2008GOCREATE USER Michael WITH DEFAULT_SCHEMA = PersonGOCREATE TABLE dbo.Person(FirstNamevarchar(25), LastNamevarchar(25), EmailAddressvarchar(50))GOINSERT INTO dbo.Person(FirstName, LastName, EmailAddress) VALUES ('Joe', 'Mugg', 'jm@mugg.com')GOGRANT SELECT ON dbo.PersonTO Michael--run from a window logged in under MichaelUSE Adventureworks2008GOSELECT * FROM PersonGO--didnt work because of ambiguity. Need to specify schema.table name
Resource Governor Configuration & Usage-- Configure Resource Governor.BEGIN TRANUSE MasterGO-- Create a resource pool that sets the MAX_CPU_PERCENT to 40%. CREATE RESOURCE POOL pMAX_CPU_PERCENT_40 WITH(max_cpu_percent=40)GO--creation of the workload group using resource pool created above.CREATE WORKLOAD GROUP gMAX_CPU_PERCENT_40 USING pMAX_CPU_PERCENT_40GO-- Create a classification function.-- Note that any request that does not get classified goes into -- the 'Default' group.CREATE FUNCTION rgclassifier_MAX_CPU() RETURNS SYSNAME WITH SCHEMABINDINGASBEGIN    DECLARE @workload_group_name AS SYSNAME      IF (SUSER_NAME() = 'Joe')SET @workload_group_name= 'gMAX_CPU_PERCENT_40'RETURN @workload_group_nameEND;GO-- Register the classifier function with Resource Governor.ALTER RESOURCE GOVERNOR WITH (CLASSIFIER_FUNCTION= dbo.rgclassifier_MAX_CPU);COMMIT TRAN;GO-- Start Resource GovernorALTER RESOURCE GOVERNOR RECONFIGURE;GO
Ownership ChainingUSE master GOCREATE LOGIN Joe WITH PASSWORD = 'P@$$w0rd'CREATE LOGIN Tom WITH PASSWORD = 'P@$$w0rd'GOUSE Adventureworks2008 GOCREATE USER JoeCREATE USER TomGOCREATE SCHEMA Marketing AUTHORIZATION Joe GOCREATE TABLE Marketing.PrintCompanies(Name varchar(25), PricePerPagemoney) GOINSERT INTO Marketing.PrintCompanies(Name, PricePerPage) VALUES ('Adventureworks', .25)GRANT CREATE PROCEDURE TO Joe GOGRANT SELECT ON Person.PersonTO Joe GO--below was used in a new query logged in under Joe's loginCREATE PROCEDURE Marketing.uspPrintCompaniesASSET NOCOUNT ONSELECT Name FROM Marketing.PrintCompaniesGOCREATE PROCEDURE Marketing.uspPersonASSET NOCOUNT ONSELECT FirstName, LastNameFROM Person.PersonGOGRANT EXECUTE ON Marketing.uspPrintCompaniesTO TomGRANT EXECUTE ON Marketing.uspPersonTO TomGO--below was used in a new query logged in under Tom's loginUSE AdventureWorks2008 GOExecute Marketing.uspPrintCompanies--worksEXECUTE Marketing.uspPersonMsg 229, Level 14, State 5, Procedure uspPerson, Line 4The SELECT permission was denied on the object 'Person', database 'AdventureWorks2008', schema 'Person'.--Tom does not have access to the Person.Person table. Select permissions were granted to Joe. Trying to do the select on the Person.Persontable will not work because it is outside of his--"ownership chain", meaning that even though Joe granted execute permissions to Tom, that only applies to the execution of the procedure. The owner or a dba or someone with sufficient permissions would need to grant select to Tom as well.
Adventure Works RepairDiagram 0High Effort Jobs ReportInvoiced Job SummaryCustomer Billing Summary
SQL Server 2008 Portfolio
High Effort Jobs Report--requirements/*The final report ("High Effort Jobs") is intended to show jobs where there is a disproportionately high  effort by production staff, measured by total number  of items on the job.  The data should contain the  following fields:	Job name	Customer name	Total number of items	Total gross margin	Total revenueThe data should be sorted by "Total number of items", highest to lowest, should only show jobs with 5 or more items, and should only show customers in the 'Transactional' or 'BPO' classifications ('Enterprise' classified customers should not be shown).*/SELECT JobName, CustomerName, count(JobItemID) as 'Total number of items',(SUM(Cost) * MarginPercentage) as 'Total gross margin',(SUM(Cost)/(1-MarginPercentage)) as 'Total revenue' FROM Job J JOIN Customer C ON J.CustomerID = C.CustomerID JOIN JobItem JION JI.JobID = J.JobID JOIN Classification CL ON CL.ClassificationID = C.ClassificationID JOIN Item ION I.ItemID = JI.ItemIDWHERE ClassificationNamein('Transactional', 'BPO')GROUP BY JobName, CustomerName, MarginPercentageHAVING COUNT(JI.ItemID) >= 2 --I used 2 to test it out to ensure that it workedORDER BY 'Total Number of Items' DESC
Invoiced Job Summary--requirements/*The first report ("Invoiced Job Summary") represents jobs for which we are attempting to collect revenue.  The data should contain the following fields:	Job name	Customer name	Total job cost	Total gross margin	Total job revenue	Date invoiced	Days since invoice dateThe data should be sorted by "Days since invoice date", highest to lowest, and only show jobs in "Collection" status.*/SELECT JobName, CustomerName, SUM(Cost) as 'Total job cost', (SUM(Cost) * MarginPercentage) as 'Total gross margin', (SUM(Cost)/(1-MarginPercentage)) as 'Total revenue', DATE,(Day(DATE)-DAY(GetDate())) as 'Days since invoice date'FROM Job J JOIN Customer CON J.CustomerID = C.CustomerID JOIN JobItem JION JI.JobID = J.JobID JOIN Item ION JI.ItemID = I.ItemID JOIN Status S	ON S.StatusID = J.StatusID JOIN JobStageDate JSD ON JSD.JobID = JI.JobIDWHERE StatusName= 'Collection' AND StageDateTypeID = 4GROUP BY JobName, CustomerName, MarginPercentage, DateORDER BY 'Days since invoice date' DESC
Customer Billing Summary Requirements--requirements/*The second report ("Customer Billing Summary") represents an overview of the billing activity for each customer.  The data should contain the following fields:	Customer name	Total number of jobs for this customer which are not in "Closed" status	Total revenue for all jobs for this customer which are not in "Closed" status	Total number of jobs for this customer which are in "Collection" status	Total revenue for all for this customer which are jobs in "Collection" status	Total number of jobs for this customer which are in "Closed" status	Total revenue for all jobs for this customer which are in "Closed" status	Average revenue for all jobs for this customer which are in "Closed" status	Total gross margin for all jobs for this customer which are in "Closed" status	Average gross margin for all jobs for this customer which are in "Closed" statusThe data should be sorted by "Total revenue for all jobs for this customer which are in 'Closed' status", highest to lowest.*/
Customer Billing SummarySELECT CustomerName, (SELECT Count(JobID) FROM Job WHERE StatusID<> 6) as 'Total # jobs not closed', (SELECT (SUM(Cost)/(1-MarginPercentage)) FROM Item I JOIN JobItem JI ON I.ItemID = JI.ItemID														JOIN Job J ON J.JobID = JI.JobIDWHERE StatusID<> 6 GROUP BY MarginPercentage) as 'Total revenue for jobs not closed',(SELECT Count(JobID) FROM Job WHERE StatusID= 5) as 'Total # jobs in collection',(SELECT (SUM(Cost)/(1-MarginPercentage)) FROM Item I JOIN JobItem JI ON I.ItemID = JI.ItemID														JOIN Job J ON J.JobID = JI.JobIDWHERE StatusID=  5 GROUP BY MarginPercentage) as 'Total revenue for jobs in collection',(SELECT count(JobID) FROM Job WHERE StatusID= 6) as 'Total # jobs closed',(SELECT (SUM(Cost)/(1-MarginPercentage)) FROM Item I JOIN JobItem JI ON I.ItemID = JI.ItemID														JOIN Job J ON J.JobID = JI.JobIDWHERE StatusID= 6 GROUP BY MarginPercentage) as 'Total revenue for closed jobs',(SELECT Avg((Cost)/(1-MarginPercentage)) FROM Item I JOIN JobItem JI ON I.ItemID = JI.ItemID														JOIN Job J ON J.JobID = JI.JobIDWHERE StatusID= 6 GROUP BY MarginPercentage) as 'Average revenue for closed jobs',(SELECT (SUM(Cost) * MarginPercentage) FROM Item I JOIN JobItem JI ON I.ItemID = JI.ItemID														JOIN Job J ON J.JobID = JI.JobIDWHERE StatusID= 6 GROUP BY MarginPercentage) as 'Total gross margin for closed jobs',(SELECT Avg((Cost) * MarginPercentage) FROM Item I JOIN JobItem JI ON I.ItemID = JI.ItemID														JOIN Job J ON J.JobID = JI.JobIDWHERE StatusID= 6 GROUP BY MarginPercentage) as 'Average gross margin for closed jobs'FROM Customer WHERE CustomerName= 'Outback Rigs' --choose a customer name from listORDER BY 'Total revenue for closed jobs' DESC
Source FilesTable CreationTriggersStored ProcedureUser Defined FunctionSSIS PackagesMini Adventure Works
3 Master FilesProductMaster.CSVShipMethodMaster.CSVVendorMaster.CSVFour Purchase Order Transaction Files  PODATA_2001.CSVPODATA_2002.CSVPODATA_2003.CSVPODATA_2004.CSV1 Master File Update	UpdatedProducts.CSVSource Files
Table CreationProduct TableUSE [MiniAdventureWorksDB]GO/****** Object:  Table [dbo].[Product]    Script Date: 11/27/2009 16:57:37 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE TABLE [dbo].[Product](	[ProductID] [int] IDENTITY(1,1) NOT NULL,	[ProductNumber] [nvarchar](50) NOT NULL,	[ProductName] [nvarchar](100) NOT NULL,	[ListPrice] [decimal](14, 4) NOT NULL,	[DateInserted] [datetime] NOT NULL,	[DateModified] [datetime] NOT NULL,CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED (	[ProductID] ASC)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY],CONSTRAINT [ProductNumber_unique] UNIQUE NONCLUSTERED (	[ProductNumber] ASC)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]) ON [PRIMARY]GOALTER TABLE [dbo].[Product] ADD  CONSTRAINT [DateInserted_def]  DEFAULT (getdate()) FOR [DateInserted]GOALTER TABLE [dbo].[Product] ADD  CONSTRAINT [DateModified_def]  DEFAULT (getdate()) FOR [DateModified]GO
Vendor TableUSE [MiniAdventureWorksDB]GO/****** Object:  Table [dbo].[Vendor]    Script Date: 11/27/2009 16:58:16 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE TABLE [dbo].[Vendor](	[VendorID] [int] IDENTITY(1,1) NOT NULL,	[Name] [nvarchar](100) NOT NULL,	[AccountNumber] [nvarchar](50) NOT NULL,	[CreditRating] [tinyint] NOT NULL,	[DateInserted] [datetime] NOT NULL,	[DateModified] [datetime] NOT NULL,CONSTRAINT [PK_Vendor] PRIMARY KEY CLUSTERED (	[VendorID] ASC)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY],CONSTRAINT [AccountNumber_unique] UNIQUE NONCLUSTERED (	[AccountNumber] ASC)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]) ON [PRIMARY]GOALTER TABLE [dbo].[Vendor] ADD  CONSTRAINT [VendorDateInserted_def]  DEFAULT (getdate()) FOR [DateInserted]GOALTER TABLE [dbo].[Vendor] ADD  CONSTRAINT [VendorDateModified_def]  DEFAULT (getdate()) FOR [DateModified]GO
ShipMethod TableUSE [MiniAdventureWorksDB]GO/****** Object:  Table [dbo].[ShipMethod]    Script Date: 11/27/2009 16:59:25 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE TABLE [dbo].[ShipMethod](	[ShipMethodID] [int] IDENTITY(1,1) NOT NULL,	[Name] [nvarchar](50) NOT NULL,	[DateInserted] [datetime] NOT NULL,	[DateModified] [datetime] NOT NULL,CONSTRAINT [PK_ShipMethod] PRIMARY KEY CLUSTERED (	[ShipMethodID] ASC)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY],CONSTRAINT [Name_unique] UNIQUE NONCLUSTERED (	[Name] ASC)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]) ON [PRIMARY]GOALTER TABLE [dbo].[ShipMethod] ADD  CONSTRAINT [ShipMethodDateInserted_def]  DEFAULT (getdate()) FOR [DateInserted]GOALTER TABLE [dbo].[ShipMethod] ADD  CONSTRAINT [ShipMethodDateModified_def]  DEFAULT (getdate()) FOR [DateModified]GO
PurchaseOrderHeader TableUSE [MiniAdventureWorksDB]GO/****** Object:  Table [dbo].[PurchaseOrderHeader]    Script Date: 11/27/2009 17:00:46 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE TABLE [dbo].[PurchaseOrderHeader](	[PurchaseOrderID] [int] IDENTITY(1,1) NOT NULL,	[POHeaderNumber] [nvarchar](20) NOT NULL,	[VendorID] [int] NOT NULL,	[ShipMethodID] [int] NOT NULL,	[OrderDate] [date] NOT NULL,	[Freight] [decimal](14, 4) NOT NULL,	[TotalDue] [decimal](14, 4) NOT NULL,	[DateInserted] [datetime] NOT NULL,	[DateModified] [datetime] NOT NULL,CONSTRAINT [PK_PurchaseOrderHeader] PRIMARY KEY CLUSTERED (	[PurchaseOrderID] ASC)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY],CONSTRAINT [PurchaseOrderHeader_unique] UNIQUE NONCLUSTERED (	[POHeaderNumber] ASC)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]) ON [PRIMARY]GOALTER TABLE [dbo].[PurchaseOrderHeader]  WITH CHECK ADD  CONSTRAINT [FK_PurchaseOrderHeader_Vendor] FOREIGN KEY([VendorID])REFERENCES [dbo].[Vendor]([VendorID])GOALTER TABLE [dbo].[PurchaseOrderHeader] CHECK CONSTRAINT [FK_PurchaseOrderHeader_Vendor]GOALTER TABLE [dbo].[PurchaseOrderHeader] ADD  CONSTRAINT [POHDateInserted_def]  DEFAULT (getdate()) FOR [DateInserted]GOALTER TABLE [dbo].[PurchaseOrderHeader] ADD  CONSTRAINT [POHDateModified_def]  DEFAULT (getdate()) FOR [DateModified]GO
PurchaseOrderDetail TableUSE [MiniAdventureWorksDB]GO/****** Object:  Table [dbo].[PurchaseOrderDetail]    Script Date: 11/27/2009 17:01:13 ******/SET ANSI_NULLS ON GOSET QUOTED_IDENTIFIER ON GOSET ANSI_PADDING ON GOCREATE TABLE [dbo].[PurchaseOrderDetail](	[PurchaseOrderID] [int] NOT NULL,	[PurchaseOrderDetailID] [int] IDENTITY(1,1) NOT NULL,	[ProductID] [int] NOT NULL,	[OrderQty] [int] NOT NULL,	[UnitPrice] [decimal](14, 4) NOT NULL,	[TotalDue]  AS ([UnitPrice]*[OrderQty]) PERSISTED,	[DateInserted] [datetime] NOT NULL,	[DateModified] [datetime] NOT NULL,CONSTRAINT [PK_PurchaseOrderDetail_1] PRIMARY KEY CLUSTERED (	[PurchaseOrderID] ASC,	[ProductID] ASC)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]) ON [PRIMARY]GOSET ANSI_PADDING OFF GOALTER TABLE [dbo].[PurchaseOrderDetail]  WITH CHECK ADD  CONSTRAINT [FK_PurchaseOrderDetail_Product] FOREIGN KEY([ProductID])REFERENCES [dbo].[Product]([ProductID]) GOALTER TABLE [dbo].[PurchaseOrderDetail] CHECK CONSTRAINT [FK_PurchaseOrderDetail_Product] GOALTER TABLE [dbo].[PurchaseOrderDetail]  WITH CHECK ADD  CONSTRAINT [FK_PurchaseOrderDetail_PurchaseOrderHeader] FOREIGN KEY([PurchaseOrderID]) REFERENCES [dbo].[PurchaseOrderHeader]([PurchaseOrderID]) GOALTER TABLE [dbo].[PurchaseOrderDetail] CHECK CONSTRAINT [FK_PurchaseOrderDetail_PurchaseOrderHeader] GOALTER TABLE [dbo].[PurchaseOrderDetail] ADD  CONSTRAINT [PODDateInserted_def]  DEFAULT (getdate()) FOR [DateInserted] GOALTER TABLE [dbo].[PurchaseOrderDetail] ADD  CONSTRAINT [PODDateModified_def]  DEFAULT (getdate()) FOR [DateModified] GO
TriggersTrigger CreationUSE MiniAdventureWorksDBGOCREATE TRIGGER UpdateProductON dbo.ProductAFTER UPDATE AS	BEGIN		SET NOCOUNT ON;UPDATE dbo.ProductSET DateModified= GetDate()FROM dbo.Product P JOIN INSERTED ION P.ProductID = I.ProductID JOIN DELETED DON P.ProductID = D.ProductIDWHERE I.ProductName <> D.ProductName ORI.ListPrice <> D.ListPriceENDGOUSE MiniAdventureWorksDBGOCREATE TRIGGER UpdatePurchaseOrderDetailON dbo.PurchaseOrderDetailAFTER UPDATE AS	BEGIN		SET NOCOUNT ON;UPDATE dbo.PurchaseOrderDetailSET DateModified= GetDate()FROM dbo.PurchaseOrderDetail POD JOIN INSERTED ION POD.PurchaseOrderDetailID = I.PurchaseOrderDetailID JOIN DELETED DON POD.PurchaseOrderDetailID = D.PurchaseOrderDetailIDWHERE I.OrderQty <> D.OrderQty ORI.UnitPrice <> D.UnitPriceENDGO
Trigger CreationUSE MiniAdventureWorksDBGOCREATE TRIGGER UpdatePurchaseOrderHeaderON dbo.PurchaseOrderHeaderAFTER UPDATE AS	BEGIN		SET NOCOUNT ON;UPDATE dbo.PurchaseOrderHeaderSET DateModified= GetDate()FROM dbo.PurchaseOrderHeader POH JOIN INSERTED ION POH.PurchaseOrderID = I.PurchaseOrderID JOIN DELETED DON POH.PurchaseOrderID = D.PurchaseOrderIDWHERE I.OrderDate <> D.OrderDate ORI.Freight <> D.FreightENDGOUSE MiniAdventureWorksDBGOCREATE TRIGGER UpdateShipMethodON dbo.ShipMethodAFTER UPDATE AS	BEGIN		SET NOCOUNT ON;UPDATE dbo.ShipMethodSET DateModified= GetDate()FROM dbo.ShipMethod SM JOIN INSERTED ION SM.ShipMethodID = I.ShipMethodID JOIN DELETED DON SM.ShipMethodID = D.ShipMethodIDWHERE I.Name <> D.NameENDGO
Trigger CreationUSE MiniAdventureWorksDBGOCREATE TRIGGER UpdateVendorON dbo.VendorAFTER UPDATE AS	BEGIN		SET NOCOUNT ON;UPDATE dbo.VendorSET DateModified= GetDate()FROM dbo.Vendor V JOIN INSERTED ION V.VendorID = I.VendorID JOIN DELETED DON V.VendorID = D.VendorIDWHERE I.Name <> D.Name ORI.CreditRating <> D.CreditRatingENDGO
Stored ProcedureStored Procedure CreationUSE MiniAdventureWorksDBGOCREATE procedure InsertOrderHeader	@POHeaderNumbernvarchar(50), @VendorIDint, @ShipMethodIDint, 	@OrderdateDateTime, @Freight decimal(14,2), @TotalDuedecimal (14,2), 	@PurchaseOrderIDint OUTPUTAS	BEGIN		INSERT INTO PurchaseOrderHeader(POHeaderNumber, VendorID, ShipMethodID, OrderDate, Freight, TotalDue)    VALUES (@POHeaderNumber, @VendorID , @ShipMethodID , @Orderdate , @Freight, @TotalDue)SET @PurchaseOrderID= SCOPE_IDENTITY()ENDGO
User Defined FunctionUser Defined FunctionUSE [MiniAdventureWorksDB]GO/****** Object:  UserDefinedFunction [dbo].[udf_Top_N_ProductOrdersForVendor]    Script Date: 11/30/2009 19:59:19 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE FUNCTION [dbo].[udf_Top_N_ProductOrdersForVendor] (@VendorIDint, @TopCountint)RETURNS @TopProducts   TABLE (VendorIDint, ProductIDint, ProductNamevarchar(100), ProductTotalDueDECIMAL(14,2), ProductRankint)AS   BEGIN;WITH ProductCTE AS (SELECT TOP (@TopCount) VendorID, ProductID, SUM(POD.TotalDue) AS ProductTotalDue				FROM dbo.PurchaseOrderDetail POD join dbo.PurchaseOrderHeader POH  ON POD.PurchaseOrderID = POH.PurchaseOrderIDWHERE POH.VendorID = @VendorIDGROUP BY VendorID,ProductIDORDER BY ProductTotalDueDesc)INSERT INTO @TopProducts					SELECT VendorID, ProductCTE.ProductID, Product.ProductNameas ProductName, ProductTotalDue, dense_RANK() OVER (ORDER BY ProductTotalDuedesc) as ProductRank                    FROM ProductCTEJOIN dbo.ProductON ProductCTE.ProductID = Product.ProductIDRETURN            ENDGO
SSIS PackagesCreate Database
Import  Products
Import  Products
Import  Products
Import  Vendors
Import  Vendors
Import  ShipMethod
Import  ShipMethod
Import  Orders
Import  Orders
Product Price Increase
Product Price Increase
Stored ProceduresXML Source FilesSSIS PackagesBlockFlix
Stored ProceduresInsert MovieUSE [Blockflix]GO/****** Object:  StoredProcedure [dbo].[usp_InsertMovie]    Script Date: 12/11/2009 11:46:49 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE procedure [dbo].[usp_InsertMovie]	@MovieTitlenvarchar(100), @GenreIDint, @RatingIDint, 	@Year nvarchar(4), @MovieDescriptionnvarchar(max),	@MovieIDint OUTPUTAS	BEGIN		INSERT INTO dbo.Movies(MovieTitle, GenreID, RatingID, Year, MovieDescription)    VALUES (@MovieTitle, @GenreID, @RatingID, @Year, @MovieDescription)SET @MovieID= SCOPE_IDENTITY()ENDGO
Insert Movie Into InventoryUSE [Blockflix]GO/****** Object:  StoredProcedure [dbo].[usp_InsertMovieIntoInventory]    Script Date: 12/11/2009 11:48:45 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE procedure [dbo].[usp_InsertMovieIntoInventory]	@ProductNamenvarchar(50), @ItemQtyint,	@ProductTypeIDint, @MediaTypeIDint,	@StatusIDint, @MovieIDintAS	BEGIN		DECLARE @loopiterationint, @RowQtyint		SET @loopiteration= 0SET @RowQty= 1WHILE @loopiteration< @ItemQtyBEGININSERT INTO dbo.MasterInventory(ProductName, QTY, ProductTypeID, MediaTypeID, StatusID, MovieID)VALUES(@ProductName, @RowQty, @ProductTypeID, @MediaTypeID, @StatusID,(SELECT MovieID							FROM Movies 					WHERE MovieTitle= @ProductName))SET @loopiteration= @loopiteration + 1END	ENDGO
Insert Into CastUSE [Blockflix] GO/****** Object:  StoredProcedure [dbo].[usp_InsertIntoCast]    Script Date: 12/11/2009 11:49:52 ******/SET ANSI_NULLS ON GOSET QUOTED_IDENTIFIER ON GOCREATE procedure [dbo].[usp_InsertIntoCast]	@MovieIDint, @Director1ID int, @Director2ID int, @Actor1ID int, 	@Actor2ID int, @Actor3ID int, @Producer1ID int, @Producer2ID intAS	BEGIN--directors: JobTypeID for director is 2		--director1INSERT INTO dbo.Cast(MovieID, PersonID, JobTypeID) VALUES (@MovieID, @Director1ID, 2)--if director2 is not null then it will insert into the Cast table	IF @Director2ID IS NOT NULL AND @Director2ID <> 0BEGININSERT INTO dbo.Cast(MovieID, PersonID, JobTypeID) VALUES (@MovieID, @Director2ID, 2)END		ELSE--actors: JobTypeID for actors is 1		--actor1INSERT INTO dbo.Cast(MovieID, PersonID, JobTypeID) VALUES (@MovieID, @Actor1ID, 1)--actor2INSERT INTO dbo.Cast(MovieID, PersonID, JobTypeID) VALUES (@MovieID, @Actor2ID, 1)--actor3INSERT INTO dbo.Cast(MovieID, PersonID, JobTypeID) VALUES (@MovieID, @Actor3ID, 1)--producers: JobTypeID for producers is 3		--producer1INSERT INTO dbo.Cast(MovieID, PersonID, JobTypeID) VALUES (@MovieID, @Producer1ID, 3)--producer2: testing to see if producer2 is not null	IF @Producer2ID IS NOT NULL AND @Producer2ID <> 0BEGININSERT INTO dbo.Cast(MovieID, PersonID, JobTypeID) VALUES (@MovieID, @Producer2ID, 3)END	ENDGO
Insert ProductsUSE [Blockflix]GO/****** Object:  StoredProcedure [dbo].[usp_InsertProducts]    Script Date: 12/11/2009 11:50:09 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE procedure [dbo].[usp_InsertProducts]	@ProductNamenvarchar(50), @ItemQtyint,	@ProductTypeIDint, @MediaTypeIDint,	@StatusIDintAS	BEGIN--local variable declarationDECLARE @loopiterationint, @RowQtyintSET @loopiteration= 0SET @RowQty= 1--testing to see if the product type is video game (2)IF @ProductTypeID= 2BEGIN		--loop will insert multiple rows for video games so that --each copy of a video game will have a unique SKU #WHILE @loopiteration< @ItemQtyBEGININSERT INTO dbo.MasterInventory(ProductName, QTY, ProductTypeID, MediaTypeID, StatusID)VALUES (@ProductName, @RowQty, @ProductTypeID, @MediaTypeID, @StatusID)SET @loopiteration= @loopiteration + 1ENDENDELSE		INSERT INTO dbo.MasterInventory(ProductName, QTY, ProductTypeID, MediaTypeID, StatusID)VALUES (@ProductName, @ItemQty, @ProductTypeID, @MediaTypeID, @StatusID)ENDGO
Customer Queue Part 1
Customer Queue Part 2
Customer Queue Results
XML Source File For Movies
XML Source File For Products
SSIS PackagesImport Movies
Import Movies
Import Movies
Import Movies
Import Products
Import Products
Import Store Info
Import Kiosk Info
Import Kiosk Info
Database Design DiagramInstructor Results Report Examples (SSRS)Evaluation Application
SQL Server 2008 Portfolio
SQL Server 2008 Portfolio
SQL Server 2008 Portfolio

More Related Content

What's hot (11)

PDF
D8 Form api
Samuel Solís Fuentes
 
PPTX
Functional GUIs with F#
Frank Krueger
 
PDF
Dig Deeper into WordPress - WD Meetup Cairo
Mohamed Mosaad
 
PDF
Modeling for Performance
MongoDB
 
PDF
Data Modeling for Performance
Michael Dwan
 
PPTX
IBM Db2 JSON 11.5
Phil Downey
 
PDF
UITableView Pain Points
Ken Auer
 
PDF
Personalized Search on the Largest Flash Sale Site in America
Adrian Trenaman
 
PPTX
Using solr in online travel to improve  user experience - By Karegowdra Sudha...
lucenerevolution
 
PDF
[Www.pkbulk.blogspot.com]dbms05
AnusAhmad
 
Functional GUIs with F#
Frank Krueger
 
Dig Deeper into WordPress - WD Meetup Cairo
Mohamed Mosaad
 
Modeling for Performance
MongoDB
 
Data Modeling for Performance
Michael Dwan
 
IBM Db2 JSON 11.5
Phil Downey
 
UITableView Pain Points
Ken Auer
 
Personalized Search on the Largest Flash Sale Site in America
Adrian Trenaman
 
Using solr in online travel to improve  user experience - By Karegowdra Sudha...
lucenerevolution
 
[Www.pkbulk.blogspot.com]dbms05
AnusAhmad
 

Similar to SQL Server 2008 Portfolio (20)

PPT
Sql Portfolio(March 31)
iceolated
 
PPTX
Robert Parkin Portfolio
rsparkin
 
PPTX
Reynaldo Fadri’S Porfolio
rfadri
 
PPTX
Marcus Matthews
MarcusMatthews38
 
PPTX
SQL command practical power point slides, which help you in learning sql.pptx
macivem311
 
PPTX
SQL command practical power point slides, which help you in learning sql.pptx
macivem311
 
PPT
Sql Portfolio
Shelli Ciaschini
 
PPSX
Jessica Herndon Sql Portfolio
JessicaLHerndon
 
PDF
10g sql e book
Mansoor Abd Algadir
 
PPTX
Database Basics
Abdel Moneim Emad
 
PPSX
Dennis Schmid Portfolio
Dennis Schmid
 
PPT
Module02
Sridhar P
 
PPTX
Sql Basics And Advanced
rainynovember12
 
PPT
Bis 345-final-exam-guide-set-1-new
assignmentcloud85
 
PPT
Kevin Bengtson Portfolio
Kbengt521
 
PPTX
Sql introduction
Bhavya Chawla
 
PPT
Sql server T-sql basics ppt-3
Vibrant Technologies & Computers
 
PPT
Sql Server 2000
Om Vikram Thapa
 
PPT
Sql portfolio admin_practicals
Shelli Ciaschini
 
PDF
Essentials of Database Management 1st Edition Hoffer Test Bank
kontzorrano4
 
Sql Portfolio(March 31)
iceolated
 
Robert Parkin Portfolio
rsparkin
 
Reynaldo Fadri’S Porfolio
rfadri
 
Marcus Matthews
MarcusMatthews38
 
SQL command practical power point slides, which help you in learning sql.pptx
macivem311
 
SQL command practical power point slides, which help you in learning sql.pptx
macivem311
 
Sql Portfolio
Shelli Ciaschini
 
Jessica Herndon Sql Portfolio
JessicaLHerndon
 
10g sql e book
Mansoor Abd Algadir
 
Database Basics
Abdel Moneim Emad
 
Dennis Schmid Portfolio
Dennis Schmid
 
Module02
Sridhar P
 
Sql Basics And Advanced
rainynovember12
 
Bis 345-final-exam-guide-set-1-new
assignmentcloud85
 
Kevin Bengtson Portfolio
Kbengt521
 
Sql introduction
Bhavya Chawla
 
Sql server T-sql basics ppt-3
Vibrant Technologies & Computers
 
Sql Server 2000
Om Vikram Thapa
 
Sql portfolio admin_practicals
Shelli Ciaschini
 
Essentials of Database Management 1st Edition Hoffer Test Bank
kontzorrano4
 
Ad

Recently uploaded (20)

PPTX
Role_of_Artificial_Intelligence_in_Livestock_Extension_Services.pptx
DrRajdeepMadavi
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PPTX
Securing Model Context Protocol with Keycloak: AuthN/AuthZ for MCP Servers
Hitachi, Ltd. OSS Solution Center.
 
PDF
Software Development Company Keene Systems, Inc (1).pdf
Custom Software Development Company | Keene Systems, Inc.
 
PPTX
Wondershare Filmora Crack Free Download 2025
josanj305
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PDF
“ONNX and Python to C++: State-of-the-art Graph Compilation,” a Presentation ...
Edge AI and Vision Alliance
 
PDF
NASA A Researcher’s Guide to International Space Station : Earth Observations
Dr. PANKAJ DHUSSA
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PDF
Home Cleaning App Development Services.pdf
V3cube
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PPTX
Talbott's brief History of Computers for CollabDays Hamburg 2025
Talbott Crowell
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PPTX
Manual Testing for Accessibility Enhancement
Julia Undeutsch
 
PDF
Bharatiya Antariksh Hackathon 2025 Idea Submission PPT.pdf
ghjghvhjgc
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PPTX
Essential Content-centric Plugins for your Website
Laura Byrne
 
PDF
[GDGoC FPTU] Spring 2025 Summary Slidess
minhtrietgect
 
Role_of_Artificial_Intelligence_in_Livestock_Extension_Services.pptx
DrRajdeepMadavi
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Securing Model Context Protocol with Keycloak: AuthN/AuthZ for MCP Servers
Hitachi, Ltd. OSS Solution Center.
 
Software Development Company Keene Systems, Inc (1).pdf
Custom Software Development Company | Keene Systems, Inc.
 
Wondershare Filmora Crack Free Download 2025
josanj305
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
“ONNX and Python to C++: State-of-the-art Graph Compilation,” a Presentation ...
Edge AI and Vision Alliance
 
NASA A Researcher’s Guide to International Space Station : Earth Observations
Dr. PANKAJ DHUSSA
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
Home Cleaning App Development Services.pdf
V3cube
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
Talbott's brief History of Computers for CollabDays Hamburg 2025
Talbott Crowell
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
Manual Testing for Accessibility Enhancement
Julia Undeutsch
 
Bharatiya Antariksh Hackathon 2025 Idea Submission PPT.pdf
ghjghvhjgc
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
Essential Content-centric Plugins for your Website
Laura Byrne
 
[GDGoC FPTU] Spring 2025 Summary Slidess
minhtrietgect
 
Ad

SQL Server 2008 Portfolio

  • 2. IntroductionGood day… My name is Susan Whitfield and I set out on a journey to augment my IT skills. This led me to SetFocus, LLC. and their SQL Masters Program. The goal of this program is to provide trainees with the skills necessary to become SQL Server 2008 experts, and to utilize the knowledge learned, in a real world setting within a short amount of time. SetFocus is a certified Microsoft Gold partner and uses Microsoft certified courses to accomplish this goal. The course was a very intense 13 weeks long, which showed the database administration side as well as the development side of SQL Server 2008. Included in this presentation are examples from projects completed during the 13 weeks. We utilized; SSMS (SQL Server Management Studio), SSIS (SQL Server Integration Studio), SSRS (SQL Server Report Studio), Visio, and BIDS (Business Intelligence Development Studio), in order to develop T-SQL code, create: packages, reports, database diagrams, as well as administer: security, mirroring, clustering, replication, snapshots, isolation levels, jobs, and other administration tasks.Enjoy the presentation and if you have any questions please feel free to contact me at the email included. Susan Whitfield
  • 3. Table of ContentsIntroduction . . . . . . . . . . . . 2Piggy Bank 1 Project:. . . . . . . . . . . 4Designing databaseTSQL Assignment: . . . . . . . . . . . 8Designing database and utilizing T-SQL skillsPiggy Bank 2 Project:. . . . . . . . . . . 24Designing database, creating: views, triggers, and robust stored procedures, shredding XMLDBA Practical’s: . . . . . . . . . . . . 38Adventure Works Repair Project: . . . . . . . . . 44T-SQL practiceMini Adventure Works Project: . . . . . . . . . 50Table creation, triggers, stored procedures, user defined function, and SSIS packagesBlockFlix Project (Final Project: showing portions I completed): . . .74Stored procedures , XML Source Files, SSIS packagesEvaluation Application (Mini-Final Project: showing portions I completed): . 93Instructor Results Report examples
  • 5. Project SpecificationsCreate a database for Piggy Unlimited. We were given a list of columns and were asked to create tables, establish relationships via primary key constraints and foreign key constraints and choose most appropriate data types. After database/table creation we were asked to backup the database and send that backup to the instructor. We were required to denormalize to 3rd NF, and to justify use of denormalization.
  • 9. Database CreationUSE [JungleBooks]GO/****** Object: Table [dbo].[Orders] Script Date: 10/07/2009 00:01:16 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE TABLE [dbo].[Orders]( [OrderID] [int] NOT NULL, [CustomerID] [int] NOT NULL, [OrderDate] [smalldatetime] NOT NULL, CONSTRAINT [PK_Orders] PRIMARY KEY CLUSTERED ( [OrderID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]GO/****** Object: Table [dbo].[OrderItems] Script Date: 10/07/2009 00:01:16 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOSET ANSI_PADDING ONGOCREATE TABLE [dbo].[OrderItems]( [OrderItemID] [int] NOT NULL, [OrderID] [int] NOT NULL, [ISBN] [char](20) NOT NULL, [QuantityOrdered] [int] NOT NULL, [QuantityDispatched] [int] NOT NULL, [UnitPrice] [money] NOT NULL, CONSTRAINT [PK_OrderItems] PRIMARY KEY CLUSTERED ( [OrderItemID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]
  • 10. GOSET ANSI_PADDING OFFGO/****** Object: Table [dbo].[Customers] Script Date: 10/07/2009 00:01:16 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOSET ANSI_PADDING ONGOCREATE TABLE [dbo].[Customers]( [CustomerID] [int] NOT NULL, [Name] [varchar](80) NOT NULL, [Address] [varchar](255) NOT NULL, [CardType] [char](20) NOT NULL, [CardNumber] [char](20) NOT NULL, [ExpiryDate] [smalldatetime] NOT NULL, CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED ( [CustomerID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]GOSET ANSI_PADDING OFFGO/****** Object: Table [dbo].[Books] Script Date: 10/07/2009 00:01:16 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOSET ANSI_PADDING ONGOCREATE TABLE [dbo].[Books]( [ISBN] [char](20) NOT NULL, [Publisher] [varchar](50) NOT NULL, [Title] [varchar](128) NOT NULL, [UnitPrice] [money] NOT NULL, [Abstract] [varchar](255) NOT NULL, [Pages] [smallint] NOT NULL, [Published] [smalldatetime] NOT NULL, [Stock] [int] NOT NULL, CONSTRAINT [PK_Books] PRIMARY KEY CLUSTERED (
  • 11. [ISBN] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]GOSET ANSI_PADDING OFFGO/****** Object: Table [dbo].[BookAuthors] Script Date: 10/07/2009 00:01:16 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOSET ANSI_PADDING ONGOCREATE TABLE [dbo].[BookAuthors]( [BookAuthorID] [int] NOT NULL, [ISBN] [char](20) NOT NULL, [AuthorID] [int] NOT NULL, CONSTRAINT [PK_BookAuthors] PRIMARY KEY CLUSTERED ( [BookAuthorID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]GOSET ANSI_PADDING OFFGO/****** Object: Table [dbo].[Authors] Script Date: 10/07/2009 00:01:16 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOSET ANSI_PADDING ONGOCREATE TABLE [dbo].[Authors]( [AuthorID] [int] NOT NULL, [Name] [varchar](120) NOT NULL, CONSTRAINT [PK_Authors] PRIMARY KEY CLUSTERED ( [AuthorID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]GOSET ANSI_PADDING OFFGO
  • 13. Problem 1The Cheap Books form displays available books below a certain price. The user enters 15 in the txtUnitPrice form field. Return ISBN, title and publisher in order by title.Statement1Write a query that displays ISBN, title, publisher having books that are priced less than $15, ordered by the title.T-SQL1SELECT ISBN, Title, PublisherFROM BooksWHEREUnitPrice< 15ORDERBY TitleProblem 2The Search For Authors form displays a list of author names which contains a string which is input by the user. The user enters ‘pet’ in the txtName form field. Display author names in alphabetical order. Use the alias ‘Search Results’ for the author name data.Statement2Write a query that displays author names having the name ‘pet’, displayed in alphabetical order. Use heading: ‘Search Results’.T-SQL2SELECT Name AS'Search Results'FROM AuthorsWHERE Name like'%pet%'ORDERBY Name
  • 14. Problem 3The Range of Customers form allows the user to view orders placed within a given range of customer IDs. The user enters 6 in the txtIDStart form field and 15 in txtIDEnd form field. Display all columns of data in order by Customer ID. Alias the columns in the result set as: ‘Order #’, ‘Cust ID’, ‘Order Date’.Statement3Write a query to display order number, customer id, and order date ordered by customer id having customer ids in the range between 6 and 15. Use headings: ‘Order#’, ‘Cust ID’, and ‘Order Date’.T-SQL3SELECTOrderID'Order#',CustomerID'Cust ID',OrderDate'Order Date'FROM OrdersWHERECustomerIDbetween 6 and 15ORDERBYCustomerIDProblem 4The Large Orders page is a report displaying the largest number of items sold per order. Display the Order ID, Customer ID and Name along with the total number of items they ordered. Display the record with the largest quantity first. Alias as: “Order ID’, ‘Cust ID’, ‘Customer’ and ‘# of items’.Statement4Write a query that displays order id, customer id, name and quantity of ordered items, showing the largest quantity first. Use Headings: ‘Order ID’, ‘Cust ID’, ‘Customer’ and ‘# of items’.T-SQL4SELECTO.OrderID'Order ID',O.CustomerID'Cust ID', Name 'Customer',SUM(QuantityOrdered)'# of items'FROM Customers C JOIN Orders O ONC.CustomerID=O.CustomerIDJOINOrderItems OI ONO.OrderID=OI.OrderIDGROUPBYO.OrderID,O.CustomerID, NameORDERBYSUM(QuantityOrdered)DESC
  • 15. Problem 5The Available Books page is a report listing the publishers and the books they offer. Output a list of publishers, the books they publish and each book’s ISBN. Ensure the output lists the Publishers in alphabetical order and the titles in alphabetical order.Statement5Write a query to display publishers, books they publish and the ISBN for each book, displaying in alphabetical orderT-SQL5SELECT Publisher, Title, ISBNFROM BooksORDERBY Publisher, TitleProblem 6The Expired Cards page is a report on credit cards that have expired and credit cards that will expire soon. Output the customer ID, customer name and expiry date of the card for records with an expiry date prior to 30 days after the current date (today). Display the records by expiry date in descending order. Alias as: ‘ID’, ‘Name’, ‘Expires’.Statement6Write a query to display customer ID, customer name, expiry date for records that are expiring within the next thirty days in descending order. Use headings: ‘ID’, ‘Name’, ‘Expires’T-SQL6SELECTCustomerID'ID', Name 'Name',ExpiryDate'Expires'FROM CustomersWHEREExpiryDate < Getdate()+30ORDERBYExpiryDateDESC
  • 16. Problem 7The Author and Books page is a report which lists the author name, book title and ISBN. The list is to be output in order by author name and title.Statement7Write a query to display the author name, book title and ISBN, displayed in order by author name and title.T-SQL7SELECT Name, Title, BA.ISBNFROM Authors A JOINBookAuthors BA ONA.AuthorID=BA.AuthorIDJOIN Books B ON B.ISBN = BA.ISBNORDERBY Name, TitleProblem 8The Hot Items page is a report of popular items. The user will input 5 in the txtMinimumTotal form field. Display ISBN, Title and the total number of items ordered. The total is to represent the sum of all quantity ordered amounts per ISBN. Display all records with a total greater than or equal to 5. The hottest items should be listed first. Alias as: ‘ISBN’, ’Title’ , ’Total’.Statement8Write a query that displays ISBN, Title, total number of items ordered where the total is greater or equal to 5, with the output ordered by total descending. Use headings ‘ISBN’, ‘Title’ and ‘Total’. T-SQL8SELECT OI.ISBN 'ISBN', Title 'Title',SUM(QuantityOrdered)'Total'FROMOrderItems OI JOIN Books B ON OI.ISBN = B.ISBNGROUPBY OI.ISBN, TitleHAVINGSUM(QuantityOrdered)>= 5ORDERBYSUM(QuantityOrdered)DESC
  • 17. Problem 9The Search For Customers by Credit Card page also allows the user to search for Customers by the last four digits of their credit card number. The user inputs ‘’7889” in the txtLastFourDigits form field. Return all information from the Customer table. Alias as: ‘ID’, ‘Name’, ‘CurrentAddress’, ’CardType’, ‘CardNumber’, ‘Expires’. In case you have different customers using the same credit card, order by Customer ID in ascending order.Statement9Write a query to display customer id, name, address, cardtype, cardnumber, and expirydate using the last four digits in the credit card number. Use headings: ‘ID’, ‘Name’, ‘CurrentAddress’, ‘CardType’, ‘CardNumber’, and ‘Expires’.T-SQL9SELECTCustomerID'ID', Name 'Name',Address'CurrentAddress',CardType'CardType',CardNumber'CardNumber',ExpiryDate'Expires'FROM CustomersWHERECardNumberlike'%7889'ORDERBYCustomerIDProblem 10Write and execute a query on the Member and Adult tables in the Library database that returns the firstname, middleinitial, lastname, street, city, state and zip. Concatenate the firstname, middleinitial and lastname columns into one string and alias as Name. Make sure that the spacing is appropriate when there is no middle initial due to a NULL or empty string value. Display records in order by lastname and firstname.Statement10Write a query to display firstname, middleinitial, lastname, street, city, state and zip. Should be displayed in order by the lastname and firstname.T-SQL10SELECT (firstname+' '+isnull(middleinitial+' ','')+lastname) AS'Name', street, city,state, zip FROM adult a JOIN member m ONa.member_no=m.member_no ORDERBYlastname,firstname
  • 18. Problem 11Write and execute a query on the Title, Item and Copy tables that returns the ISBN, copy_no, on_loan, title, translation, and cover for rows in the copy table with an ISBN of 500 or 1000. Only available books should be displayed and hardback copies should be listed first.Statement11Write a query that displays the ISBN, copy_no, on_loan, title, translation, and cover where the ISBN is 500 or 1000 and the books are available and order it by cover.T-SQL11SELECTc.isbn,copy_no,on_loan, title, translation, cover FROM title t JOIN item iONt.title_no=i.title_noJOIN copy c ONc.isbn=i.isbnWHERE(c.ISBN= 500 ORc.ISBN= 1000) AND on_loan='N'ORDERBY coverProblem 12Write and execute a query to retrieve the member’s full name and member_no from the Member table and the ISBN and log_date values from the Reservation table for member numbers 250, 341, and 1675. Order the results by member_no and log_date. You should show information for these members, even if they have no books on reserve.Statement12Write a query to display firstname, middleinitial, lastname, member_no, ISBN, log_date for members with 250, 341 and 1675 member numbers. Order results by member_no and log_date. Members who do not have books on reserve should be included in the output.T-SQL12SELECTfirstname,middleinitial,lastname,m.member_no,isbn,log_dateFROM member m LEFTOUTERJOIN reservation r ONm.member_no=r.member_noWHEREm.member_noin(250, 341, 1675)ORDERBYm.member_no,log_date
  • 19. Problem 13Using joins and a UNION clause, write a query to retrieve a single list of members both adult and juvenile, who have reserved ISBN number 288. The list must include the ISBN, title, member_no and name (i.e.: Smith, John) of each member who has the reservation. Additionally, the list should indicate whether the member is an adult or a juvenile. Output the records by name.Statement13Write a query that displays ISBN, title, member_no, name of each member (adult/juvenile) who has the book with ISBN number 288 reserved; indicate whether member is adult/juvenile and output records by name.T-SQL13 (Query #1 in problem #14)SELECTc.isbn, title,a.member_no,lastname+', '+firstnameas'name','Adult'as'Adult / Juvenile'FROM adult a JOIN reservation r ONa.member_no=r.member_noJOIN copy c ONr.isbn=c.isbnJOIN title t ONc.title_no=t.title_noJOIN member m ONm.member_no=a.member_noWHEREc.ISBN= 288UNIONSELECTc.isbn, title,j.member_no,lastname+', '+firstnameas'name','Juvenile'as'Adult / Juvenile'FROM juvenile j JOIN reservation r ONj.member_no=r.member_noJOIN copy c ONr.isbn=c.isbnJOIN title t ONc.title_no=t.title_noJOIN member m ONm.member_no=j.member_noWHEREc.ISBN= 288ORDERBY'name'
  • 20. Problem 14Write the above statement again using a CASE statement. You cannot JOIN to the Adult or Juvenile tables. Compare the two versions and determine which one is more efficient. Cut and paste the proof of your research. (No need to copy the output of records)Statement14Write the query from problem 13 using a CASE statement. Compare each version and determine which one is more efficient.T-SQL14 (Query #2)SELECTi.isbn, title,m.member_no,lastname+', '+firstname'name','Adult/Juvenile'=CASEWHENEXISTS(SELECTmember_noFROM juvenile jWHEREj.member_no=m.member_no)THEN'Juvenile'ELSE'Adult'ENDFROM member m JOIN reservation r ONm.member_no=r.member_noJOIN item iONi.isbn=r.isbnJOIN title t ONt.title_no=i.title_noWHEREi.isbn= 288ORDERBY'name'Output14Viewing the Execution plan in SSMS, we find this: Query 1: Query cost (relative to the batch: 65% Query 2: Query cost (relative to the batch: 35%The above indicates that Query 2, using the CASE statement, was more efficient.
  • 21. Problem 15Write and execute a query that returns the member_no, full name, out_date, due_date, and title columns from the Loan, Member, and Title tables. Convert the datetime values from the out_date and due_date columns to char(12), format 101. Restrict the results to books which were due prior to the current date. Load the records into a temporary table called #overdue. Leave the query window open after you create the temporary table.Statement15Write a query to display member_no, full name, out_date, due_date, and title. Datetime values should be converted to specified format and only books that were due before today’s date should be returned. Load all returned records into a temp table.T-SQL15CREATETABLE #overdue(member_nosmallintNOTNULL,fullnamevarchar(35)NOTNULL,out_datechar(12)NOTNULL,due_datechar(12)NOTNULL, title varchar(63)NOTNULL) INSERTINTO #overdue (member_no,fullname,out_date,due_date, title)SELECTm.member_no,firstname+' '+ISNULL(SUBSTRING(middleinitial,1,1),'')+' '+lastname,CONVERT(char(12),out_date, 101)ASout_date,CONVERT(char(12),due_date, 101)ASdue_date, titleFROM loan l JOIN title t ONl.title_no=t.title_noJOIN member m ONm.member_no=l.member_noWHEREdue_date<GETDATE()
  • 22. Problem 16Write and execute a query that returns the member number, member name and number of past due loans of each member from the #overdue table in a column called ‘# Overdue’. Use the same query window that you used to create the temporary table. Display by the number outstanding and the member name.Statement16Write a query to display the member number, member name, number of past due loans in a specific column. Oder by number outstanding and the member name. Use heading: ‘# Overdue’.T-SQL16SELECTmember_no,fullname,COUNT(due_date)AS'# Overdue'FROM #overdueGROUPBYmember_no,fullnameORDERBY'# Overdue'DESC,fullnameProblem 17Write and execute a query that returns member_no, firstname, lastname and sum of fine_paid for members who have paid the highest fines to date. Members should only appear once in the list. Display the highest fine first. If more than one member has paid the same amount display the records in order by member_no.Statement17Write a query to display member_no, firstname, lastname, and sum of fine-paid for members who have paid the highest fines to date. Order by fine_paid, if more than one member has paid the same amount display in order by member_no.T-SQL17SELECTlh.member_no,firstname,lastname,SUM(fine_paid)AS'Paid Fines'FROMloanhistlhJOIN member m ONlh.member_no=m.member_noWHEREfine_paidISNOTNULLGROUPBYlh.member_no,firstname,lastnameORDERBY'Paid Fines'DESC,lh.member_no
  • 23. Problem 18Write and execute a query on the Reservation table that returns the ISBN, title and Total. The Total column is a calculated column which represents the number of members wishing to reserve a particular book.Statement18Write a query that displays ISBN, title, and total (calculated column).T-SQL18SELECTr.isbn, title,Count(member_no)AS'Total'FROM reservation r JOIN item iONr.isbn=i.isbnJOIN title t ONt.title_no=i.title_noGROUPBYr.isbn, title
  • 24. Diagram 0ViewsTriggersStored procedures (code snippets of a few sp’s)XML shred snippetPiggy Bank 2 Project
  • 26. Views/****** Object: View [dbo].[v_CurrentMonthStatement] Script Date: 10/17/2009 00:43:55 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE VIEW [dbo].[v_CurrentMonthStatement] WITH SCHEMABINDINGAS SELECT CustomerFirstName, CustomerMiddleInitial, CustomerLastName, Street, City, State, ZipCode, TransactionID, AccountID, TransactionTypeID, T.CustomerID, TransactionDate, TransactionAmount, NewBalance FROM dbo.Transactions T JOIN dbo.Customer C ONT.CustomerID = C.CustomerIDGO/****** Object: View [dbo].[v_GetBalance] Script Date: 10/17/2009 00:43:55 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE VIEW [dbo].[v_GetBalance] WITH SCHEMABINDINGAS SELECT TransactionID, AccountID, T.TransactionTypeID, CustomerID, TransactionDate, TransactionAmount, TransactionTypeName,NewBalance FROM dbo.Transactions T JOIN dbo.TransactionType TT ONT.TransactionTypeID = TT.TransactionTypeIDGO
  • 27. /****** Object: View [dbo].[v_GetHistoricalStatement] Script Date: 10/17/2009 00:43:55 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE VIEW [dbo].[v_GetHistoricalStatement] WITH SCHEMABINDINGAS SELECT CustomerFirstName, CustomerMiddleInitial, CustomerLastName, Street, City, State, ZipCode, TransactionID, AccountID,TransactionTypeID, T.CustomerID, TransactionDate,TransactionAmount, NewBalance FROM dbo.Transactions T JOIN dbo.Customer C ONT.CustomerID = C.CustomerIDGO/****** Object: View [dbo].[v_GetTransactions] Script Date: 10/17/2009 00:43:55 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE VIEW [dbo].[v_GetTransactions] WITH SCHEMABINDINGAS SELECT TransactionID, AccountID, TransactionTypeID,CustomerID, TransactionDate, TransactionAmount,NewBalance FROM dbo.TransactionsGO
  • 28. /****** Object: View [dbo].[v_ListCustomerAccounts] Script Date: 10/17/2009 00:43:55 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE VIEW [dbo].[v_ListCustomerAccounts] WITH SCHEMABINDINGAS SELECT CustomerFirstName, CustomerMiddleInitial, CustomerLastName, Street, City, State, ZipCode, CA.AccountID, CA.CustomerID FROM dbo.CustomerAccount CA JOIN dbo.Customer C ONC.CustomerID = CA.CustomerIDGO
  • 29. TriggersUSE [PiggyBankWk4]GO/****** Object: DdlTrigger [NoUnwantedChanges] Script Date: 10/17/2009 00:50:48 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE TRIGGER [NoUnwantedChanges] ON DATABASE FOR DROP_TABLE, ALTER_TABLE AS PRINT 'You must disable Trigger "NoUnwantedChanges" to drop or alter tables!' ROLLBACK;GO/****** Object: Trigger [dbo].[NoAccountDeletions] Script Date: 10/17/2009 00:51:09 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE TRIGGER [dbo].[NoAccountDeletions]ON [PiggyBankWk4].[dbo].[Account]FOR DELETE AS PRINT 'You cannot delete accounts from the Account table, you may however disable the account.' ROLLBACKGO
  • 30. SP’sAdd Account Stored Proc Code Snippet
  • 31. Deposit Transaction Stored Proc Code Snippet
  • 32. Deposit Transfer Stored Proc Code Snippet
  • 33. Insert Customer Stored Proc Code Snippet
  • 34. Close Account Stored Proc Code Snippet
  • 35. Reopen Account Stored Proc Code Snippet
  • 36. Withdrawal Transfer Stored Proc Code Snippet
  • 38. Backup/Restore Disaster Recovery Mini-SimulationSnapshot Creation and UsageWorking With SchemasResource Governor Configuration & UsageOwnership ChainingDBA Practical’s
  • 39. Backup & Restore: Disaster Recovery Mini-Simulation--primary file group backupBACKUP DATABASE [AdventureWorks2008] FILEGROUP = N'PRIMARY' TO [Adventureworks2008Backups] WITH NOFORMAT, INIT, NAME = N'AdventureWorks2008-Full Primary Filegroup Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10GO--secondary file group backupBACKUP DATABASE [AdventureWorks2008] FILEGROUP = N'EmployeeWorkHistoryFG' TO [Adventureworks2008Backups] WITH NOFORMAT, NOINIT, NAME = N'AdventureWorks2008-Full Secondary Filegroup Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10GO--Update the ClockOutTime for the only record in the EmployeeWorkHistoryTable. The current value is NULLUSE AdventureWorks2008GOUPDATE HumanResources.EmployeeWorkHistorySET ClockOutTime= GETDATE() WHERE BusinessEntityID= 1--log file backupBACKUP LOG [AdventureWorks2008] TO [Adventureworks2008Backups] WITH NOFORMAT, NOINIT, NAME = N'AdventureWorks2008-Transaction Log Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10GO--Simulate accidental deletion of a table by executing the following statements:DROP TABLE HumanResources.EmployeeWorkHistory--secondary filegroup with norecovery, the transaction log backup with RECOVERYRESTORE HEADERONLY FROM Adventureworks2008Backups--AdventureWorks2008-Full Primary FilegroupBackup,AdventureWorks2008-Full Secondary FilegroupBackup, AdventureWorks2008-Transaction Log BackupRESTORE FILELISTONLY FROM Adventureworks2008Backups--AdventureWorks2008_Data , EmpWorkHist, AdventureWorks2008_Log, -FileStreamDocumentsUse masterGORESTORE DATABASE AdventureWorks2008 FROM Adventureworks2008Backups WITH FILE = 1, NORECOVERY--Processed 8 pages for database 'AdventureWorks2008', file 'EmpWorkHist' on file 2.--RESTORE DATABASE ... FILE=<name> successfully processed 8 pages in 0.134 seconds (0.466 MB/sec).RESTORE LOG AdventureWorks2008 FROM Adventureworks2008Backups WITH RECOVERY--Processed 0 pages for database 'AdventureWorks2008', file 'EmpWorkHist' on file 3.--The roll forward start point is now at log sequence number (LSN) 47000000029200001. Additional roll forward past LSN 47000000031500001 is required to complete the restore sequence.--RESTORE LOG successfully processed 0 pages in 0.060 seconds (0.000 MB/sec).
  • 40. Snapshot Creation and Usage/* Author: Susan WhitfieldDate: Friday, November 6, 2009Purpose: To show database snapshot creation and usage.*/--creation of db snapshotUSE masterGOCREATE DATABASE AdventureWorks_snapshot1420 ON(NAME = AdventureWorks_Data,FILENAME= 'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\AdventureWorks_1420.ss')AS SNAPSHOT OF AdventureWorks--insertion of recordUSE AdventureWorksGOINSERT INTO Production.ProductCategory(Name, ModifiedDate) VALUES ('Test Category', GETDATE())--making sure record existsselect * FROM Production.ProductCategoryWHERE Name = 'Test Category'--ProductCategoryID Name rowguidModifiedDate--7 Test Category E597E244-E10E-4222-9F4D-9B14291AC41C 2009-11-06 15:19:07.603--revert back to snapshotUSE masterGORESTORE DATABASE AdventureWorks FROM DATABASE_SNAPSHOT = 'AdventureWorks_snapshot1420'--testing to see if record is still thereUSE AdventureWorksGOselect * FROM Production.ProductCategoryWHERE Name = 'Test Category'--nothing is there with that name
  • 41. Working With Schemas/* Author: Susan WhitfieldDate: Friday, November 6, 2009Purpose: Schema work: Working With Schemas.*/--creating loginUSE masterGOCREATE LOGIN Michael WITH PASSWORD = 'P@$$w0rd'USE Adventureworks2008GOCREATE USER Michael WITH DEFAULT_SCHEMA = PersonGOCREATE TABLE dbo.Person(FirstNamevarchar(25), LastNamevarchar(25), EmailAddressvarchar(50))GOINSERT INTO dbo.Person(FirstName, LastName, EmailAddress) VALUES ('Joe', 'Mugg', '[email protected]')GOGRANT SELECT ON dbo.PersonTO Michael--run from a window logged in under MichaelUSE Adventureworks2008GOSELECT * FROM PersonGO--didnt work because of ambiguity. Need to specify schema.table name
  • 42. Resource Governor Configuration & Usage-- Configure Resource Governor.BEGIN TRANUSE MasterGO-- Create a resource pool that sets the MAX_CPU_PERCENT to 40%. CREATE RESOURCE POOL pMAX_CPU_PERCENT_40 WITH(max_cpu_percent=40)GO--creation of the workload group using resource pool created above.CREATE WORKLOAD GROUP gMAX_CPU_PERCENT_40 USING pMAX_CPU_PERCENT_40GO-- Create a classification function.-- Note that any request that does not get classified goes into -- the 'Default' group.CREATE FUNCTION rgclassifier_MAX_CPU() RETURNS SYSNAME WITH SCHEMABINDINGASBEGIN DECLARE @workload_group_name AS SYSNAME IF (SUSER_NAME() = 'Joe')SET @workload_group_name= 'gMAX_CPU_PERCENT_40'RETURN @workload_group_nameEND;GO-- Register the classifier function with Resource Governor.ALTER RESOURCE GOVERNOR WITH (CLASSIFIER_FUNCTION= dbo.rgclassifier_MAX_CPU);COMMIT TRAN;GO-- Start Resource GovernorALTER RESOURCE GOVERNOR RECONFIGURE;GO
  • 43. Ownership ChainingUSE master GOCREATE LOGIN Joe WITH PASSWORD = 'P@$$w0rd'CREATE LOGIN Tom WITH PASSWORD = 'P@$$w0rd'GOUSE Adventureworks2008 GOCREATE USER JoeCREATE USER TomGOCREATE SCHEMA Marketing AUTHORIZATION Joe GOCREATE TABLE Marketing.PrintCompanies(Name varchar(25), PricePerPagemoney) GOINSERT INTO Marketing.PrintCompanies(Name, PricePerPage) VALUES ('Adventureworks', .25)GRANT CREATE PROCEDURE TO Joe GOGRANT SELECT ON Person.PersonTO Joe GO--below was used in a new query logged in under Joe's loginCREATE PROCEDURE Marketing.uspPrintCompaniesASSET NOCOUNT ONSELECT Name FROM Marketing.PrintCompaniesGOCREATE PROCEDURE Marketing.uspPersonASSET NOCOUNT ONSELECT FirstName, LastNameFROM Person.PersonGOGRANT EXECUTE ON Marketing.uspPrintCompaniesTO TomGRANT EXECUTE ON Marketing.uspPersonTO TomGO--below was used in a new query logged in under Tom's loginUSE AdventureWorks2008 GOExecute Marketing.uspPrintCompanies--worksEXECUTE Marketing.uspPersonMsg 229, Level 14, State 5, Procedure uspPerson, Line 4The SELECT permission was denied on the object 'Person', database 'AdventureWorks2008', schema 'Person'.--Tom does not have access to the Person.Person table. Select permissions were granted to Joe. Trying to do the select on the Person.Persontable will not work because it is outside of his--"ownership chain", meaning that even though Joe granted execute permissions to Tom, that only applies to the execution of the procedure. The owner or a dba or someone with sufficient permissions would need to grant select to Tom as well.
  • 44. Adventure Works RepairDiagram 0High Effort Jobs ReportInvoiced Job SummaryCustomer Billing Summary
  • 46. High Effort Jobs Report--requirements/*The final report ("High Effort Jobs") is intended to show jobs where there is a disproportionately high effort by production staff, measured by total number of items on the job. The data should contain the following fields: Job name Customer name Total number of items Total gross margin Total revenueThe data should be sorted by "Total number of items", highest to lowest, should only show jobs with 5 or more items, and should only show customers in the 'Transactional' or 'BPO' classifications ('Enterprise' classified customers should not be shown).*/SELECT JobName, CustomerName, count(JobItemID) as 'Total number of items',(SUM(Cost) * MarginPercentage) as 'Total gross margin',(SUM(Cost)/(1-MarginPercentage)) as 'Total revenue' FROM Job J JOIN Customer C ON J.CustomerID = C.CustomerID JOIN JobItem JION JI.JobID = J.JobID JOIN Classification CL ON CL.ClassificationID = C.ClassificationID JOIN Item ION I.ItemID = JI.ItemIDWHERE ClassificationNamein('Transactional', 'BPO')GROUP BY JobName, CustomerName, MarginPercentageHAVING COUNT(JI.ItemID) >= 2 --I used 2 to test it out to ensure that it workedORDER BY 'Total Number of Items' DESC
  • 47. Invoiced Job Summary--requirements/*The first report ("Invoiced Job Summary") represents jobs for which we are attempting to collect revenue. The data should contain the following fields: Job name Customer name Total job cost Total gross margin Total job revenue Date invoiced Days since invoice dateThe data should be sorted by "Days since invoice date", highest to lowest, and only show jobs in "Collection" status.*/SELECT JobName, CustomerName, SUM(Cost) as 'Total job cost', (SUM(Cost) * MarginPercentage) as 'Total gross margin', (SUM(Cost)/(1-MarginPercentage)) as 'Total revenue', DATE,(Day(DATE)-DAY(GetDate())) as 'Days since invoice date'FROM Job J JOIN Customer CON J.CustomerID = C.CustomerID JOIN JobItem JION JI.JobID = J.JobID JOIN Item ION JI.ItemID = I.ItemID JOIN Status S ON S.StatusID = J.StatusID JOIN JobStageDate JSD ON JSD.JobID = JI.JobIDWHERE StatusName= 'Collection' AND StageDateTypeID = 4GROUP BY JobName, CustomerName, MarginPercentage, DateORDER BY 'Days since invoice date' DESC
  • 48. Customer Billing Summary Requirements--requirements/*The second report ("Customer Billing Summary") represents an overview of the billing activity for each customer. The data should contain the following fields: Customer name Total number of jobs for this customer which are not in "Closed" status Total revenue for all jobs for this customer which are not in "Closed" status Total number of jobs for this customer which are in "Collection" status Total revenue for all for this customer which are jobs in "Collection" status Total number of jobs for this customer which are in "Closed" status Total revenue for all jobs for this customer which are in "Closed" status Average revenue for all jobs for this customer which are in "Closed" status Total gross margin for all jobs for this customer which are in "Closed" status Average gross margin for all jobs for this customer which are in "Closed" statusThe data should be sorted by "Total revenue for all jobs for this customer which are in 'Closed' status", highest to lowest.*/
  • 49. Customer Billing SummarySELECT CustomerName, (SELECT Count(JobID) FROM Job WHERE StatusID<> 6) as 'Total # jobs not closed', (SELECT (SUM(Cost)/(1-MarginPercentage)) FROM Item I JOIN JobItem JI ON I.ItemID = JI.ItemID JOIN Job J ON J.JobID = JI.JobIDWHERE StatusID<> 6 GROUP BY MarginPercentage) as 'Total revenue for jobs not closed',(SELECT Count(JobID) FROM Job WHERE StatusID= 5) as 'Total # jobs in collection',(SELECT (SUM(Cost)/(1-MarginPercentage)) FROM Item I JOIN JobItem JI ON I.ItemID = JI.ItemID JOIN Job J ON J.JobID = JI.JobIDWHERE StatusID= 5 GROUP BY MarginPercentage) as 'Total revenue for jobs in collection',(SELECT count(JobID) FROM Job WHERE StatusID= 6) as 'Total # jobs closed',(SELECT (SUM(Cost)/(1-MarginPercentage)) FROM Item I JOIN JobItem JI ON I.ItemID = JI.ItemID JOIN Job J ON J.JobID = JI.JobIDWHERE StatusID= 6 GROUP BY MarginPercentage) as 'Total revenue for closed jobs',(SELECT Avg((Cost)/(1-MarginPercentage)) FROM Item I JOIN JobItem JI ON I.ItemID = JI.ItemID JOIN Job J ON J.JobID = JI.JobIDWHERE StatusID= 6 GROUP BY MarginPercentage) as 'Average revenue for closed jobs',(SELECT (SUM(Cost) * MarginPercentage) FROM Item I JOIN JobItem JI ON I.ItemID = JI.ItemID JOIN Job J ON J.JobID = JI.JobIDWHERE StatusID= 6 GROUP BY MarginPercentage) as 'Total gross margin for closed jobs',(SELECT Avg((Cost) * MarginPercentage) FROM Item I JOIN JobItem JI ON I.ItemID = JI.ItemID JOIN Job J ON J.JobID = JI.JobIDWHERE StatusID= 6 GROUP BY MarginPercentage) as 'Average gross margin for closed jobs'FROM Customer WHERE CustomerName= 'Outback Rigs' --choose a customer name from listORDER BY 'Total revenue for closed jobs' DESC
  • 50. Source FilesTable CreationTriggersStored ProcedureUser Defined FunctionSSIS PackagesMini Adventure Works
  • 51. 3 Master FilesProductMaster.CSVShipMethodMaster.CSVVendorMaster.CSVFour Purchase Order Transaction Files PODATA_2001.CSVPODATA_2002.CSVPODATA_2003.CSVPODATA_2004.CSV1 Master File Update UpdatedProducts.CSVSource Files
  • 52. Table CreationProduct TableUSE [MiniAdventureWorksDB]GO/****** Object: Table [dbo].[Product] Script Date: 11/27/2009 16:57:37 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE TABLE [dbo].[Product]( [ProductID] [int] IDENTITY(1,1) NOT NULL, [ProductNumber] [nvarchar](50) NOT NULL, [ProductName] [nvarchar](100) NOT NULL, [ListPrice] [decimal](14, 4) NOT NULL, [DateInserted] [datetime] NOT NULL, [DateModified] [datetime] NOT NULL,CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED ( [ProductID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],CONSTRAINT [ProductNumber_unique] UNIQUE NONCLUSTERED ( [ProductNumber] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]GOALTER TABLE [dbo].[Product] ADD CONSTRAINT [DateInserted_def] DEFAULT (getdate()) FOR [DateInserted]GOALTER TABLE [dbo].[Product] ADD CONSTRAINT [DateModified_def] DEFAULT (getdate()) FOR [DateModified]GO
  • 53. Vendor TableUSE [MiniAdventureWorksDB]GO/****** Object: Table [dbo].[Vendor] Script Date: 11/27/2009 16:58:16 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE TABLE [dbo].[Vendor]( [VendorID] [int] IDENTITY(1,1) NOT NULL, [Name] [nvarchar](100) NOT NULL, [AccountNumber] [nvarchar](50) NOT NULL, [CreditRating] [tinyint] NOT NULL, [DateInserted] [datetime] NOT NULL, [DateModified] [datetime] NOT NULL,CONSTRAINT [PK_Vendor] PRIMARY KEY CLUSTERED ( [VendorID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],CONSTRAINT [AccountNumber_unique] UNIQUE NONCLUSTERED ( [AccountNumber] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]GOALTER TABLE [dbo].[Vendor] ADD CONSTRAINT [VendorDateInserted_def] DEFAULT (getdate()) FOR [DateInserted]GOALTER TABLE [dbo].[Vendor] ADD CONSTRAINT [VendorDateModified_def] DEFAULT (getdate()) FOR [DateModified]GO
  • 54. ShipMethod TableUSE [MiniAdventureWorksDB]GO/****** Object: Table [dbo].[ShipMethod] Script Date: 11/27/2009 16:59:25 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE TABLE [dbo].[ShipMethod]( [ShipMethodID] [int] IDENTITY(1,1) NOT NULL, [Name] [nvarchar](50) NOT NULL, [DateInserted] [datetime] NOT NULL, [DateModified] [datetime] NOT NULL,CONSTRAINT [PK_ShipMethod] PRIMARY KEY CLUSTERED ( [ShipMethodID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],CONSTRAINT [Name_unique] UNIQUE NONCLUSTERED ( [Name] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]GOALTER TABLE [dbo].[ShipMethod] ADD CONSTRAINT [ShipMethodDateInserted_def] DEFAULT (getdate()) FOR [DateInserted]GOALTER TABLE [dbo].[ShipMethod] ADD CONSTRAINT [ShipMethodDateModified_def] DEFAULT (getdate()) FOR [DateModified]GO
  • 55. PurchaseOrderHeader TableUSE [MiniAdventureWorksDB]GO/****** Object: Table [dbo].[PurchaseOrderHeader] Script Date: 11/27/2009 17:00:46 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE TABLE [dbo].[PurchaseOrderHeader]( [PurchaseOrderID] [int] IDENTITY(1,1) NOT NULL, [POHeaderNumber] [nvarchar](20) NOT NULL, [VendorID] [int] NOT NULL, [ShipMethodID] [int] NOT NULL, [OrderDate] [date] NOT NULL, [Freight] [decimal](14, 4) NOT NULL, [TotalDue] [decimal](14, 4) NOT NULL, [DateInserted] [datetime] NOT NULL, [DateModified] [datetime] NOT NULL,CONSTRAINT [PK_PurchaseOrderHeader] PRIMARY KEY CLUSTERED ( [PurchaseOrderID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],CONSTRAINT [PurchaseOrderHeader_unique] UNIQUE NONCLUSTERED ( [POHeaderNumber] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]GOALTER TABLE [dbo].[PurchaseOrderHeader] WITH CHECK ADD CONSTRAINT [FK_PurchaseOrderHeader_Vendor] FOREIGN KEY([VendorID])REFERENCES [dbo].[Vendor]([VendorID])GOALTER TABLE [dbo].[PurchaseOrderHeader] CHECK CONSTRAINT [FK_PurchaseOrderHeader_Vendor]GOALTER TABLE [dbo].[PurchaseOrderHeader] ADD CONSTRAINT [POHDateInserted_def] DEFAULT (getdate()) FOR [DateInserted]GOALTER TABLE [dbo].[PurchaseOrderHeader] ADD CONSTRAINT [POHDateModified_def] DEFAULT (getdate()) FOR [DateModified]GO
  • 56. PurchaseOrderDetail TableUSE [MiniAdventureWorksDB]GO/****** Object: Table [dbo].[PurchaseOrderDetail] Script Date: 11/27/2009 17:01:13 ******/SET ANSI_NULLS ON GOSET QUOTED_IDENTIFIER ON GOSET ANSI_PADDING ON GOCREATE TABLE [dbo].[PurchaseOrderDetail]( [PurchaseOrderID] [int] NOT NULL, [PurchaseOrderDetailID] [int] IDENTITY(1,1) NOT NULL, [ProductID] [int] NOT NULL, [OrderQty] [int] NOT NULL, [UnitPrice] [decimal](14, 4) NOT NULL, [TotalDue] AS ([UnitPrice]*[OrderQty]) PERSISTED, [DateInserted] [datetime] NOT NULL, [DateModified] [datetime] NOT NULL,CONSTRAINT [PK_PurchaseOrderDetail_1] PRIMARY KEY CLUSTERED ( [PurchaseOrderID] ASC, [ProductID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]GOSET ANSI_PADDING OFF GOALTER TABLE [dbo].[PurchaseOrderDetail] WITH CHECK ADD CONSTRAINT [FK_PurchaseOrderDetail_Product] FOREIGN KEY([ProductID])REFERENCES [dbo].[Product]([ProductID]) GOALTER TABLE [dbo].[PurchaseOrderDetail] CHECK CONSTRAINT [FK_PurchaseOrderDetail_Product] GOALTER TABLE [dbo].[PurchaseOrderDetail] WITH CHECK ADD CONSTRAINT [FK_PurchaseOrderDetail_PurchaseOrderHeader] FOREIGN KEY([PurchaseOrderID]) REFERENCES [dbo].[PurchaseOrderHeader]([PurchaseOrderID]) GOALTER TABLE [dbo].[PurchaseOrderDetail] CHECK CONSTRAINT [FK_PurchaseOrderDetail_PurchaseOrderHeader] GOALTER TABLE [dbo].[PurchaseOrderDetail] ADD CONSTRAINT [PODDateInserted_def] DEFAULT (getdate()) FOR [DateInserted] GOALTER TABLE [dbo].[PurchaseOrderDetail] ADD CONSTRAINT [PODDateModified_def] DEFAULT (getdate()) FOR [DateModified] GO
  • 57. TriggersTrigger CreationUSE MiniAdventureWorksDBGOCREATE TRIGGER UpdateProductON dbo.ProductAFTER UPDATE AS BEGIN SET NOCOUNT ON;UPDATE dbo.ProductSET DateModified= GetDate()FROM dbo.Product P JOIN INSERTED ION P.ProductID = I.ProductID JOIN DELETED DON P.ProductID = D.ProductIDWHERE I.ProductName <> D.ProductName ORI.ListPrice <> D.ListPriceENDGOUSE MiniAdventureWorksDBGOCREATE TRIGGER UpdatePurchaseOrderDetailON dbo.PurchaseOrderDetailAFTER UPDATE AS BEGIN SET NOCOUNT ON;UPDATE dbo.PurchaseOrderDetailSET DateModified= GetDate()FROM dbo.PurchaseOrderDetail POD JOIN INSERTED ION POD.PurchaseOrderDetailID = I.PurchaseOrderDetailID JOIN DELETED DON POD.PurchaseOrderDetailID = D.PurchaseOrderDetailIDWHERE I.OrderQty <> D.OrderQty ORI.UnitPrice <> D.UnitPriceENDGO
  • 58. Trigger CreationUSE MiniAdventureWorksDBGOCREATE TRIGGER UpdatePurchaseOrderHeaderON dbo.PurchaseOrderHeaderAFTER UPDATE AS BEGIN SET NOCOUNT ON;UPDATE dbo.PurchaseOrderHeaderSET DateModified= GetDate()FROM dbo.PurchaseOrderHeader POH JOIN INSERTED ION POH.PurchaseOrderID = I.PurchaseOrderID JOIN DELETED DON POH.PurchaseOrderID = D.PurchaseOrderIDWHERE I.OrderDate <> D.OrderDate ORI.Freight <> D.FreightENDGOUSE MiniAdventureWorksDBGOCREATE TRIGGER UpdateShipMethodON dbo.ShipMethodAFTER UPDATE AS BEGIN SET NOCOUNT ON;UPDATE dbo.ShipMethodSET DateModified= GetDate()FROM dbo.ShipMethod SM JOIN INSERTED ION SM.ShipMethodID = I.ShipMethodID JOIN DELETED DON SM.ShipMethodID = D.ShipMethodIDWHERE I.Name <> D.NameENDGO
  • 59. Trigger CreationUSE MiniAdventureWorksDBGOCREATE TRIGGER UpdateVendorON dbo.VendorAFTER UPDATE AS BEGIN SET NOCOUNT ON;UPDATE dbo.VendorSET DateModified= GetDate()FROM dbo.Vendor V JOIN INSERTED ION V.VendorID = I.VendorID JOIN DELETED DON V.VendorID = D.VendorIDWHERE I.Name <> D.Name ORI.CreditRating <> D.CreditRatingENDGO
  • 60. Stored ProcedureStored Procedure CreationUSE MiniAdventureWorksDBGOCREATE procedure InsertOrderHeader @POHeaderNumbernvarchar(50), @VendorIDint, @ShipMethodIDint, @OrderdateDateTime, @Freight decimal(14,2), @TotalDuedecimal (14,2), @PurchaseOrderIDint OUTPUTAS BEGIN INSERT INTO PurchaseOrderHeader(POHeaderNumber, VendorID, ShipMethodID, OrderDate, Freight, TotalDue) VALUES (@POHeaderNumber, @VendorID , @ShipMethodID , @Orderdate , @Freight, @TotalDue)SET @PurchaseOrderID= SCOPE_IDENTITY()ENDGO
  • 61. User Defined FunctionUser Defined FunctionUSE [MiniAdventureWorksDB]GO/****** Object: UserDefinedFunction [dbo].[udf_Top_N_ProductOrdersForVendor] Script Date: 11/30/2009 19:59:19 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE FUNCTION [dbo].[udf_Top_N_ProductOrdersForVendor] (@VendorIDint, @TopCountint)RETURNS @TopProducts TABLE (VendorIDint, ProductIDint, ProductNamevarchar(100), ProductTotalDueDECIMAL(14,2), ProductRankint)AS BEGIN;WITH ProductCTE AS (SELECT TOP (@TopCount) VendorID, ProductID, SUM(POD.TotalDue) AS ProductTotalDue FROM dbo.PurchaseOrderDetail POD join dbo.PurchaseOrderHeader POH ON POD.PurchaseOrderID = POH.PurchaseOrderIDWHERE POH.VendorID = @VendorIDGROUP BY VendorID,ProductIDORDER BY ProductTotalDueDesc)INSERT INTO @TopProducts SELECT VendorID, ProductCTE.ProductID, Product.ProductNameas ProductName, ProductTotalDue, dense_RANK() OVER (ORDER BY ProductTotalDuedesc) as ProductRank FROM ProductCTEJOIN dbo.ProductON ProductCTE.ProductID = Product.ProductIDRETURN ENDGO
  • 74. Stored ProceduresXML Source FilesSSIS PackagesBlockFlix
  • 75. Stored ProceduresInsert MovieUSE [Blockflix]GO/****** Object: StoredProcedure [dbo].[usp_InsertMovie] Script Date: 12/11/2009 11:46:49 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE procedure [dbo].[usp_InsertMovie] @MovieTitlenvarchar(100), @GenreIDint, @RatingIDint, @Year nvarchar(4), @MovieDescriptionnvarchar(max), @MovieIDint OUTPUTAS BEGIN INSERT INTO dbo.Movies(MovieTitle, GenreID, RatingID, Year, MovieDescription) VALUES (@MovieTitle, @GenreID, @RatingID, @Year, @MovieDescription)SET @MovieID= SCOPE_IDENTITY()ENDGO
  • 76. Insert Movie Into InventoryUSE [Blockflix]GO/****** Object: StoredProcedure [dbo].[usp_InsertMovieIntoInventory] Script Date: 12/11/2009 11:48:45 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE procedure [dbo].[usp_InsertMovieIntoInventory] @ProductNamenvarchar(50), @ItemQtyint, @ProductTypeIDint, @MediaTypeIDint, @StatusIDint, @MovieIDintAS BEGIN DECLARE @loopiterationint, @RowQtyint SET @loopiteration= 0SET @RowQty= 1WHILE @loopiteration< @ItemQtyBEGININSERT INTO dbo.MasterInventory(ProductName, QTY, ProductTypeID, MediaTypeID, StatusID, MovieID)VALUES(@ProductName, @RowQty, @ProductTypeID, @MediaTypeID, @StatusID,(SELECT MovieID FROM Movies WHERE MovieTitle= @ProductName))SET @loopiteration= @loopiteration + 1END ENDGO
  • 77. Insert Into CastUSE [Blockflix] GO/****** Object: StoredProcedure [dbo].[usp_InsertIntoCast] Script Date: 12/11/2009 11:49:52 ******/SET ANSI_NULLS ON GOSET QUOTED_IDENTIFIER ON GOCREATE procedure [dbo].[usp_InsertIntoCast] @MovieIDint, @Director1ID int, @Director2ID int, @Actor1ID int, @Actor2ID int, @Actor3ID int, @Producer1ID int, @Producer2ID intAS BEGIN--directors: JobTypeID for director is 2 --director1INSERT INTO dbo.Cast(MovieID, PersonID, JobTypeID) VALUES (@MovieID, @Director1ID, 2)--if director2 is not null then it will insert into the Cast table IF @Director2ID IS NOT NULL AND @Director2ID <> 0BEGININSERT INTO dbo.Cast(MovieID, PersonID, JobTypeID) VALUES (@MovieID, @Director2ID, 2)END ELSE--actors: JobTypeID for actors is 1 --actor1INSERT INTO dbo.Cast(MovieID, PersonID, JobTypeID) VALUES (@MovieID, @Actor1ID, 1)--actor2INSERT INTO dbo.Cast(MovieID, PersonID, JobTypeID) VALUES (@MovieID, @Actor2ID, 1)--actor3INSERT INTO dbo.Cast(MovieID, PersonID, JobTypeID) VALUES (@MovieID, @Actor3ID, 1)--producers: JobTypeID for producers is 3 --producer1INSERT INTO dbo.Cast(MovieID, PersonID, JobTypeID) VALUES (@MovieID, @Producer1ID, 3)--producer2: testing to see if producer2 is not null IF @Producer2ID IS NOT NULL AND @Producer2ID <> 0BEGININSERT INTO dbo.Cast(MovieID, PersonID, JobTypeID) VALUES (@MovieID, @Producer2ID, 3)END ENDGO
  • 78. Insert ProductsUSE [Blockflix]GO/****** Object: StoredProcedure [dbo].[usp_InsertProducts] Script Date: 12/11/2009 11:50:09 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE procedure [dbo].[usp_InsertProducts] @ProductNamenvarchar(50), @ItemQtyint, @ProductTypeIDint, @MediaTypeIDint, @StatusIDintAS BEGIN--local variable declarationDECLARE @loopiterationint, @RowQtyintSET @loopiteration= 0SET @RowQty= 1--testing to see if the product type is video game (2)IF @ProductTypeID= 2BEGIN --loop will insert multiple rows for video games so that --each copy of a video game will have a unique SKU #WHILE @loopiteration< @ItemQtyBEGININSERT INTO dbo.MasterInventory(ProductName, QTY, ProductTypeID, MediaTypeID, StatusID)VALUES (@ProductName, @RowQty, @ProductTypeID, @MediaTypeID, @StatusID)SET @loopiteration= @loopiteration + 1ENDENDELSE INSERT INTO dbo.MasterInventory(ProductName, QTY, ProductTypeID, MediaTypeID, StatusID)VALUES (@ProductName, @ItemQty, @ProductTypeID, @MediaTypeID, @StatusID)ENDGO
  • 82. XML Source File For Movies
  • 83. XML Source File For Products
  • 93. Database Design DiagramInstructor Results Report Examples (SSRS)Evaluation Application