student lab manual advance t-sql for sql server

25
Student Lab Manual Advance T-SQL for SQL Server 1

Upload: others

Post on 12-Sep-2021

15 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Student Lab Manual Advance T-SQL for SQL Server

Student Lab Manual

Advance T-SQL for SQL Server

1

Page 2: Student Lab Manual Advance T-SQL for SQL Server

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

Page 3: Student Lab Manual Advance T-SQL for SQL Server

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

Page 4: Student Lab Manual Advance T-SQL for SQL Server

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

Page 5: Student Lab Manual Advance T-SQL for SQL Server

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

Page 6: Student Lab Manual Advance T-SQL for SQL Server

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

Page 7: Student Lab Manual Advance T-SQL for SQL Server

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 nullBirth Name (max 100 characters) not nullBirth Date (month name day, year) not nullBirth Location (max 100 characters) not nullDeath Date (month name day, year) may be nullAge integer may be nullDeath Location (max 100 characters) may be nullDescription (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

Page 8: Student Lab Manual Advance T-SQL for SQL Server

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

Page 9: Student Lab Manual Advance T-SQL for SQL Server

Student Lab Manual

Advance T-SQL for SQL Server

Solutions

9

Page 10: Student Lab Manual Advance T-SQL for SQL Server

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 → ContactManagerID → 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,LoginIDTitle

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

Page 11: Student Lab Manual Advance T-SQL for SQL Server

Lab 2: Reading Create Table DDL Statements

Please answer the following questions:

1. Which field(s) have a CONSTRAINT attached to them?

SalariedFlagVacationHoursSickLeaveHoursCurrentFlagrowguidModifiedDateEmployeeID

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

Page 12: Student Lab Manual Advance T-SQL for SQL Server

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.mdfmodellog.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

Page 13: Student Lab Manual Advance T-SQL for SQL Server

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

Page 14: Student Lab Manual Advance T-SQL for SQL Server

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

Page 15: Student Lab Manual Advance T-SQL for SQL Server

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.Sourceadd constraint UQ_Stage_nameUnique (stage_name)

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

alter table Humor.Sourceadd constraint CN_Agecheck (age > 0)

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

alter table Humor.Sourceadd constraint CN_Description_Defaultdefault 'A Famous Person' for description

15

Page 16: Student Lab Manual Advance T-SQL for SQL Server

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.EmployeeWHERE 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 ABFROM Sales.Currency;

16

Page 17: Student Lab Manual Advance T-SQL for SQL Server

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 LoginFROM HumanResources.EmployeeWHERE 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.ProductGROUP BY ProductSubCategoryIDHAVING COUNT(ProductSubCategoryID) > 20ORDER 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.EmployeeGROUP BY Title, GenderWITH ROLLUP;

17

Page 18: Student Lab Manual Advance T-SQL for SQL Server

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, SubTotalFROM Purchasing.Vendor INNER JOIN Purchasing.PurchaseOrderHeaderOn Vendor.VendorID = PurchaseOrderHeader.VendorIDORDER 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.ProductON Production.ProductSubCategory.ProductSubCategoryID = Product.ProductSubCategoryIDLEFT OUTER JOIN Sales.SalesOrderDetailON Product.ProductID = Sales.SalesOrderDetail.ProductIDWHERE SalesOrderDetail.ProductID IS NOT NULL;

18

Page 19: Student Lab Manual Advance T-SQL for SQL Server

Student Lab Manual

Advance T-SQL for SQL Server

Challenge Labs

19

Page 20: Student Lab Manual Advance T-SQL for SQL Server

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

Page 21: Student Lab Manual Advance T-SQL for SQL Server

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

Page 22: Student Lab Manual Advance T-SQL for SQL Server

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 InsensitiveAS – Accent Sensitive

See: http://msdn.microsoft.com/en-us/library/aa258233(SQL.80).aspx

22

Page 23: Student Lab Manual Advance T-SQL for SQL Server

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_AIGO

USE [HumorSystem]GO

EXEC sp_changedbowner 'sa'GO

23

Page 24: Student Lab Manual Advance T-SQL for SQL Server

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;gocreate schema Humor;goalter schema Humor transfer dbo.Source;go

24

Page 25: Student Lab Manual Advance T-SQL for SQL Server

Lab 6 Challenge:

Verify the constraints were created.

exec sp_helpconstraint 'Humor.Source'go

25