Appendix A - Writing SQL Statements and Stored Procedures
Appendix A - Writing SQL Statements and Stored Procedures
Overview 1
Lesson: Retrieving Data from a Database 2
Lesson: Combining Data from Multiple
Tables 11
Lesson: Modifying Data 17
Lesson: Using Stored Procedures 29
Review 33
Lab A: Best Practices for Writing SQL
Statements and Stored Procedures 36
Appendix A: Overview of SQL Statements and Stored Procedures 1
Overview
Introduction This appendix describes the main features of the Structured Query
Language (SQL). SQL is a standard language for retrieving data from a
relational database and for modifying the data in the database. You use SQL
statements in Microsoft® ADO.NET applications, to retrieve and modify data in
the database.
In this appendix, you will learn how to write SQL statements to retrieve data
from a single table or from multiple tables.
Objectives After completing this appendix, you will be able to:
Retrieve data from a database.
Join data in different tables.
Insert, update, and delete data in a database.
Create and call stored procedures.
2 Appendix A: Overview of SQL Statements and Stored Procedures
Introduction In this lesson, you will learn how to retrieve data from a relational database.
This lesson shows how to use the SELECT statement to retrieve data from a
database. The lesson also shows how to filter data by using the WHERE clause,
and describes performance considerations that affect retrieving data.
Lesson objectives After completing this lesson, you will be able to:
Describe the structure of relational databases.
Retrieve data from a database by using the SELECT statement.
Filter data by using search conditions by using the WHERE clause.
Appendix A: Overview of SQL Statements and Stored Procedures 3
suppliers
suppliers
supplierid
supplierid companyname
companyname address
address city
city
11 Exotic
ExoticLiquids
Liquids 49
49Gilbert
GilbertSt.
St. London
London
22 New
NewOrleans
OrleansCajun
CajunDelights
Delights P.O.
P.O.Box
Box78934
78934 New
NewOrleans
Orleans
33 Grandma
GrandmaKelly's
Kelly'sHomestead
Homestead 707
707Oxford
OxfordRd.
Rd. Ann
AnnArbor
Arbor
Introduction Relational databases are organized into tables. Each table contains rows
and columns. The rows represent records. The columns define the data items in
each record.
A key is a column, or group of columns, that contains a unique attribute or
attributes that you use to identify a row in a table. For example, each employee
must have a unique identification number. In an employee table, the employee’s
identification number uniquely identifies a row for each employee.
Scenario When you design a database, you define tables to represent each related group
of data. For example, a retailer company might design a database with tables
named Customers, Products, and Orders.
Definition of primary key You use a primary key to uniquely identify rows in a table. When you
design a database table, you should specify one or more columns as the primary
key. Each row has a unique value for its primary key that distinguishes it from
all other rows
Definition of foreign key You use a foreign key to link to a different table. When you design a
database table, you can specify foreign keys in the table. A foreign key in one
table refers to a primary key in another table. The value of the foreign key
identifies a particular row in the other table. A foreign key can be a single
column or a combination of columns. You can define any number of foreign
keys in a table.
Guidelines for defining a Consider the following facts and guidelines when defining a table:
normalized database
Each column in the table must represent an atomic piece of data.
Choose an appropriate name for each column.
Choose an appropriate data type for each column.
Identify one or more columns in the table as the primary key.
Define foreign keys to establish links to primary keys in other tables.
4 Appendix A: Overview of SQL Statements and Stored Procedures
Specifying the required You use a FROM clause to specify the required tables. Consider the
tables following facts and guidelines when using the FROM clause:
The FROM clause is mandatory. Use the FROM clause to read from a
specific table.
You can join data from several tables, by using the JOIN operator. You will
see how to do this later in this appendix.
Appendix A: Overview of SQL Statements and Stored Procedures 5
Specifying the rows to Use a WHERE clause to specify the rows to be returned. Consider the
be returned following facts and guidelines when using the WHERE clause:
The WHERE clause is optional. If you do not provide a WHERE clause,
you will retrieve all of the rows in the specified table.
You can define search conditions in the WHERE clause, to restrict the rows
to return. The search conditions can include string comparisons, numerical
comparisons, and other conditional tests.
Specifying the row order You use an ORDER BY clause to retrieve rows in a specific order.
Consider the following facts and guidelines when using the ORDER BY clause:
The ORDER BY clause is optional. If you do not provide an ORDER BY
clause, the row order is undefined.
If you provide an ORDER BY clause, specify a column for the database
engine to use for sorting the rows.
You can provide an optional ASC or DESC clause to sort rows in ascending
or descending order. The default sorting order is ASC (ascending).
Example of using the The USE statement moves the connection context to the specified database. The
SELECT statement SELECT statement retrieves the productid, productname, and unitprice
columns from the Products table in the Northwind Traders database. The
WHERE clause restricts the rows returned so that only products costing more
than $50 and less than $100 are returned. The ORDER BY clause sorts rows in
order of descending unit price.
/* Retrieve the product ID, product name, and unit price
for products costing more than $50 and less than $100.
Retrieve products in order of descending price */
USE northwind
SELECT productid, productname, unitprice
FROM products
WHERE unitprice > 50.00 AND unitprice < 100.00
ORDER BY unitprice DESC
GO
Result The SELECT statement in the preceding example produces the following result.
productid productname unitprice
9 Mishi Kobe Niku 97.00
20 Sir Rodney's Marmalade 81.00
18 Carnarvon Tigers 62.50
59 Raclette Courdavault 55.00
51 Manjimup Dried Apples 53.00
6 Appendix A: Overview of SQL Statements and Stored Procedures
Practice The Products table has a column named unitsinstock, which gives the number
of units currently in stock for each product. There is also a column named
reorderlevel, which indicates the minimum number of units to maintain in
stock for each product.
Rewrite the SELECT statement in the previous example, to retrieve the
productid, productname, unitsinstock, and reorderlevel columns for all
products that have fallen below the reorder level. There is no need to sort the
rows in any particular order.
A sample solution is provided for this practice. See the file Select.sql in the
folder <install folder>\Practices\AppendixA.
Appendix A: Overview of SQL Statements and Stored Procedures 7
Introduction You use a WHERE clause to filter rows retrieved in a query. You can
retrieve only the rows that you need from the database, rather than retrieving all
of the rows.
8 Appendix A: Overview of SQL Statements and Stored Procedures
Filtering rows You filter rows by using search conditions. The following table describes
the types of filters and the corresponding search conditions that you can use to
filter data.
Type of filter Usage Search condition
Comparison Use comparison operators to compare values =, >, <, >=, <=, and
operators in a table to a specified value or expression. <>
Likeness Use the LIKE and NOT LIKE search LIKE and NOT
comparisons conditions with wildcard characters to select LIKE
rows by comparing character strings.
Logical Use the AND, OR, and NOT logical operators AND, OR, and
operators to combine a series of expressions and to NOT
refine query processing. Use parentheses to
enforce or emphasize the order of evaluation
of the test conditions.
Range of Use the BETWEEN and NOT BETWEEN BETWEEN and
values operators to retrieve rows within or outside a NOT BETWEEN
specified range of values.
Microsoft SQL Server™ includes the end
values in the result set. This means you can
use BETWEEN rather than an expression
such as (>= x AND <= y). Similarly, you can
use NOT BETWEEN rather than an
expression such as (< x OR > y).
Lists of values Use the IN search condition to retrieve rows IN and NOT IN
that match a specified list of values.
Use the NOT IN search condition to retrieve
rows that do not match a specified list of
values.
Unknown Use the IS NULL search condition to retrieve IS NULL and IS
values rows where information is missing from a NOT NULL
specified column. A column has a null value
if no value is entered during data entry and no
default values are defined for that column.
Use the IS NOT NULL search condition to
retrieve rows that do not have a null value for
a specified column.
Example of using The following example retrieves from the Employees table the last name and
comparison operators city of residence of employees who reside in the United States:
/* Retrieve information for employees who reside in the US */
USE northwind
SELECT lastname, city
FROM employees
WHERE country = 'USA'
GO
Appendix A: Overview of SQL Statements and Stored Procedures 9
Using string The following table describes characters to use for string comparisons.
comparisons
Wildcard Description
Example of using string The following example retrieves companies from the Customers table that have
comparisons the word “Restaurant” somewhere in their company names:
/* Retrieve company names that contain the word restaurant */
USE northwind
SELECT companyname
FROM customers
WHERE companyname LIKE '%Restaurant%'
GO
Example of using logical The following example retrieves all products with product names that begin
operators with the letter T or have a product ID of 46, and that have a price greater than
$10:
/* Retrieve products that start with T or have a product ID
of 46, and cost more than $10 */
USE northwind
SELECT productid, productname, supplierid, unitprice
FROM products
WHERE (productname LIKE 'T%' OR productid = 46)
AND (unitprice > 10)
GO
Example of using a The following example retrieves the product name and unit price of all products
range of values with a unit price between $10 and $18, inclusive:
/* Retrieve products costing between $10 and $18 inclusive */
USE northwind
SELECT productname, unitprice
FROM products
WHERE unitprice BETWEEN 10 AND 18
GO
Example of using a list The following example produces a list of companies from the Suppliers table
of values that are located in Japan or Italy:
/* Retrieve suppliers in Japan or Italy */
USE northwind
SELECT companyname, country
FROM suppliers
WHERE country IN ('Japan', 'Italy')
GO
10 Appendix A: Overview of SQL Statements and Stored Procedures
Example of retrieving The following example retrieves a list of companies from the Suppliers table for
unknown values which the fax column contains a null value:
/* Retrieve suppliers that have a null fax */
USE northwind
SELECT companyname, fax
FROM suppliers
WHERE fax IS NULL
GO
Practice Write an SQL SELECT statement to retrieve the product name, unit price, and
number of units in stock for products that match all of the following conditions:
The product name must start with the letter T.
The unit price must be between $5 and $10, inclusive.
The number of units in stock must be at least 25.
A sample solution is provided for this practice. See the file Filter.sql in the
folder <install folder>\Practices\AppendixA.
Appendix A: Overview of SQL Statements and Stored Procedures 11
Introduction This lesson shows how to use the JOIN keyword to join tables. The result set
includes rows and columns from each table. You will see how to use the ON
keyword to define the join condition. You will also see how to provide aliases
for table names to simplify the syntax in a complex query.
Lesson objectives After completing this lesson, you will be able to:
Describe why joins are important in relational databases.
Combine data from separate tables by using joins.
Use aliases for table names.
12 Appendix A: Overview of SQL Statements and Stored Procedures
orders
orders customers
customers
orderid
orderid orderdate
orderdate customerid
customerid customerid
customerid companyname
companyname
10248
10248 1996-07-04
1996-07-04 VINET
VINET VINET
VINET Vins
Vinsetetalcools
alcoolsChevalier
Chevalier
10249
10249 1996-07-05
1996-07-05 TOMSP
TOMSP TOMSP
TOMSP Toms
TomsSpezialitäten
Spezialitäten
10250
10250 1996-07-08
1996-07-08 HANAR
HANAR HANAR
HANAR Hanari
HanariCarnes
Carnes
results
results
orderid
orderid orderdate
orderdate companyname
companyname
10248
10248 1996-07-04
1996-07-04 Vins
Vinsetetalcools
alcoolsChevalier
Chevalier
10249
10249 1996-07-05
1996-07-05 Toms
TomsSpezialitäten
Spezialitäten
10250
10250 1996-07-08
1996-07-08 Hanari
HanariCarnes
Carnes
Introduction A table join combines data from two or more tables. You use the JOIN
operator in a FROM clause to query any number of tables in the database to
produce a single result set that contains merged data from these tables.
Joins are an essential part of relational database theory. You can write a JOIN
operator to combine data from multiple tables in any way you want, depending
on the needs of your application.
Using inner joins An inner join combines tables by comparing values in common columns in the
tables. The database engine returns only rows that match the join conditions.
Example of using an The Northwind Traders database has a table named Orders that contains
inner join information about all orders received by Northwind Traders. The following
table shows some of the data in the Orders table.
orderid orderdate customerid
10248 1996-07-04 VINET
10249 1996-07-05 TOMSP
10250 1996-07-08 HANAR
The database also has a table named Customers that contains information about
all customers who have placed an order with Northwind Traders. The following
table shows some of the data in the Customers table.
customerid companyname
VINET Vins et alcools Chevalier
TOMSP Toms Spezialitäten
HANAR Hanari Carnes
Appendix A: Overview of SQL Statements and Stored Procedures 13
You can define an inner join on the Orders and Customers tables to retrieve
detailed information about the customer who placed each order. You use the
customerid foreign key in the Orders table to identify the customer who placed
each order.
Practice Open the Northwind Traders database in the SQL Server Query Analyzer.
Examine the Orders table and identify the foreign keys in this table. Consider
how you can use these foreign keys to join the Orders table to other tables in the
Northwind Traders database.
14 Appendix A: Overview of SQL Statements and Stored Procedures
orders
orders customers
customers
orderid
orderid orderdate
orderdate customerid
customerid customerid
customerid companyname
companyname
10248
10248 1996-07-04
1996-07-04 VINET
VINET VINET
VINET Vins
Vinsetetalcools
alcoolsChevalier
Chevalier
10249
10249 1996-07-05
1996-07-05 TOMSP
TOMSP TOMSP
TOMSP Toms
TomsSpezialitäten
Spezialitäten
10250
10250 1996-07-08
1996-07-08 HANAR
HANAR HANAR
HANAR Hanari
HanariCarnes
Carnes
results
results
orderid
orderid orderdate
orderdate companyname
companyname
10248 1996-07-04 Vins
Vinsetetalcools
alcoolsChevalier
Practice
10248 1996-07-04 Chevalier
10249
10249
10250
1996-07-05
1996-07-05
1996-07-08
Toms
TomsSpezialitäten
Hanari
Spezialitäten
10250 1996-07-08 HanariCarnes
Carnes
Introduction You use the JOIN keyword to join two tables. The JOIN keyword specifies
which tables are to be joined and how to join them. Inner joins are used in most
situations, and are the default type of join in SQL Server.
Partial syntax for an Partial syntax for an inner join is as follows:
inner join
SELECT <select_list>
FROM {<first_table_source>} [,…n]
JOIN <joined_table_source>
ON <join_condition>
Defining an inner join You use the ON keyword to specify the join condition for an inner join.
Consider the following facts and guidelines when defining an inner join:
Specify the tables that you want to join.
Limit the number of tables in a join. The more tables that you join, the
longer the database engine takes to process your query.
Use a foreign key in one table to link to a primary key in another table. The
columns must have the same or similar data types.
Select required columns from the joined tables.
If any columns have the same name in both tables, use the table name to
qualify the column name. Use the syntax table_name.column_name.
Appendix A: Overview of SQL Statements and Stored Procedures 15
Example of defining an The following example performs an inner join on the Orders and Customers
inner join on two tables tables to get the name of the customer who placed each order. The join
condition uses the customerid column in each table.
/* Join the orders and customers tables, using the customerid
as the join condition */
USE northwind
SELECT orderid, orderdate, companyname
FROM orders JOIN customers
ON orders.customerid = customers.customerid
GO
Practice Rewrite the SELECT statement in the previous example to perform an inner
join on the Orders and Employees tables. For each order, retrieve the order ID,
the order date, and the last name of the employee who took the order.
A sample solution is provided for this practice. See the file
JoinOrdersEmployees.sql in the folder <install
folder>\Practices\AppendixA.
16 Appendix A: Overview of SQL Statements and Stored Procedures
Introduction You use aliases for table names, to simplify complex query statements. This
makes Transact-SQL scripts easier to read and to maintain.
You can replace a long and complex fully qualified table name with a simple,
abbreviated alias name when writing scripts. You use an alias name in place of
the full table name.
Partial syntax for table Partial syntax for table aliases is as follows:
aliases
SELECT <select_list>
FROM <table_source> AS <table_alias>
Example of defining a The following example performs a join on the Orders and Customers tables.
join without using table Because the example does not use table aliases, you must write the names of the
aliases Orders and Customers tables in full in the join condition.
/* Perform a join without using table aliases */
USE northwind
SELECT orderid, orderdate, companyname
FROM orders JOIN customers
ON orders.customerid = customers.customerid
GO
Example of defining a The following example performs the same join as the previous example
join by using table but uses aliases for the Orders and Customers tables. The aliases are
aliases used to simplify the join condition.
/* Perform a join using table aliases */
USE northwind
SELECT o.orderid, o.orderdate, c.companyname
FROM orders AS o
JOIN customers AS c
ON o.customerid = c.customerid
GO
Appendix A: Overview of SQL Statements and Stored Procedures 17
Introduction In this lesson, you will learn how to modify data in a database. You have
already seen how to query data by using a SELECT statement. In this lesson,
you will see how to write INSERT, DELETE, and UPDATE statements to
change the data in the database.
Lesson objectives After completing this lesson, you will be able to:
Use transactions to enforce the logical consistency of data.
Write INSERT statements to insert rows into a new or existing table.
Write DELETE statements to delete rows.
Write UPDATE statements to update existing rows.
18 Appendix A: Overview of SQL Statements and Stored Procedures
Ending a transaction You can end a transaction in one of two ways. To commit a transaction, use the
COMMIT TRANSACTION statement. To rollback a transaction, use the
ROLLBACK TRANSACTION statement. The following table describes these
statements.
Statement Description
Example of using The following example transfers $100 from a savings account into a checking
transactions account for a customer by using a transaction. It undoes any data changes if
there is an error at any point during the transaction.
/* Transfer money from a savings account to a checking
account. Use a transaction to ensure the logical
consistency of the data */
BEGIN TRANSACTION
UPDATE savings
SET balance = balance – 100
WHERE custid = 78910
IF @@ERROR <> 0
BEGIN
RAISERROR ('Error, transaction not completed!', 16, -1)
ROLLBACK TRANSACTION
END
UPDATE checking
SET balance = balance + 100
WHERE custid = 78910
IF @@ERROR <> 0
BEGIN
RAISERROR ('Error, transaction not completed!', 16, -1)
ROLLBACK TRANSACTION
END
COMMIT TRANSACTION
20 Appendix A: Overview of SQL Statements and Stored Procedures
Introduction You use the INSERT…VALUES statement to insert a new row into an existing
table. The VALUES keyword indicates the values for the new row.
Partial syntax for Partial syntax for the INSERT…VALUES statement is as follows:
INSERT…VALUES
INSERT [INTO] <table_name>(column_name {,…n})
VALUES (value {,…n})
Guidelines for using Consider the following facts and guidelines when using the
INSERT…SELECT INSERT…VALUES statement:
Make sure that the new values have the same or similar data types as the
columns in the destination table.
Specify values for all of the required columns in the destination table.
You do not have to specify values for columns with default values or for
columns that can contain null values.
Do not specify values for identity columns.
Appendix A: Overview of SQL Statements and Stored Procedures 21
Example of using The following example adds a single product to the Products table. The
INSERT…VALUES ProductName and Discontinued columns cannot be null, so these values must
be supplied in the INSERT...VALUES statement. The other columns in this
table can be null, so they can be omitted from the INSERT...VALUES
statement.
/* Insert a new product into the Products table */
USE northwind
INSERT Products (ProductName, Discontinued)
VALUES ('Carving Ski', 0)
GO
Introduction You use the SELECT…INTO statement to insert a result set into a new table.
This enables you to populate new tables in a database with imported or
computed data.
Scenario 1 You can use the SELECT…INTO statement to break down complex problems
that require a data set from various sources. If you first create a temporary table,
the queries that you execute on it are simpler than those that you execute on
multiple tables or databases.
For example, you might want to create a temporary table containing detailed
information about orders at Northwind Traders. For each order, the temporary
table might contain the product name from the Products table, the company
name from the Customers table, and the last name of the employee that took the
order.
Scenario 2 You can also use the SELECT…INTO statement to temporarily store computed
data. For example, you might want to create a temporary table containing the
unit price and computed sales tax for all products sold by Northwind Traders.
Partial syntax for Partial syntax for the SELECT…INTO statement is as follows:
SELECT…INTO
SELECT <select_list>
INTO <new_table>
FROM {<table_source>}{,…n}
[ WHERE <search_condition> ]
Appendix A: Overview of SQL Statements and Stored Procedures 23
Guidelines for using Consider the following facts and guidelines when using the SELECT…INTO
SELECT…INTO statement:
You can use the SELECT…INTO statement to create a table and to insert
rows into the table in a single operation.
You must ensure that the table name in the SELECT…INTO statement is
unique. If a table exists with the same name, the SELECT…INTO statement
fails.
You must create column aliases or specify the column names of the new
table in the select list.
Creating a temporary or You can use the SELECT…INTO statement to create a local temporary table, a
permanent table global temporary table, or a permanent table. The following describes each of
these table types and shows how to specify them by using the SELECT…INTO
statement.
Type of table How to specify Description
Example of using The following example creates a local temporary table based on a query made
SELECT…INTO on the Products table. Notice that you can use string and mathematical
functions to manipulate the result set.
/* Retrieve data from the products table, and insert the
result set into a new temporary table named #pricetable */
USE northwind
SELECT productname AS products
, unitprice AS price
, (unitprice * 0.1) AS tax
INTO #pricetable
FROM products
GO
Introduction You use the DELETE statement to delete one or more rows from a table. Each
deleted row is logged in the transaction log.
Partial syntax for Partial syntax for the DELETE statement is as follows:
DELETE
DELETE <table_name>
[ WHERE <search_condition> ]
Guidelines for using Consider the following facts and guidelines when using the DELETE statement:
DELETE
Use a WHERE clause to specify which rows to delete.
If you omit the WHERE clause, SQL Server deletes all of the rows in the
table.
Example of using The following example deletes order records that are at least six months old:
DELETE
/* Delete orders that are at least six months old */
USE northwind
DELETE orders
WHERE DATEDIFF (MONTH, shippeddate, GETDATE()) >= 6
GO
Practice Write a DELETE statement to delete rows from the "Order Details" table. (You
must use quotes around this table name, because the table name contains a
space character.) Delete each row where the quantity ordered is more than 50.
A sample solution is provided for this practice. See DeleteOrderDetails.sql in
the folder <install folder>\Practices\AppendixA.
26 Appendix A: Overview of SQL Statements and Stored Procedures
Introduction You use the UPDATE statement to modify existing rows in a table. You can
change single rows, a group of rows, or all of the rows in a table.
Partial syntax for Partial syntax for the UPDATE statement is as follows:
UPDATE
UPDATE <table_name>
SET { column_name = {expression | DEFAULT | NULL} } [,…n]
[ WHERE <search_condition> ]
Guidelines for using Consider the following facts and guidelines when using the UPDATE
UPDATE statement:
You can change the data in only one table at a time.
Use a WHERE clause to specify which rows to update.
Use the SET keyword to specify the new values for columns in the table.
You can use expressions for the new values. For example, you can use an
expression such as (unitprice * 2), add two columns together, and so on.
Make sure that the new values have the correct data types for the columns
that you are updating.
SQL Server does not update any rows that violate any integrity constraints.
The changes do not occur, and the statement is rolled back.
Appendix A: Overview of SQL Statements and Stored Procedures 27
Example of using The following example adds 10 percent to the current price of all Northwind
UPDATE Traders products:
/* Add 10 percent to the price of all products */
USE northwind
UPDATE products
SET unitprice = unitprice * 1.1
GO
Practice Rewrite the UPDATE statement in the previous example so that it only updates
the price for products that cost $50 or more.
A sample solution is provided for this practice. See the file
UpdateSomePrices.sql in the folder <install folder>\Practices\AppendixA.
28 Appendix A: Overview of SQL Statements and Stored Procedures
Introduction You use the @@ERROR variable to detect errors in SQL statements. SQL
Server sets this variable after every statement, to indicate whether the statement
succeeded or failed.
The value 0 indicates successful completion. Any other value indicates an error.
The value of @@ERROR indicates the specific problem.
Guidelines for using Consider the following facts and guidelines when using use the @@ERROR
@@ERROR variable:
The value of @@ERROR is reset after each statement. If you have multiple
statements that might fail, test the value of @@ERROR after each
statement.
Use the value of @@ERROR to detect the precise nature of the error.
Example of using The following example changes the CategoryID for all products that currently
@@ERROR have a CategoryID of 8. The CategoryID is changed to 9 for these products.
The @@ERROR variable is tested, to see if the statement succeeded.
/* Change CategoryID, and test for errors */
UPDATE products SET CategoryID = 9
WHERE CategoryID = 8
IF @@ERROR = 547
print 'A check constraint violation occurred'
Appendix A: Overview of SQL Statements and Stored Procedures 29
Introduction In this lesson, you will learn how to create and execute a simple stored
procedure in Transact-SQL. You can use stored procedures to encapsulate
business rules and to execute these rules in procedural code in the database
engine.
Lesson objectives After completing this lesson, you will be able to:
Create a simple stored procedure.
Execute a stored procedure.
Describe the advantages of using stored procedures.
30 Appendix A: Overview of SQL Statements and Stored Procedures
Introduction You use the CREATE PROCEDURE statement to create a stored procedure. If
necessary, you can define parameters for the stored procedure to make it more
flexible. Within the body of the stored procedure, you specify the statements
that you want to perform when the stored procedure is executed.
Syntax for creating a The syntax for creating a stored procedure is as follows:
stored procedure
CREATE PROCEDURE <procedure_name>
( @<parameter_name> <parameter_type> {,…n} )
AS
<statements>
Example of creating a The following example creates a stored procedure named orders_info_all. The
stored procedure stored procedure performs a complex SELECT statement, which uses a three-
table join on the Orders, Customers, and Employees tables. The query retrieves
the order ID, the company name for the customer who made the order, and the
last name of the employee that took the order.
This stored procedure does not use any parameters.
/* Create a stored procedure with a SELECT statement, using a
join on the orders, customers, and employees tables */
CREATE PROCEDURE orders_info_all
AS
SELECT o.orderid, c.companyname, e.lastname
FROM orders AS o
JOIN customers AS c ON o.customerid = c.customerid
JOIN employees AS e ON o.employeeid = e.employeeid
GO
32 Appendix A: Overview of SQL Statements and Stored Procedures
Executing a stored You use the EXECUTE statement to execute a stored procedure. If the stored
procedure procedure requires parameters, you pass these parameters as a comma-separated
list.
Syntax for executing a The syntax for executing a stored procedure is as follows:
stored procedure
EXECUTE <procedure_name>
{<parameter_value>}{,…n}
Example of executing a The following example executes the orders_info_all stored procedure created
stored procedure in the previous example:
/* Execute the orders_info_all stored procedure */
USE northwind
EXECUTE orders_info_all
GO
Practice Write a stored procedure to increase the unit price of all products in the
Products table by 10 percent. Also write an SQL statement to execute the stored
procedure.
A sample solution is provided for this practice. See the file
CreateUpdateStoredProcedure.sql in the folder <install
folder>\Practices\AppendixA. When you execute this SQL statement, it
creates a stored procedure named increase_product_prices. To execute this
stored procedure, use the file CallStoredProcedure.sql.
Appendix A: Overview of SQL Statements and Stored Procedures 33
Review
Patients
Column Description
pat_id int NOT NULL, PRIMARY KEY
fname char(20) NOT NULL
lname char(25) NOT NULL
insurance_company char(25) NOT NULL
phone char(10) NULL
34 Appendix A: Overview of SQL Statements and Stored Procedures
Casefiles
Column Description
casefile_id int NOT NULL, PRIMARY KEY
admission_date datetime NOT NULL
pat_id int NOT NULL,
FOREIGN KEY to patients.pat_id
Doc_id int NOT NULL,
FOREIGN KEY to doctors.doc_id
diagnosis char(150) NOT NULL
2. How can you generate a list of patient names for a particular doctor?
You must join all three tables. The relationship between doctors and
patients is a many-to-many relationship. Even though you only want
information from the Doctors and Patients tables, you must also use the
Casefiles table because this table relates doctors to patients. Join the
Doctors table to the Casefiles table on the doc_id column, and then join
the Patients table to the casefiles table on the pat_id column. Use a
WHERE clause to limit the results for a particular doctor.
3. The participating doctors have increased their costs of services. How can
you increase the value in the charge_rate column for all doctors by 12
percent?
Use an UPDATE statement of the following type:
UPDATE doctors SET charge_rate = (charge_rate * 1.12)
Appendix A: Overview of SQL Statements and Stored Procedures 35
4. What is the minimum number of column values that you must supply to add
a new row to the Doctors table?
You must supply data for at least five columns. At a minimum, the
INSERT statement must contain values for the doc_id, fname, lname,
specialty, and charge_rate columns. All other columns can have null
values.
5. How can you remove rows from the Casefiles table for cases where the date
of admission was more than 12 months ago?
Use a DELETE statement of the following type:
DELETE casefiles
WHERE DATEDIFF (MONTH, admission_date, GETDATE()) >= 12
For more information For help with executing files, search for “Execute a query” in SQL Query
Analyzer Help.
Other resources that you can use include:
The Northwind database schema. Use the SQL Query Analyzer to examine
the table information for the Northwind database.
Microsoft SQL Server Books Online.
Appendix A: Overview of SQL Statements and Stored Procedures 37
Scenario The organization of the classroom simulates a worldwide trading firm named
Northwind Traders.
Starter and solution files You will save your SQL scripts and result files in the folder <install
folder>\Labs\LabA\Starter. Solution SQL scripts and result files are in the
folder <install folder>\Labs\LabA\Solution.
Estimated time to
complete this lab: 60
minutes
38 Appendix A: Overview of SQL Statements and Stored Procedures
Exercise 1
Retrieving Data from a Database
In this exercise, you will select specific data from tables in the Northwind
database.
Result Your result should look similar to the following partial result set.
productname unitprice
Chai 18.0000
Chang 19.0000
Aniseed Syrup 10.0000
.
.
.
(77 row(s) affected)
Appendix A: Overview of SQL Statements and Stored Procedures 39
Result Your result should look like the following result set.
productname unitprice
Ikura 31.0000
(1 row(s) affected)
Result Your result should look similar to the following partial result set.
productname unitprice
Chef Anton's Cajun Seasoning 22.0000
Chef Anton's Gumbo Mix 21.3500
Grandma's Boysenberry Spread 25.0000
.
.
.
(31 row(s) affected)
Result Your result should look similar to the following partial result set.
companyname country
Alfreds Futterkiste Germany
Around the Horn UK
Blauer See Delikatessen Germany
Blondesddsl père et fils France
.
.
.
(29 row(s) affected)
Result Your result should look similar to the following partial result set.
orderid orderdate requireddate
11008 1998-04-08 00:00:00.000 1998-05-06 00:00:00.000
11019 1998-04-13 00:00:00.000 1998-05-11 00:00:00.000
11039 1998-04-21 00:00:00.000 1998-05-19 00:00:00.000
.
.
.
(21 row(s) affected)
Appendix A: Overview of SQL Statements and Stored Procedures 41
Exercise 2
Combining Data from Multiple Tables
In this exercise, you will write and execute queries that join tables in the
Northwind database. You will use the following tables:
The Categories table, which describes the different categories of products
that Northwind Traders sells. The Categories table has a primary key named
categoryid.
The Suppliers table, which describes the companies that supply products to
Northwind Traders. The Suppliers table has a primary key named
supplierid.
The Products table, which describes the products that Northwind Traders
offers. The Products table has a primary key named productid.
The Products table has a foreign key named categoryid, which identifies a
category row in the Categories table. The categoryid value in the Products
table corresponds to a categoryid value in the Categories table.
The Products table also has a foreign key named supplierid, which
identifies a supplier row in the Suppliers table. The supplierid value in the
Products table corresponds to a supplierid value in the Suppliers table.
Result Your result will look similar to the following partial result set.
productname categoryname
Chai Beverages
Chang Beverages
Guaraná Fantástica Beverages
…
Aniseed Syrup Condiments
Chef Anton's Cajun Seasoning Condiments
Chef Anton's Gumbo Mix Condiments
…
Pavlova Confections
Teatime Chocolate Biscuits Confections
Sir Rodney's Marmalade Confections
.
.
.
(77 row(s) affected)
Result Your result should look similar to the following partial result set.
productname categoryname companyname
Côte de Blaye Beverages Aux joyeux
ecclésiastiques
Chartreuse verte Beverages Aux joyeux
ecclésiastiques
Sasquatch Ale Beverages Bigfoot Breweries
Steeleye Stout Beverages Bigfoot Breweries
Laughing Lumberjack Lager Beverages Bigfoot Breweries
Queso Cabrales Dairy Products Cooperativa de
Quesos 'Las Cabras'
.
.
.
(77 row(s) affected)
Appendix A: Overview of SQL Statements and Stored Procedures 43
Exercise 3
Modifying Data
In this exercise, you will modify the data in the Northwind database. You will
use an INSERT statement to insert new rows into the Customers table. You will
use the DELETE statement to delete rows from the Order Details table. Finally,
you will use the UPDATE statement to update rows in the Products table.
3. Execute the SELECT statement from step 1 to see how the Customers table
has changed. Verify that the table contains rows inserted from the Suppliers
table.
44 Appendix A: Overview of SQL Statements and Stored Procedures
Exercise 4
Using Stored Procedures
In this exercise, you will create a stored procedure to encapsulate a series of
SQL statements.