Professional Documents
Culture Documents
Chapter 2
How to use SQL Server Management Studio and other development tools
Before you start the exercises
Before you start these exercises, you need to install SQL Server and the SQL Server Management Studio. The procedures for doing both of these tasks are provided in appendix A. In addition, youll need to get the Exercise Starts directory from your instructor. This directory contains some script files that you need to do these exercises.
Exercises
In these exercises, youll use SQL Server Management Studio to create the MyGuitarShop database, to review the tables in the MyGuitarShop database, and to enter SQL statements and run them against this database.
9. Delete the e at the end of ProductName and run the statement again. Note the error number and the description of the error. 10. Open another Query Editor window by clicking the New Query button. Then, enter and run this statement:
SELECT COUNT(*) AS NumberOfProducts FROM Products
Chapter 3
Sort the result set by last name in ascending sequence. Return only the contacts whose last name begins with letters from M to Z. 3. Write a SELECT statement that returns these column names and data from the Products table: ProductName ListPrice DateAdded The ProductName column The ListPrice column The DateAdded column
Return only the rows with a list price thats greater than 500 and less than 2000. Sort the result set in descending sequence by the DateAdded column. 4. Write a SELECT statement that returns these column names and data from the Products table: ProductName ListPrice DiscountPercent DiscountAmount DiscountPrice The ProductName column The ListPrice column The DiscountPercent column A column thats calculated from the previous two columns A column thats calculated from the previous three columns
5. Write a SELECT statement that returns these column names and data from the OrderItems table: ItemID ItemPrice DiscountAmount Quantity PriceTotal DiscountTotal ItemTotal The ItemID column The ItemPrice column The DiscountAmount column The Quantity column A column thats calculated by multiplying the item price with the quantity A column thats calculated by multiplying the discount amount with the quantity A column thats calculated by subtracting the discount amount from the item price and then multiplying by the quantity
Only return rows where the ItemTotal is greater than 500. Sort the result set by item total in descending sequence.
Return only the rows where the ShipDate column contains a null value. 7. Write a SELECT statement without a FROM clause that creates a row with these columns: Price TaxRate TaxAmount Total 100 (dollars) .07 (7 percent) The price multiplied by the tax The price plus tax
To calculate the fourth column, add the expressions you used for the first and third columns.
Chapter 4
Return one row for each category that has never been used. Hint: Use an outer join and only return rows where the ProductID column contains a null value.
7. Use the UNION operator to generate a result set consisting of three columns from the Orders table: ShipStatus OrderID OrderDate A calculated column that contains a value of SHIPPED or NOT SHIPPED The OrderID column The OrderDate column
If the order has a value in the ShipDate column, the ShipStatus column should contain a value of SHIPPED. Otherwise, it should contain a value of NOT SHIPPED. Sort the final result set by OrderDate.
Chapter 5
6. Write a SELECT statement that answers this question: What is the total amount ordered for each product? Return these columns: The product name from the Products table The total amount for each product in the OrderItems table (Hint: You can calculate the total amount by subtracting the discount amount from the item price and then multiplying it by the quantity) Use the WITH ROLLUP operator to include a row that gives the grand total. 7. Write a SELECT statement that answers this question: Which customers have ordered more than one product? Return these columns: The email address from the Customers table The count of distinct products from the customers orders
Chapter 6
2. Write a SELECT statement that answers this question: Which products have a list price thats greater than the average list price for all products? Return the ProductName and ListPrice columns for each product. Sort the results by the ListPrice column in descending sequence. 3. Write a SELECT statement that returns the CategoryName column from the Categories table. Return one row for each category that has never been assigned to any product in the Products table. To do that, use a subquery introduced with the NOT EXISTS operator. 4. Write a SELECT statement that returns three columns: EmailAddress, OrderID, and the order total for each customer. To do this, you can group the result set by the EmailAddress and OrderID columns. In addition, you must calculate the order total from the columns in the OrderItems table. Write a second SELECT statement that uses the first SELECT statement in its FROM clause. The main query should return two columns: the customers email address and the largest order for that customer. To do this, you can group the result set by the EmailAddress column. 5. Write a SELECT statement that returns the name and discount percent of each product that has a unique discount percent. In other words, dont include products that have the same discount percent as another product. Sort the results by the ProductName column. 6. Use a correlated subquery to return one row per customer, representing the customers oldest order (the one with the earliest date). Each row should include these three columns: EmailAddress, OrderID, and OrderDate.
10
Chapter 7
Code the INSERT statement so SQL Server automatically generates the value for the CategoryID column. 2. Write an UPDATE statement that modifies the row you just added to the Categories table. This statement should change the ProductName column to Woodwinds, and it should use the CategoryID column to identify the row. 3. Write a DELETE statement that deletes the row you added to the Categories table in exercise 1. This statement should use the CategoryID column to identify the row. 4. Write an INSERT statement that adds this row to the Products table: ProductID: CategoryID: ProductCode: ProductName: Description: ListPrice: DiscountPercent: DateAdded: The next automatically generated ID 4 dgx_640 Yamaha DGX 640 88-Key Digital Piano Long description to come. 799.99 0 Todays date/time.
Use a column list for this statement. 5. Write an UPDATE statement that modifies the product you added in exercise 4. This statement should change the DiscountPercent column from 0% to 35%. 6. Write a DELETE statement that deletes the row in the Categories table that has an ID of 4. When you execute this statement, it will produce an error since the category has related rows in the Products table. To fix that, precede the DELETE statement with another DELETE statement that deletes all products in this category. 7. Write an INSERT statement that adds this row to the Customers table: EmailAddress: Password: FirstName: LastName: rick@raven.com (empty string) Rick Raven
Use a column list for this statement. 8. Write an UPDATE statement that modifies the Customers table. Change the password column to secret for the customer with an email address of rick@raven.com.
11
9. Write an UPDATE statement that modifies the Customers table. Change the password column to reset for every customer in the table. 10. Open the script named CreateMyGuitarShop.sql thats in the Exercise Starts directory. Then, run this script. That should restore the data thats in the database.
12
Chapter 8
13
Chapter 9
14
Chapter 10
15
Chapter 11
How to create and maintain databases, tables, and sequences with SQL statements
Exercises
1. Write a script that adds an index to the MyGuitarShop database for the zip code field in the Customers table. 2. Write a script that implements the following design in a database named MyWebDB:
In the Downloads table, the UserID and ProductID columns are the foreign keys. Include a statement to drop the database if it already exists. Include statements to create and select the database. Include any indexes that you think are necessary. 3. Write a script that adds rows to the database that you created in exercise 2. Add two rows to the Users and Products tables. Add three rows to the Downloads table: one row for user 1 and product 2; one for user 2 and product 1; and one for user 2 and product 2. Use the GETDATE function to insert the current date and time into the DownloadDate column. Write a SELECT statement that joins the three tables and retrieves the data from these tables like this:
Sort the results by the email address in descending order and the product name in ascending order. 4. Write an ALTER TABLE statement that adds two new columns to the Products table created in exercise 2. Add one column for product price that provides for three digits to the left of the decimal point and two to the right. This column should have a default value of 9.99. Add one column for the date and time that the product was added to the database.
16
5. Write an ALTER TABLE statement that modifies the Users table created in exercise 2 so the FirstName column cannot store null values and can store a maximum of 20 characters. Code an UPDATE statement that attempts to insert a null value into this column. It should fail due to the not null constraint. Code another UPDATE statement that attempts to insert a first name thats longer than 20 characters. It should fail due to the length of the column.
17
Chapter 12
3. Define the UserID column in the Users table, the ProductsID column in the Products table, and the DownloadID column in the Downloads table as primary keys and identity columns. 4. In the Downloads table, set the UserID and ProductID column as the foreign keys. 5. Define the columns so none of them allow null values. 6. Use the Management Studio to create indexes for the foreign keys in the Downloads table. 7. Use the Management Studio to create a unique index on the EmailAddress and ProductName columns and a regular index on the DownloadDate column.
18
Chapter 13
19
Chapter 14
4. Write a script that attempts to insert a new category named Guitars into the Categories table. If the insert is successful, the script should display this message:
SUCCESS: Record was inserted.
If the update is unsuccessful, the script should display a message something like this:
FAILURE: Record was not inserted. Error 2627: Violation of UNIQUE KEY constraint 'UQ__Categori__8517B2E0A87CE853'. Cannot insert duplicate key in object 'dbo.Categories'. The duplicate key value is (Guitars).
20
Chapter 15
21
6. Create a trigger named Products_UPDATE that checks the new value for the DiscountPercent column of the Products table. This trigger should raise an appropriate error if the discount percent is greater than 100 or less than 0. If the new discount percent is between 0 and 1, this trigger should modify the new discount percent by multiplying it by 100. That way, a discount percent of .2 becomes 20. Test this trigger with an appropriate UPDATE statement. 7. Create a trigger named Products_INSERT that inserts the current date for the DateAdded column of the Products table if the value for that column is null. Test this trigger with an appropriate INSERT statement. 8. Create a table named ProductsAudit. This table should have all columns of the Products table, except the Description column. Also, it should have an AuditID column for its primary key, and the DateAdded column should be changed to DateUpdated. Create a trigger named Products_UPDATE. This trigger should insert the old data about the product into the ProductsAudit table after the row is updated. Then, test this trigger with an appropriate UPDATE statement.
22
Chapter 16
2. Write a script to declare and use a cursor for the following SELECT statement. Use a WHILE loop to fetch each row in the result set. Omit the INTO clause to fetch directly to the Results tab.
SELECT LastName, AVG(ShipAmount) AS ShipAmountAvg FROM Customers JOIN Orders ON Customers.CustomerID = Orders.CustomerID GROUP BY LastName;
3. Modify the solution to exercise 1 to fetch each row into a set of local variables. Use the PRINT statement to return each row in the format Name, $0.00 to the Messages tab.
23
Chapter 17
Here, the @@IDENTITY variable is used to get the order ID value thats automatically generated when the first INSERT statement inserts an order. If these statements execute successfully, commit the changes. Otherwise, roll back the changes.
24
Chapter 18
25
Chapter 19