2. Introduction Good 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
5. Project Specifications Create 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 Creation USE [JungleBooks] GO /****** Object: Table [dbo].[Orders] Script Date: 10/07/2009 00:01:16 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE 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 ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE 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. GO SET ANSI_PADDING OFF GO /****** Object: Table [dbo].[Customers] Script Date: 10/07/2009 00:01:16 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE 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] GO SET ANSI_PADDING OFF GO /****** Object: Table [dbo].[Books] Script Date: 10/07/2009 00:01:16 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE 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] GO SET ANSI_PADDING OFF GO /****** Object: Table [dbo].[BookAuthors] Script Date: 10/07/2009 00:01:16 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE 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] GO SET ANSI_PADDING OFF GO /****** Object: Table [dbo].[Authors] Script Date: 10/07/2009 00:01:16 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE 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] GO SET ANSI_PADDING OFF GO
12.
13. Problem 1 The 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. Statement1 Write a query that displays ISBN, title, publisher having books that are priced less than $15, ordered by the title. T-SQL1 SELECT ISBN, Title, Publisher FROM Books WHEREUnitPrice< 15 ORDERBY Title Problem 2 The 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. Statement2 Write a query that displays author names having the name ‘pet’, displayed in alphabetical order. Use heading: ‘Search Results’. T-SQL2 SELECT Name AS'Search Results' FROM Authors WHERE Name like'%pet%' ORDERBY Name
14. Problem 3 The 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’. Statement3 Write 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-SQL3 SELECTOrderID'Order#',CustomerID'Cust ID',OrderDate'Order Date' FROM Orders WHERECustomerIDbetween 6 and 15 ORDERBYCustomerID Problem 4 The 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’. Statement4 Write 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-SQL4 SELECTO.OrderID'Order ID',O.CustomerID'Cust ID', Name 'Customer',SUM(QuantityOrdered)'# of items' FROM Customers C JOIN Orders O ON C.CustomerID=O.CustomerIDJOINOrderItems OI ON O.OrderID=OI.OrderID GROUPBYO.OrderID,O.CustomerID, Name ORDERBYSUM(QuantityOrdered)DESC
15. Problem 5 The 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. Statement5 Write a query to display publishers, books they publish and the ISBN for each book, displaying in alphabetical order T-SQL5 SELECT Publisher, Title, ISBN FROM Books ORDERBY Publisher, Title Problem 6 The 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’. Statement6 Write 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-SQL6 SELECTCustomerID'ID', Name 'Name',ExpiryDate'Expires' FROM Customers WHEREExpiryDate < Getdate()+30 ORDERBYExpiryDateDESC
16. Problem 7 The 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. Statement7 Write a query to display the author name, book title and ISBN, displayed in order by author name and title. T-SQL7 SELECT Name, Title, BA.ISBN FROM Authors A JOINBookAuthors BA ON A.AuthorID=BA.AuthorIDJOIN Books B ON B.ISBN = BA.ISBN ORDERBY Name, Title Problem 8 The 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’. Statement8 Write 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-SQL8 SELECT OI.ISBN 'ISBN', Title 'Title',SUM(QuantityOrdered)'Total' FROMOrderItems OI JOIN Books B ON OI.ISBN = B.ISBN GROUPBY OI.ISBN, Title HAVINGSUM(QuantityOrdered)>= 5 ORDERBYSUM(QuantityOrdered)DESC
17. Problem 9 The 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. Statement9 Write 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-SQL9 SELECTCustomerID'ID', Name 'Name',Address'CurrentAddress', CardType'CardType',CardNumber'CardNumber',ExpiryDate'Expires' FROM Customers WHERECardNumberlike'%7889' ORDERBYCustomerID Problem 10 Write 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. Statement10 Write a query to display firstname, middleinitial, lastname, street, city, state and zip. Should be displayed in order by the lastname and firstname. T-SQL10 SELECT (firstname+' '+isnull(middleinitial+' ','')+lastname) AS'Name', street, city,state, zip FROM adult a JOIN member m ON a.member_no=m.member_no ORDERBYlastname,firstname
18. Problem 11 Write 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. Statement11 Write 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-SQL11 SELECTc.isbn,copy_no,on_loan, title, translation, cover FROM title t JOIN item iON t.title_no=i.title_noJOIN copy c ON c.isbn=i.isbn WHERE(c.ISBN= 500 ORc.ISBN= 1000) AND on_loan='N' ORDERBY cover Problem 12 Write 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. Statement12 Write 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-SQL12 SELECTfirstname,middleinitial,lastname,m.member_no,isbn,log_date FROM member m LEFTOUTERJOIN reservation r ON m.member_no=r.member_no WHEREm.member_noin(250, 341, 1675) ORDERBYm.member_no,log_date
19. Problem 13 Using 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. Statement13 Write 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+', '+firstname as'name','Adult'as'Adult / Juvenile' FROM adult a JOIN reservation r ON a.member_no=r.member_noJOIN copy c ON r.isbn=c.isbnJOIN title t ON c.title_no=t.title_noJOIN member m ON m.member_no=a.member_no WHEREc.ISBN= 288 UNION SELECTc.isbn, title,j.member_no,lastname+', '+firstname as'name','Juvenile'as'Adult / Juvenile' FROM juvenile j JOIN reservation r ON j.member_no=r.member_noJOIN copy c ON r.isbn=c.isbnJOIN title t ON c.title_no=t.title_noJOIN member m ON m.member_no=j.member_no WHEREc.ISBN= 288 ORDERBY'name'
20. Problem 14 Write 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) Statement14 Write 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'= CASE WHENEXISTS(SELECTmember_no FROM juvenile j WHEREj.member_no=m.member_no) THEN'Juvenile' ELSE'Adult' END FROM member m JOIN reservation r ON m.member_no=r.member_noJOIN item iON i.isbn=r.isbnJOIN title t ON t.title_no=i.title_no WHEREi.isbn= 288 ORDERBY'name' Output14 Viewing 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 15 Write 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. Statement15 Write 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-SQL15 CREATETABLE #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, title FROM loan l JOIN title t ON l.title_no=t.title_noJOIN member m ON m.member_no=l.member_no WHEREdue_date<GETDATE()
22. Problem 16 Write 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. Statement16 Write 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-SQL16 SELECTmember_no,fullname,COUNT(due_date)AS'# Overdue' FROM #overdue GROUPBYmember_no,fullname ORDERBY'# Overdue'DESC,fullname Problem 17 Write 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. Statement17 Write 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-SQL17 SELECTlh.member_no,firstname,lastname,SUM(fine_paid) AS'Paid Fines' FROMloanhistlhJOIN member m ON lh.member_no=m.member_no WHEREfine_paidISNOTNULL GROUPBYlh.member_no,firstname,lastname ORDERBY'Paid Fines'DESC,lh.member_no
23. Problem 18 Write 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. Statement18 Write a query that displays ISBN, title, and total (calculated column). T-SQL18 SELECTr.isbn, title,Count(member_no)AS'Total' FROM reservation r JOIN item iON r.isbn=i.isbnJOIN title t ON t.title_no=i.title_no GROUPBYr.isbn, title
24. Diagram 0 Views Triggers Stored procedures (code snippets of a few sp’s) XML shred snippet Piggy Bank 2 Project
25.
26. Views /****** Object: View [dbo].[v_CurrentMonthStatement] Script Date: 10/17/2009 00:43:55 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE VIEW [dbo].[v_CurrentMonthStatement] WITH SCHEMABINDING AS SELECT CustomerFirstName, CustomerMiddleInitial, CustomerLastName, Street, City, State, ZipCode, TransactionID, AccountID, TransactionTypeID, T.CustomerID, TransactionDate, TransactionAmount, NewBalance FROM dbo.Transactions T JOIN dbo.Customer C ON T.CustomerID = C.CustomerID GO /****** Object: View [dbo].[v_GetBalance] Script Date: 10/17/2009 00:43:55 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE VIEW [dbo].[v_GetBalance] WITH SCHEMABINDING AS SELECT TransactionID, AccountID, T.TransactionTypeID, CustomerID, TransactionDate, TransactionAmount, TransactionTypeName, NewBalance FROM dbo.Transactions T JOIN dbo.TransactionType TT ON T.TransactionTypeID = TT.TransactionTypeID GO
27. /****** Object: View [dbo].[v_GetHistoricalStatement] Script Date: 10/17/2009 00:43:55 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE VIEW [dbo].[v_GetHistoricalStatement] WITH SCHEMABINDING AS SELECT CustomerFirstName, CustomerMiddleInitial, CustomerLastName, Street, City, State, ZipCode, TransactionID, AccountID, TransactionTypeID, T.CustomerID, TransactionDate, TransactionAmount, NewBalance FROM dbo.Transactions T JOIN dbo.Customer C ON T.CustomerID = C.CustomerID GO /****** Object: View [dbo].[v_GetTransactions] Script Date: 10/17/2009 00:43:55 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE VIEW [dbo].[v_GetTransactions] WITH SCHEMABINDING AS SELECT TransactionID, AccountID, TransactionTypeID, CustomerID, TransactionDate, TransactionAmount, NewBalance FROM dbo.Transactions GO
28. /****** Object: View [dbo].[v_ListCustomerAccounts] Script Date: 10/17/2009 00:43:55 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE VIEW [dbo].[v_ListCustomerAccounts] WITH SCHEMABINDING AS SELECT CustomerFirstName, CustomerMiddleInitial, CustomerLastName, Street, City, State, ZipCode, CA.AccountID, CA.CustomerID FROM dbo.CustomerAccount CA JOIN dbo.Customer C ON C.CustomerID = CA.CustomerID GO
29. Triggers USE [PiggyBankWk4] GO /****** Object: DdlTrigger [NoUnwantedChanges] Script Date: 10/17/2009 00:50:48 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE 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 ON GO SET QUOTED_IDENTIFIER ON GO CREATE 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.' ROLLBACK GO
38. Backup/Restore Disaster Recovery Mini-Simulation Snapshot Creation and Usage Working With Schemas Resource Governor Configuration & Usage Ownership Chaining DBA Practical’s
39. Backup & Restore: Disaster Recovery Mini-Simulation --primary file group backup BACKUP DATABASE [AdventureWorks2008] FILEGROUP = N'PRIMARY' TO [Adventureworks2008Backups] WITH NOFORMAT, INIT, NAME = N'AdventureWorks2008-Full Primary Filegroup Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10 GO --secondary file group backup BACKUP DATABASE [AdventureWorks2008] FILEGROUP = N'EmployeeWorkHistoryFG' TO [Adventureworks2008Backups] WITH NOFORMAT, NOINIT, NAME = N'AdventureWorks2008-Full Secondary Filegroup Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10 GO --Update the ClockOutTime for the only record in the EmployeeWorkHistoryTable. The current value is NULL USE AdventureWorks2008 GO UPDATE HumanResources.EmployeeWorkHistorySET ClockOutTime= GETDATE() WHERE BusinessEntityID= 1 --log file backup BACKUP LOG [AdventureWorks2008] TO [Adventureworks2008Backups] WITH NOFORMAT, NOINIT, NAME = N'AdventureWorks2008-Transaction Log Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10 GO --Simulate accidental deletion of a table by executing the following statements: DROP TABLE HumanResources.EmployeeWorkHistory --secondary filegroup with norecovery, the transaction log backup with RECOVERY RESTORE HEADERONLY FROM Adventureworks2008Backups --AdventureWorks2008-Full Primary FilegroupBackup,AdventureWorks2008-Full Secondary FilegroupBackup, AdventureWorks2008-Transaction Log Backup RESTORE FILELISTONLY FROM Adventureworks2008Backups --AdventureWorks2008_Data , EmpWorkHist, AdventureWorks2008_Log, -FileStreamDocuments Use master GO RESTORE 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 Whitfield Date: Friday, November 6, 2009 Purpose: To show database snapshot creation and usage. */ --creation of db snapshot USE master GO CREATE DATABASE AdventureWorks_snapshot1420 ON (NAME = AdventureWorks_Data, FILENAME= 'C:rogram Filesicrosoft SQL ServerSSQL10.MSSQLSERVERSSQLATAdventureWorks_1420.ss') AS SNAPSHOT OF AdventureWorks --insertion of record USE AdventureWorks GO INSERT INTO Production.ProductCategory(Name, ModifiedDate) VALUES ('Test Category', GETDATE()) --making sure record exists select * 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 snapshot USE master GO RESTORE DATABASE AdventureWorks FROM DATABASE_SNAPSHOT = 'AdventureWorks_snapshot1420' --testing to see if record is still there USE AdventureWorks GO select * FROM Production.ProductCategoryWHERE Name = 'Test Category' --nothing is there with that name
41. Working With Schemas /* Author: Susan Whitfield Date: Friday, November 6, 2009 Purpose: Schema work: Working With Schemas. */ --creating login USE master GO CREATE LOGIN Michael WITH PASSWORD = 'P@$$w0rd' USE Adventureworks2008 GO CREATE USER Michael WITH DEFAULT_SCHEMA = Person GO CREATE TABLE dbo.Person(FirstNamevarchar(25), LastNamevarchar(25), EmailAddressvarchar(50)) GO INSERT INTO dbo.Person(FirstName, LastName, EmailAddress) VALUES ('Joe', 'Mugg', 'jm@mugg.com') GO GRANT SELECT ON dbo.PersonTO Michael --run from a window logged in under Michael USE Adventureworks2008 GO SELECT * FROM Person GO --didnt work because of ambiguity. Need to specify schema.table name
42. Resource Governor Configuration & Usage -- Configure Resource Governor. BEGIN TRAN USE Master GO -- 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_40 GO -- 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 SCHEMABINDING AS BEGIN DECLARE @workload_group_name AS SYSNAME IF (SUSER_NAME() = 'Joe') SET @workload_group_name= 'gMAX_CPU_PERCENT_40' RETURN @workload_group_name END; GO -- Register the classifier function with Resource Governor. ALTER RESOURCE GOVERNOR WITH (CLASSIFIER_FUNCTION= dbo.rgclassifier_MAX_CPU); COMMIT TRAN; GO -- Start Resource Governor ALTER RESOURCE GOVERNOR RECONFIGURE; GO
43. Ownership Chaining USE master GO CREATE LOGIN Joe WITH PASSWORD = 'P@$$w0rd' CREATE LOGIN Tom WITH PASSWORD = 'P@$$w0rd' GO USE Adventureworks2008 GO CREATE USER Joe CREATE USER Tom GO CREATE SCHEMA Marketing AUTHORIZATION Joe GO CREATE TABLE Marketing.PrintCompanies(Name varchar(25), PricePerPagemoney) GO INSERT INTO Marketing.PrintCompanies(Name, PricePerPage) VALUES ('Adventureworks', .25) GRANT CREATE PROCEDURE TO Joe GO GRANT SELECT ON Person.PersonTO Joe GO --below was used in a new query logged in under Joe's login CREATE PROCEDURE Marketing.uspPrintCompanies AS SET NOCOUNT ON SELECT Name FROM Marketing.PrintCompanies GO CREATE PROCEDURE Marketing.uspPerson AS SET NOCOUNT ON SELECT FirstName, LastNameFROM Person.Person GO GRANT EXECUTE ON Marketing.uspPrintCompaniesTO Tom GRANT EXECUTE ON Marketing.uspPersonTO Tom GO --below was used in a new query logged in under Tom's login USE AdventureWorks2008 GO Execute Marketing.uspPrintCompanies --works EXECUTE Marketing.uspPerson Msg 229, Level 14, State 5, Procedure uspPerson, Line 4 The 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 Repair Diagram 0 High Effort Jobs Report Invoiced Job Summary Customer Billing Summary
45.
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 revenue The 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 JI ON JI.JobID = J.JobID JOIN Classification CL ON CL.ClassificationID = C.ClassificationID JOIN Item I ON I.ItemID = JI.ItemID WHERE ClassificationNamein('Transactional', 'BPO') GROUP BY JobName, CustomerName, MarginPercentage HAVING COUNT(JI.ItemID) >= 2 --I used 2 to test it out to ensure that it worked ORDER 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 date The 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 C ON J.CustomerID = C.CustomerID JOIN JobItem JI ON JI.JobID = J.JobID JOIN Item I ON JI.ItemID = I.ItemID JOIN Status S ON S.StatusID = J.StatusID JOIN JobStageDate JSD ON JSD.JobID = JI.JobID WHERE StatusName= 'Collection' AND StageDateTypeID = 4 GROUP BY JobName, CustomerName, MarginPercentage, Date ORDER 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" status The data should be sorted by "Total revenue for all jobs for this customer which are in 'Closed' status", highest to lowest. */
49. Customer Billing Summary SELECT 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.JobID WHERE 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.JobID WHERE 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.JobID WHERE 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.JobID WHERE 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.JobID WHERE 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.JobID WHERE StatusID= 6 GROUP BY MarginPercentage) as 'Average gross margin for closed jobs' FROM Customer WHERE CustomerName= 'Outback Rigs' --choose a customer name from list ORDER BY 'Total revenue for closed jobs' DESC
50. Source Files Table Creation Triggers Stored Procedure User Defined Function SSIS Packages Mini Adventure Works
52. Table Creation Product Table USE [MiniAdventureWorksDB] GO /****** Object: Table [dbo].[Product] Script Date: 11/27/2009 16:57:37 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE 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] GO ALTER TABLE [dbo].[Product] ADD CONSTRAINT [DateInserted_def] DEFAULT (getdate()) FOR [DateInserted] GO ALTER TABLE [dbo].[Product] ADD CONSTRAINT [DateModified_def] DEFAULT (getdate()) FOR [DateModified] GO
53. Vendor Table USE [MiniAdventureWorksDB] GO /****** Object: Table [dbo].[Vendor] Script Date: 11/27/2009 16:58:16 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE 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] GO ALTER TABLE [dbo].[Vendor] ADD CONSTRAINT [VendorDateInserted_def] DEFAULT (getdate()) FOR [DateInserted] GO ALTER TABLE [dbo].[Vendor] ADD CONSTRAINT [VendorDateModified_def] DEFAULT (getdate()) FOR [DateModified] GO
54. ShipMethod Table USE [MiniAdventureWorksDB] GO /****** Object: Table [dbo].[ShipMethod] Script Date: 11/27/2009 16:59:25 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE 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] GO ALTER TABLE [dbo].[ShipMethod] ADD CONSTRAINT [ShipMethodDateInserted_def] DEFAULT (getdate()) FOR [DateInserted] GO ALTER TABLE [dbo].[ShipMethod] ADD CONSTRAINT [ShipMethodDateModified_def] DEFAULT (getdate()) FOR [DateModified] GO
55. PurchaseOrderHeader Table USE [MiniAdventureWorksDB] GO /****** Object: Table [dbo].[PurchaseOrderHeader] Script Date: 11/27/2009 17:00:46 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE 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] GO ALTER TABLE [dbo].[PurchaseOrderHeader] WITH CHECK ADD CONSTRAINT [FK_PurchaseOrderHeader_Vendor] FOREIGN KEY([VendorID]) REFERENCES [dbo].[Vendor]([VendorID]) GO ALTER TABLE [dbo].[PurchaseOrderHeader] CHECK CONSTRAINT [FK_PurchaseOrderHeader_Vendor] GO ALTER TABLE [dbo].[PurchaseOrderHeader] ADD CONSTRAINT [POHDateInserted_def] DEFAULT (getdate()) FOR [DateInserted] GO ALTER TABLE [dbo].[PurchaseOrderHeader] ADD CONSTRAINT [POHDateModified_def] DEFAULT (getdate()) FOR [DateModified] GO
56. PurchaseOrderDetail Table USE [MiniAdventureWorksDB] GO /****** Object: Table [dbo].[PurchaseOrderDetail] Script Date: 11/27/2009 17:01:13 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE 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] GO SET ANSI_PADDING OFF GO ALTER TABLE [dbo].[PurchaseOrderDetail] WITH CHECK ADD CONSTRAINT [FK_PurchaseOrderDetail_Product] FOREIGN KEY([ProductID]) REFERENCES [dbo].[Product]([ProductID]) GO ALTER TABLE [dbo].[PurchaseOrderDetail] CHECK CONSTRAINT [FK_PurchaseOrderDetail_Product] GO ALTER TABLE [dbo].[PurchaseOrderDetail] WITH CHECK ADD CONSTRAINT [FK_PurchaseOrderDetail_PurchaseOrderHeader] FOREIGN KEY([PurchaseOrderID]) REFERENCES [dbo].[PurchaseOrderHeader]([PurchaseOrderID]) GO ALTER TABLE [dbo].[PurchaseOrderDetail] CHECK CONSTRAINT [FK_PurchaseOrderDetail_PurchaseOrderHeader] GO ALTER TABLE [dbo].[PurchaseOrderDetail] ADD CONSTRAINT [PODDateInserted_def] DEFAULT (getdate()) FOR [DateInserted] GO ALTER TABLE [dbo].[PurchaseOrderDetail] ADD CONSTRAINT [PODDateModified_def] DEFAULT (getdate()) FOR [DateModified] GO
57. Triggers Trigger Creation USE MiniAdventureWorksDB GO CREATE TRIGGER UpdateProduct ON dbo.Product AFTER UPDATE AS BEGIN SET NOCOUNT ON; UPDATE dbo.Product SET DateModified= GetDate() FROM dbo.Product P JOIN INSERTED I ON P.ProductID = I.ProductID JOIN DELETED D ON P.ProductID = D.ProductID WHERE I.ProductName <> D.ProductName OR I.ListPrice <> D.ListPrice END GO USE MiniAdventureWorksDB GO CREATE TRIGGER UpdatePurchaseOrderDetail ON dbo.PurchaseOrderDetail AFTER UPDATE AS BEGIN SET NOCOUNT ON; UPDATE dbo.PurchaseOrderDetail SET DateModified= GetDate() FROM dbo.PurchaseOrderDetail POD JOIN INSERTED I ON POD.PurchaseOrderDetailID = I.PurchaseOrderDetailID JOIN DELETED D ON POD.PurchaseOrderDetailID = D.PurchaseOrderDetailID WHERE I.OrderQty <> D.OrderQty OR I.UnitPrice <> D.UnitPrice END GO
58. Trigger Creation USE MiniAdventureWorksDB GO CREATE TRIGGER UpdatePurchaseOrderHeader ON dbo.PurchaseOrderHeader AFTER UPDATE AS BEGIN SET NOCOUNT ON; UPDATE dbo.PurchaseOrderHeader SET DateModified= GetDate() FROM dbo.PurchaseOrderHeader POH JOIN INSERTED I ON POH.PurchaseOrderID = I.PurchaseOrderID JOIN DELETED D ON POH.PurchaseOrderID = D.PurchaseOrderID WHERE I.OrderDate <> D.OrderDate OR I.Freight <> D.Freight END GO USE MiniAdventureWorksDB GO CREATE TRIGGER UpdateShipMethod ON dbo.ShipMethod AFTER UPDATE AS BEGIN SET NOCOUNT ON; UPDATE dbo.ShipMethod SET DateModified= GetDate() FROM dbo.ShipMethod SM JOIN INSERTED I ON SM.ShipMethodID = I.ShipMethodID JOIN DELETED D ON SM.ShipMethodID = D.ShipMethodID WHERE I.Name <> D.Name END GO
59. Trigger Creation USE MiniAdventureWorksDB GO CREATE TRIGGER UpdateVendor ON dbo.Vendor AFTER UPDATE AS BEGIN SET NOCOUNT ON; UPDATE dbo.Vendor SET DateModified= GetDate() FROM dbo.Vendor V JOIN INSERTED I ON V.VendorID = I.VendorID JOIN DELETED D ON V.VendorID = D.VendorID WHERE I.Name <> D.Name OR I.CreditRating <> D.CreditRating END GO
60. Stored Procedure Stored Procedure Creation USE MiniAdventureWorksDB GO CREATE procedure InsertOrderHeader @POHeaderNumbernvarchar(50), @VendorIDint, @ShipMethodIDint, @OrderdateDateTime, @Freight decimal(14,2), @TotalDuedecimal (14,2), @PurchaseOrderIDint OUTPUT AS BEGIN INSERT INTO PurchaseOrderHeader (POHeaderNumber, VendorID, ShipMethodID, OrderDate, Freight, TotalDue) VALUES (@POHeaderNumber, @VendorID , @ShipMethodID , @Orderdate , @Freight, @TotalDue) SET @PurchaseOrderID= SCOPE_IDENTITY() END GO
61. User Defined Function User Defined Function USE [MiniAdventureWorksDB] GO /****** Object: UserDefinedFunction [dbo].[udf_Top_N_ProductOrdersForVendor] Script Date: 11/30/2009 19:59:19 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE 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.PurchaseOrderID WHERE POH.VendorID = @VendorID GROUP BY VendorID,ProductID ORDER BY ProductTotalDueDesc) INSERT INTO @TopProducts SELECT VendorID, ProductCTE.ProductID, Product.ProductNameas ProductName, ProductTotalDue, dense_RANK() OVER (ORDER BY ProductTotalDuedesc) as ProductRank FROM ProductCTEJOIN dbo.Product ON ProductCTE.ProductID = Product.ProductID RETURN END GO
75. Stored Procedures Insert Movie USE [Blockflix] GO /****** Object: StoredProcedure [dbo].[usp_InsertMovie] Script Date: 12/11/2009 11:46:49 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE procedure [dbo].[usp_InsertMovie] @MovieTitlenvarchar(100), @GenreIDint, @RatingIDint, @Year nvarchar(4), @MovieDescriptionnvarchar(max), @MovieIDint OUTPUT AS BEGIN INSERT INTO dbo.Movies (MovieTitle, GenreID, RatingID, Year, MovieDescription) VALUES (@MovieTitle, @GenreID, @RatingID, @Year, @MovieDescription) SET @MovieID= SCOPE_IDENTITY() END GO
76. Insert Movie Into Inventory USE [Blockflix] GO /****** Object: StoredProcedure [dbo].[usp_InsertMovieIntoInventory] Script Date: 12/11/2009 11:48:45 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE procedure [dbo].[usp_InsertMovieIntoInventory] @ProductNamenvarchar(50), @ItemQtyint, @ProductTypeIDint, @MediaTypeIDint, @StatusIDint, @MovieIDint AS BEGIN DECLARE @loopiterationint, @RowQtyint SET @loopiteration= 0 SET @RowQty= 1 WHILE @loopiteration< @ItemQty BEGIN INSERT 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 + 1 END END GO
77. Insert Into Cast USE [Blockflix] GO /****** Object: StoredProcedure [dbo].[usp_InsertIntoCast] Script Date: 12/11/2009 11:49:52 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE procedure [dbo].[usp_InsertIntoCast] @MovieIDint, @Director1ID int, @Director2ID int, @Actor1ID int, @Actor2ID int, @Actor3ID int, @Producer1ID int, @Producer2ID int AS BEGIN --directors: JobTypeID for director is 2 --director1 INSERT 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 <> 0 BEGIN INSERT INTO dbo.Cast(MovieID, PersonID, JobTypeID) VALUES (@MovieID, @Director2ID, 2) END ELSE --actors: JobTypeID for actors is 1 --actor1 INSERT INTO dbo.Cast(MovieID, PersonID, JobTypeID) VALUES (@MovieID, @Actor1ID, 1) --actor2 INSERT INTO dbo.Cast(MovieID, PersonID, JobTypeID) VALUES (@MovieID, @Actor2ID, 1) --actor3 INSERT INTO dbo.Cast(MovieID, PersonID, JobTypeID) VALUES (@MovieID, @Actor3ID, 1) --producers: JobTypeID for producers is 3 --producer1 INSERT 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 <> 0 BEGIN INSERT INTO dbo.Cast(MovieID, PersonID, JobTypeID) VALUES (@MovieID, @Producer2ID, 3) END END GO
78. Insert Products USE [Blockflix] GO /****** Object: StoredProcedure [dbo].[usp_InsertProducts] Script Date: 12/11/2009 11:50:09 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE procedure [dbo].[usp_InsertProducts] @ProductNamenvarchar(50), @ItemQtyint, @ProductTypeIDint, @MediaTypeIDint, @StatusIDint AS BEGIN --local variable declaration DECLARE @loopiterationint, @RowQtyint SET @loopiteration= 0 SET @RowQty= 1 --testing to see if the product type is video game (2) IF @ProductTypeID= 2 BEGIN --loop will insert multiple rows for video games so that --each copy of a video game will have a unique SKU # WHILE @loopiteration< @ItemQty BEGIN INSERT INTO dbo.MasterInventory(ProductName, QTY, ProductTypeID, MediaTypeID, StatusID) VALUES (@ProductName, @RowQty, @ProductTypeID, @MediaTypeID, @StatusID) SET @loopiteration= @loopiteration + 1 END END ELSE INSERT INTO dbo.MasterInventory(ProductName, QTY, ProductTypeID, MediaTypeID, StatusID) VALUES (@ProductName, @ItemQty, @ProductTypeID, @MediaTypeID, @StatusID) END GO