Sql Portfolio(March 31)
Transcript of Sql Portfolio(March 31)
Table of ContentsTable of ContentsWhat is SetFocus 3RDBMS Concepts 4
Writing Queries using MS SQL Server 2008 T SQL 7
Implementing a Microsoft SQL Server Database 13
SSIS – SQL Server Integration Services
What is SetFocus?What is SetFocus?
• The SetFocus SQL Master’s Program is an intensive, hands–on, The SetFocus SQL Master’s Program is an intensive, hands–on, project oriented program allowing knowledge and valuable project oriented program allowing knowledge and valuable experience putting the SQL skill set to use in a simulated work experience putting the SQL skill set to use in a simulated work environment.environment.
• Over 300 hours of in-depth hands on experience focused on SQL. Over 300 hours of in-depth hands on experience focused on SQL.
• SetFocus projects are real world projects that are distributed just SetFocus projects are real world projects that are distributed just as I would receive in a position. I received project specifications and as I would receive in a position. I received project specifications and was expected to identify best courses of action with deadlines set was expected to identify best courses of action with deadlines set for completion.for completion.
RDBMS ConceptsRDBMS Concepts
Normalization - What and WhyWe normalize data into a computerized and logical model by
converting the data from its real world or physical model.
• Displaying data to a user in a familiar form alleviates confusion when describing how the system will perform
• In order to get the best performance from a database data needs to be organized. This helps it to function at its optimal efficiency.
• Keys/constraints are needed to keep the Data Integrity and assist in the separation of duties amongst database programmers and administrators.
Database Objects - WhyData retrieval needs to be as efficient as possible. Databases needs
more tools to meet demands placed on them.
• Views – is a highly utilized tool in a SQL database and can combine data from two or more tables. It also can utilize tables, functions, and even other views to produce results.
• Functions – performs specific tasks by taking one or more arguments and return a result as a SQL object.
•Stored Procedures – are complete T SQL programs that may consist of SQL statements and functions.
• Triggers – is a special form of a stored procedure and is automatically run when an event such as INSERT, UPDATE, DELETE occurs in a table. Similar to Schemabinding.
Writing Queries using MS Writing Queries using MS SQL Server 2008 T-SQLSQL Server 2008 T-SQL
Single Table Queries, Views and Stored Procedures, Joins, Unions, and Advanced Queries
Single Table Queries
• 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.
Use JungleBooksDECLARE @txtUnitPrice intSET @txtUnitPrice = 15SELECT B.ISBN as ISBN, B.Title as Title, B.Publisher as PublisherFROM dbo.Books as BWHERE B.UnitPrice < @txtUnitPriceORDER BY b.Title
• 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’. Use JungleBooksDeclare @txtlDStart as int , @txtlDEnd as intSet @txtlDStart = 6Set @txtlDEnd = 15Select OrderDate as [Order Date], CustomerID as [Cust ID], OrderID as [Order #]From dbo.OrdersWhere OrderID BETWEEN @txtlDStart AND @txtlDEndOrder by [Cust ID]
Advanced Single Table Query with Results
•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’.
Use JungleBooks
Declare @Expiration datetimeSet @Expiration = DATEADD(day, 30, Getdate())Select CustomerID as [ID], Name as [Name], Day(ExpiryDate)as [Expires]From dbo.CustomersWhere Day(ExpiryDate) < @ExpirationOrder by Expires DESC
Advanced Queries Using Joins
• Write and execute a query on the Title, Item and Copy tables that returns the ISBN, copy_no, on_loan, title, translation, 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.Use library
Declare @onloan char(10) = 'N'Select Distinct I.isbn, C.copy_no, C.on_loan, T.title, I.translation,I.cover From dbo.title as T Join dbo.item as I on T.title_no = I.title_no Join dbo.copy as C on C.title_no = I.title_noWhere I.isbn IN(500, 1000) and C.on_loan = @onloanOrder by I.cover, C.on_loan
• Retrieve the member’s full name and member_no from the Member table and the ISBN and log_date values fromthe 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.Use library
Select M.firstname + N' ' + COALESCE(M.middleinitial, + N'') + N' ' + M.lastname as [Full Name], M.member_no, R.isbn, R.log_date From dbo.reservation as R Right Join dbo.member as M on R.member_no = M.member_noWhere M.member_no IN(250, 341, 1675)Order by M.member_no, R.log_date
Join/Union Query with ResultsJoin/Union Query with Results
Use libraryDeclare @reserved# int = 288,@txtAdult As Char(10) = 'Adult‘, @txtJuvenile As Char(10) = 'Juvenile'Select R.isbn as ISBN, T.title as Title, R.member_no as [Member No.], @txtAdult as 'Member Type' , M.lastname + N', ' + (M.middleinitial, + N'') + N' ' + M.firstname as FullNameFrom dbo.item as IJoin dbo.reservation as ROn I.isbn = R.isbnJoin dbo.member as MOn R.member_no = M.member_noJoin dbo.adult as AOn M.member_no = A.member_noJoin dbo.title as TOn I.title_no = T.title_noWhere R.isbn = @reserved#
Union AllSelect R.isbn, T.title, M.member_no, @txtJuvenile, M.lastname + N', ' + M.middleinitial, + N'') + N' ' + M.firstname as FullNameFrom dbo.item as IJoin dbo.reservation as ROn I.isbn = R.isbnJoin dbo.member as MOn R.member_no = M.member_noJoin juvenile as JOn M.member_no = J.member_noJoin dbo.title as TOn I.title_no = T.title_noWhere R.isbn = @reserved#Order by FullName
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.
View and Stored ProcedureView and Stored Procedure
Create a view in the TSQLFundamentals2008 database that returns the orderid, day of the week (Spelled Out), the name of the month (spelled Out), the day of the month, and the year based on the order date
in the sales.orders table
USE TSQLFundamentals2008Create VIEW [dbo].[MyDateView]ASSELECT orderid, DATENAME(dw, orderdate) AS [Day Name], DATENAME(MM, orderdate) AS [Month Name], DAY(orderdate) AS [Day Of Month], YEAR(orderdate) AS [Order Year]FROM Sales.Orders;
Create a stored procedure in the TSQLFundamentals2008 database that returns the order ID, the order date, the ship country. The employee full name, and the company name. The ship country should be a
parameter and the result set should be sorted by order date from most recent to oldest.
USE [TSQLFundamentals2008]GO SET ANSI_NULLS ON GOSET QUOTED_IDENTIFIER ON GOCREATE PROCEDURE [dbo].[usp_OrdersByCountry] @ShipCountry as VarChar(25)= 'USA'ASBEGINSET NOCOUNT ON;Select O.orderid, O.orderdate, O.shipcountry, E.firstname + N' ' + E.lastname As Employee, C.companynameFrom Sales.Orders As OInner Join Sales.Customers As C On C.custid = O.custidInner Join HR.Employees As E On E.empid = O.empidWhere O.shipcountry = @ShipCountryOrder By O.orderdate DescEND
Edited to fit format of page
Implementing a Microsoft Implementing a Microsoft SQL Server Database SQL Server Database
Piggy Bank Piggy BankPiggy Bank is a database produced by SetFocus students
ranging from the CREATE DATABASE script to all stored procedures, Functions, Views, and Triggers required so
that banking transactions may be done in a clean efficient manner. Deposits, withdrawals, bank statements, etc. are just a few of the requirements considered in this project.
Add Customer Stored ProcedureAdd Customer Stored Procedure
CREATE proc [dbo].[sp_addnewcustomer]
@CustomerFirstName nvarchar(20) = null
, @CustomerLastName nvarchar(30) = null
, @CustomerMiddleInitial nvarchar(1) = null
, @Street nvarchar(50) = null
, @City nvarchar(20) = null
, @State char(2) = null
, @ZipCode char(10) = null
, @Email nvarchar(30) = null
, @HomePhone char(12) = null
, @WorkPhone char(12) = null
, @CellPhone char(12) = null
, @CustomerID int OUTPUT
as
BEGIN TRY
If @CustomerLastName is null
Begin
RAISERROR('first name cant be null',11,1)
End
BEGIN TRAN
INSERT INTO [PiggyBank].[dbo].[Customer]
([CustomerFirstName] ,[CustomerLastName] ,[CustomerMiddleInitial] ,[Street] ,[City],[State] ,[ZipCode] ,[Email] ,[HomePhone])
VALUES
( @CustomerFirstName, @CustomerLastName, @CustomerMiddleInitial, @Street, @City, @State, @ZipCode, @Email, @HomePhone)
SET @CustomerID = SCOPE_IDENTITY()
Return @CustomerID
NOTE: Missing Code (Rollback/Catch
Transaction) - Edited to fit format of
page
Deposit into Bank AccountDeposit into Bank Account
CREATE PROCEDURE [dbo].[sp_Deposit]
@AccountID int = null
,@CustomerID int = null
,@TransactionAmount money = null
,@TransactionID int OUTPUT
AS
BEGIN TRY
DECLARE @NewBalance money, @CurrentBalance money
SET @NewBalance = (SELECT CurrentBalance
FROM dbo.Account
WHERE AccountID = @AccountID) + @TransactionAmount
BEGIN TRAN
IF NOT EXISTS (SELECT AccountID
FROM dbo.Account
WHERE AccountID = @AccountID)
BEGIN
RAISERROR ('Account does not exist',3,1)
END
IF NOT EXISTS (SELECT CustomerID
FROM dbo.Customer
WHERE CustomerID = @CustomerID)
BEGIN
RAISERROR('Customer does not exist',3,1)
END
BEGIN
INSERT INTO [PiggyBank].[dbo].[Transactions]
([AccountID],[TransactionTypeID],[CustomerID],[TransactionDate],[TransactionAmount],[NewBalance])
VALUES
(@AccountID,2,@CustomerID,GETDATE(),@TransactionAmount,@NewBalance)
UPDATE dbo.Account
SET CurrentBalance = @NewBalance
WHERE AccountID = @AccountID
SELECT @TransactionID = SCOPE_IDENTITY()
Deposit of $2000 to AccountID 100001
(row number 2)
Triggers in the DatabaseTriggers in the Database
CREATE TRIGGER trgDropTables
ON DATABASE FOR DROP_TABLE
AS
BEGIN TRAN
RAISERROR('TABLES ARE SET SO THAT THEY MAY NOT BE DROPPED FROM SYSTEM', 5,1)
ROLLBACK
GO
CREATE TRIGGER trgAlterTables
ON DATABASE FOR ALTER_TABLE
AS
BEGIN TRAN
RAISERROR('TABLES ARE SET SO THAT THEY MAY NOT BE ALTERED', 5,1)
ROLLBACK
GO
CREATE TRIGGER trgDropViews
ON DATABASE FOR DROP_VIEW
AS
BEGIN TRAN
RAISERROR('VIEWS ARE SET SO THAT THEY MAY NOT BE DROPPED FROM SYSTEM', 5,1)
ROLLBACK
GO
CREATE TRIGGER dbo.trgNODELETTRANSACTION
ON dbo.Transactions
AFTER DELETE
AS
BEGIN TRAN
RAISERROR('TRANSACTIONS CANNOT BE DELETED', 5,1)
ROLLBACK
GO
SSIS – SQL Server SSIS – SQL Server Integration ServicesIntegration Services
SSRS – SQL Server SSRS – SQL Server Reporting ServicesReporting Services