Student Lab Manual Advance T-SQL for SQL Server

20 downloads 149 Views 100KB Size Report
This lab manual is based on the SQL Server 2005 AdventureWorks sample ... each lab in class and provide example solutions to the challenge assignments.
Student Lab Manual Advance T-SQL for SQL Server

1

Introduction: This lab manual is based on the SQL Server 2005 AdventureWorks sample database. Assignments will use the objects from the AdventureWorks database and a new Database to be designed in class, and the labs will use the Microsoft SQL Server management Studio as a learning platform. Each lab will feature a basic assignment and optionally a challenge assignment. Your Instructor will review each lab in class and provide example solutions to the challenge assignments. Learning SQL is a hand-on experience, you are encouraged to explore beyond these basic assignments and ask questions in class. Before you proceed beyond a specific lab, please ensure you understand the topics being explored and all your questions have been answered. Enjoy and have fun.

2

Lab 1: Learning to explore a Database Table in SQL Server Management Studio For the Employee table in the AdventureWorks sample database, please answer the following questions: 1. What is the Schema the Employee table belongs in?

2. What is the Primary Key for the Employee table?

3. Are there any Foreign Keys within the Employee table, if so what tables do these keys reference?

4. Which field(s) of the Employee table may be null?

5. What are the valid entries in the MartialStatus column?

6. Which field(s) hold variable length data?

7. What is the Default Value for the SalariedFlag? And what does it mean?

Lab 1 Challenge: Examine the dEmplyee Trigger and answer the following question: What happens when you delete an Employee?

3

Lab 2: Reading Create Table DDL Statements Please follow these steps: • • • • •

Expand the Tables list for the AdventureWorks database Right click the Employee Table Select Script Table As... Select CREATE To... Select New Query Editor Window

Examine the results. Please answer the following questions: 1. Which field(s) have a CONSTRAINT attached to them? 2. What is the prefix for a CHECK CONSTRAINT? 3. What is the prefix for a DEFAULT CONSTRAINT? 4. What is the stored procedure used to add a description for a field? 5. What command is executed to run a T-SQL command in a script?

Lab 2 Challenge: What are the Dependencies for the StateProvince table?

4

Lab 3: Examining the Model Database Please follow these steps: • • • •

Expand the Databases section Expand the System Databases section Select Model Right click and select Properties

Examine the results. Please answer the following questions: 1. What is the Initial Size? 2. What is the Autogrowth? 3. What is the Maximum Size? 4. What is the Current Size? 5. What is the name of the Database file, and the Log file? 6. What is the Path to the files? 7. Who is the Owner? 8. Does the Log file have the same Autogrowth parameter?

Lab 3 Challenge: Is the Model Database Case Sensitive or Case Insensitive?

5

Lab 4: Create Database We are going to create a new database for this class, it will contain a number of Humor tables. Please right click the Databases selection and select New Database... Please create this new database with the following options: Name: HumorSystem Owner: sa Initial Size: 2 MB (must be as large as the Model database) Autogrowth: By 1 MB, restricted growth to 10 MB (data) By 10 percent, unrestricted growth (log) Collation: Latin1_General_CS_AI

Lab 4 Challenge: Delete the HumorSystem Database, and re-create it using an SQL script.

6

Lab 5: Create Table You are going to create a table within the HumorSystem database. This table will hold biographical data for a series of quotes we will store in the database. The table has the following columns: Table name: Source Contents: An autogenerated number (identity) number as primary key Stage Name (max 25 characters) not null Birth Name (max 100 characters) not null Birth Date (month name day, year) not null Birth Location (max 100 characters) not null Death Date (month name day, year) may be null Age integer may be null Death Location (max 100 characters) may be null Description (max 500 characters) Using the New Table... wizard create this table Hint: Try right clicking on a column to see what options are available

Lab 5 Challenge: Can you create a new Schema named Humor and alter the Source table so it belonged to the new schema?

7

Lab 6: Constraints For the Source table in the HumorSystem database, please alter the table to apply these changes: 1. Stage Names must be Unique.

2. A Check Constraint on the age field, the age must be positive;

3. Add a Default Constraint to the Description, that provides “A Famous Person”.

Lab 6 Challenge: Verify the constraints were created.

8

Student Lab Manual Advance T-SQL for SQL Server Solutions

9

Lab 1: Learning to explore a Database Table in SQL Server Management Studio For the Employee table in the AdventureWorks sample database, please answer the following questions: 1. What is the Schema the Employee table belongs in? HumanResources 2. What is the Primary Key for the Employee table? EmployeeID 3. Are there any Foreign Keys within the Employee table, if so what tables do these keys reference? ContactID → Contact ManagerID → Employee 4. Which field(s) of the Employee table may be null? ManagerID 5. What are the valid entries in the MartialStatus column? M = Married, S = Single 6. Which field(s) hold variable length data? NationalIDNumber, LoginID Title 7. What is the Default Value for the SalariedFlag? And what does it mean? ((1)) → Job classification. 0 = Hourly, not exempt from collective bargaining. 1 = Salaried, exempt from collective bargaining.

10

Lab 2: Reading Create Table DDL Statements Please answer the following questions: 1. Which field(s) have a CONSTRAINT attached to them? SalariedFlag VacationHours SickLeaveHours CurrentFlag rowguid ModifiedDate EmployeeID 2. What is the prefix for a CHECK CONSTRAINT? CF_ 3. What is the prefix for a DEFAULT CONSTRAINT? DF_ 4. What is the stored procedure used to add a description for a field? sys.sp_addextendedproperty 5. What command is executed to run a T-SQL command in a script? go

11

Lab 3: Examining the Model Database Please answer the following questions: 1. What is the Initial Size? 2 MB (database) 1 MB (log) 2. What is the Autogrowth? By 1 MB (database) By 10 percent (log) 3. What is the Maximum Size? unrestricted 4. What is the Current Size? 1.69 MB 5. What is the name of the Database file, and the Log file? model.mdf modellog.ldf 6. What is the Path to the files? c:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA 7. Who is the Owner? sa 8. Does the Log file have the same Autogrowth parameter? No, it grows by 10 percent

12

Lab 4: Create Database We are going to create a new database for this class, it will contain a number of Humor tables. Please right click the Databases selection and select New Database... Please create this new database with the following options: Name: HumorSystem Owner: sa Initial Size: 2 MB (must be as large as the Model database) Autogrowth: By 1 MB, restricted growth to 10 MB (data) By 10 percent, unrestricted growth (log) Collation: Latin1_General_CS_AI Use the wizard options to build this database

13

Lab 5: Create Table You are going to create a table within the HumorSystem database. This table will hold biographical data for a series of quotes we will store in the database. The table has the following columns: CREATE TABLE [dbo].[Source] ( [number] [int] IDENTITY(1,1) NOT NULL, [stage_name] [nvarchar](25) NOT NULL, [birth_name] [nvarchar](100) NOT NULL, [birth_date] [datetime] NOT NULL, [birth_location] [nvarchar](100) NOT NULL, [death_date] [datetime] NULL, [age] [int] NULL, [death_location] [nvarchar](100) NULL, [description] [nvarchar](500) NULL, CONSTRAINT [PK_Source] PRIMARY KEY CLUSTERED ( [number] ASC ) ON [PRIMARY]

14

Lab 6: Constraints For the Source table in the HumorSystem database, please alter the table to apply these changes: 1. Stage Names must be Unique. alter table Humor.Source add constraint UQ_Stage_name Unique (stage_name) 2. A Check Constraint on the age field, the age must be positive; alter table Humor.Source add constraint CN_Age check (age > 0) 3. Add a Default Constraint to the Description, that provides “A Famous Person”. alter table Humor.Source add constraint CN_Description_Default default 'A Famous Person' for description

15

Lab 7: The SQL Functions These question refer to several tables in the AdventureWorks sample database, please create the following queries: 1. The average commission percent for the SalesPerson table. SELECT AVG(CommissionPct) FROM Sales.SalesPerson; 2. A count of all Male Employees; SELECT COUNT(*) FROM HumanResources.Employee WHERE Gender = 'M'; 3. The highest List Price of any Product. SELECT MAX(ListPrice) FROM Production.Product; 4. The length of all Descriptions in the ProductDescription table. SELECT LEN(Description) FROM Production.ProductDescription; 5. The Currency Code and the first 3 letters of the Currency Name as 'AB'. SELECT CurrencyCode, LEFT(Name, 3) AS AB FROM Sales.Currency;

16

Lab 8: The Aggregation and Grouping These question refer to several tables in the AdventureWorks sample database, please create the following queries: 1. List the Title, Gender, and Lowest Login Id for each group of Employees grouped by the following titles: “Buyer', 'Recruiter' or 'Stocker'. SELECT Title, MIN(LoginID) AS Login FROM HumanResources.Employee WHERE Title IN('Buyer', 'Recruiter' , 'Stocker') GROUP BY Title; 2. List Product Sub Category IDs from the Product table, include only those subcategories that occur more than 20 times. In addition to the ID also return the first product name in alphabetical order and the highest price for products in this subcategory. SELECT ProductSubCategoryID, MIN(Name) AS Name, MAX(ListPrice) FROM Production.Product GROUP BY ProductSubCategoryID HAVING COUNT(ProductSubCategoryID) > 20 ORDER BY Name; 3. Provide a list of Employee Titles and Genders from the Employee table. For each title, include the average vacation hours for all employees of each gender. Also provide an additional subtotal for each title that includes the average vacation hours for all employees of that title. SELECT Title, Gender, AVG(VacationHours) FROM HumanResources.Employee GROUP BY Title, Gender WITH ROLLUP;

17

Lab 9: The Multi-Table Queries These question refer to several tables in the AdventureWorks sample database, please create the following queries: 1. Create a list of Vendors and the subtotals amounts for their purchase orders, sorted by vendor name. Please include vendor name, and the subtotal amount for all vendors who have purchase orders recorded in the PurchaseOrderHeader table. SELECT Name, SubTotal FROM Purchasing.Vendor INNER JOIN Purchasing.PurchaseOrderHeader On Vendor.VendorID = PurchaseOrderHeader.VendorID ORDER BY Name; 2. Provide a list of all Product subcategories and related products that do not have any sales order detail records. Please provide two columns including the SubCategory Name and the Product Name. SELECT ProductSubCategory.Name AS SubCategory, Product.Name AS ProductName FROM Production.ProductSubCategory INNER JOIN Production.Product ON Production.ProductSubCategory.ProductSubCategoryID = Product.ProductSubCategoryID LEFT OUTER JOIN Sales.SalesOrderDetail ON Product.ProductID = Sales.SalesOrderDetail.ProductID WHERE SalesOrderDetail.ProductID IS NOT NULL;

18

Student Lab Manual Advance T-SQL for SQL Server Challenge Labs

19

Lab 1 Challenge: Examine the dEmplyee Trigger and answer the following question: What happens when you delete an Employee? RAISERROR (N'Employees cannot be deleted. They can only be marked as not current.', -- Message 10, -- Severity. 1); -- State.

20

Lab 2 Challenge: What are the Dependencies for the StateProvince table? Objects that depend on StateProvince • Address • SaleTaxRate • vStateProvinceCountryRegion Objects the StateProvince depend on • CountryRegion • Flag • Name • SalesTerritory

21

Lab 3 Challenge: Is the Model Database Case Sensitive or Case Insensitive? Case Insensitive:; Note the Collation as: SQL_Latin1_General_CP1_CI_AS. CI – Case Insensitive AS – Accent Sensitive See: http://msdn.microsoft.com/en-us/library/aa258233(SQL.80).aspx

22

Lab 4 Challenge: Delete the HumorSystem Database, and re-create it using an SQL script. USE [master] GO CREATE DATABASE [HumorSystem] ON ( NAME = N'HumorSystem', FILENAME = N'c:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\HumorSystem.mdf' , SIZE = 2048KB , MAXSIZE = 10240KB , FILEGROWTH = 1024KB ) LOG ON ( NAME = N'HumorSystem_log', FILENAME = N'c:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\HumorSystem_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%) COLLATE Latin1_General_CS_AI GO USE [HumorSystem] GO EXEC sp_changedbowner 'sa' GO

23

Lab 5 Challenge: Can you create a new Schema named Humor and alter the Source table so it belonged to the new schema? use HumorSystem; go create schema Humor; go alter schema Humor transfer dbo.Source; go

24

Lab 6 Challenge: Verify the constraints were created. exec sp_helpconstraint 'Humor.Source' go

25