Professional Documents
Culture Documents
DB Best Lab Mannual
DB Best Lab Mannual
Systems
Laboratory Manual
September,
2008
1
Table of Contents
BACKGROUND.................................................................................................................................................5
LABORATORY SESSION 1: INTRODUCING MICROSOFT SQL SERVER 2000 ENVIRONMENT 6
WHAT ARE QUERY ANALYZER AND ENTERPRISE MANAGER? .....................................................................................7
HOW TO USE QUERY ANALYZER:..........................................................................................................................7
HOW TO USE ENTERPRISE MANAGER:....................................................................................................................8
LABORATORY SESSION 2: CREATING, MODIFYING AND DELETING DATABASES...............10
I.CREATING A DATABASE....................................................................................................................................10
II.M ODIFYING A DATABASE.................................................................................................................................11
III.DELETING A DATABASE..................................................................................................................................11
EXERCISES:.......................................................................................................................................................12
LABORATORY SESSION 3: CREATING TABLES AND DATA TYPES..............................................13
CREATING TABLES.............................................................................................................................................13
DELETING A TABLE............................................................................................................................................14
MODIFYING A TABLE..........................................................................................................................................14
Adding a Column .....................................................................................................................................14
Deleting a Column...................................................................................................................................14
Generating Column Values......................................................................................................................14
LABORATORY SESSION 4: RETRIEVING DATA..................................................................................16
RETRIEVING DATA BY USING THE SELECT STATEMENT AND FILTERING DATA........................................................16
Using the SELECT Statement...................................................................................................................16
Specifying columns............................................................................................................................................16
Selecting ALL Columns (SELECT *)...........................................................................................................17
Eliminating Duplicates using DISTINCT......................................................................................................17
LABORATORY SESSION 5: FILTERING DATA.....................................................................................18
Logical and Grouping Operators (Parentheses).....................................................................................20
LABORATORY SESSION 6: FORMATTING RESULT SETS................................................................22
Sorting Data.............................................................................................................................................22
Eliminating Duplicate Rows.....................................................................................................................22
Changing Columns Names (Aliases)........................................................................................................22
Exercise:...................................................................................................................................................23
LABORATORY SESSION 7: GROUPING AND SUMMARIZING DATA.............................................25
LISTING THE TOP N VALUES..............................................................................................................................25
USING AGGREGATE FUNCTIONS...........................................................................................................................25
Using Aggregate Functions with NULL Values.......................................................................................26
GROUP BY Fundamentals.......................................................................................................................27
Using the GROUP BY Clause............................................................................................................................27
Using the GROUP BY Clause with the HAVING Clause...................................................................................27
Using the GROUPING Function........................................................................................................................29
LABORATORY SESSION 8: IMPLEMENTING DATA INTEGRITY/SPECIFYING
CONSTRAINTS\..............................................................................................................................................31
CREATING CONSTRAINTS.....................................................................................................................................31
TYPES OF CONSTRAINTS.....................................................................................................................................32
1.DEFAULT Constraints..........................................................................................................................32
2. CHECK Constraints ............................................................................................................................33
3.PRIMARY KEY Constraints..................................................................................................................33
4.UNIQUE Constraints............................................................................................................................34
FOREIGN KEY Constraints.....................................................................................................................34
Cascading Referential Integrity...........................................................................................................................35
DISABLING CONSTRAINTS....................................................................................................................................35
Disabling Constraint Checking When Loading New Data......................................................................36
LABORATORY SESSION 9: JOINING MULTIPLE TABLES................................................................39
2
USING INNER JOINS ............................................................................................................................................39
EXERCISES........................................................................................................................................................40
LABORATORY SESSION 10: SUBQUEIRES............................................................................................41
How to use Subqueries.............................................................................................................................41
Using a Subquery as a Derived Table......................................................................................................41
Using a Subquery as an Expression.........................................................................................................41
Using a subquery to correlated Data.......................................................................................................42
Subqueries in the SELECT Clause...........................................................................................................43
The IN, ALL, and ANY operators in subquery.........................................................................................43
Using the Exists and NOT EXISTS Clauses.............................................................................................44
Exercises...................................................................................................................................................45
LABORATORY SESSION 11: MODIFYING DATA.................................................................................46
Using Transactions..................................................................................................................................46
Inserting Data..........................................................................................................................................47
Inserting a Row of Data by Values.....................................................................................................................47
Using the INSERT…SELECT Statement...........................................................................................................47
Creating a Table Using the SELECT INTO Statement.......................................................................................48
Inserting Partial Data..........................................................................................................................................48
Inserting Data by Using Column Defaults..........................................................................................................49
Deleting Data...........................................................................................................................................49
Using the Delete Statement.................................................................................................................................49
Using the Truncate Table Statement ..................................................................................................................49
Deleting Rows Based on Other Tables................................................................................................................50
Specifying Conditions in the WHERE Clause....................................................................................................50
Updating Data..........................................................................................................................................50
Updating Rows Based on Data in the Table........................................................................................................51
Updating Rows Based on Other Tables...............................................................................................................51
LABORATORY SESSION 12: VIRTUAL TABLE (VIEWS)....................................................................53
Creating Views.........................................................................................................................................53
Restrictions on View Definitions:.......................................................................................................................53
Example: View of Joined Tables...................................................................................................................54
Altering and Dropping Views...................................................................................................................54
Altering View....................................................................................................................................................54
Syntax: CREATE VIEW owner view_name [column]...............................................................................55
Dropping View...................................................................................................................................................55
Locating View Definition Information................................................................................................................55
LABORATORY SESSION 13: USER DEFINED FUNCTION..................................................................57
WHAT IS A USER DEFINED FUNCTION?.................................................................................................................57
SETTING PERMISSIONS FOR USER-DEFINED FUNCTIONS............................................................................................58
ALTERING AND DROPPING USER-DEFINED FUNCTIONS.............................................................................................58
Altering Functions....................................................................................................................................58
Dropping Functions.................................................................................................................................58
USING A SCALAR USER-DEFINED FUNCTION...........................................................................................................59
USING A MULTI-STATEMENT TABLE-VALUED FUNCTION.........................................................................................59
LABORATORY SESSION 14: STORED PROCEDURES.........................................................................61
CREATING A STORED PROCEDURE.........................................................................................................................61
Viewing Information About Stored Procedures.......................................................................................62
EXECUTING STORED PROCEDURES........................................................................................................................62
Executing a Stored Procedure by Itself....................................................................................................62
ALTERING AND DROPPING STORED PROCEDURES....................................................................................................63
Altering Stored Procedures......................................................................................................................63
Dropping Stored Procedures...................................................................................................................64
USING PARAMETERS IN STORED PROCEDURES........................................................................................................64
Using Input Parameters...........................................................................................................................64
LABORATORY SESSION 15: TRIGGERS.................................................................................................66
CONSIDERATION OF USING TRIGGERS....................................................................................................................66
CREATING TRIGGERS..........................................................................................................................................66
3
Disabling and Enabling a Trigger ..........................................................................................................68
DROPPING A TRIGGER .........................................................................................................................................68
HOW AN INSERT TRIGGER WORKS...................................................................................................................69
HOW A DELETE TRIGGER WORKS........................................................................................................................69
HOW AN UPDATE TRIGGER WORKS.................................................................................................................70
HOW AN INSTEAD OF TRIGGER WORKS..........................................................................................................70
1.CREATE A TRIGGER THAT GUARANTEES THAT THE SUM OF ALL PENALTIES FOR ONE PLAYER IS NOT MORE THAN 250 BIRR
.......................................................................................................................................................................72
APPENDIX.......................................................................................................................................................73
A. FOOT BALL LEAGUE DATABASE......................................................................................................................73
B. CREDIT DATABASE........................................................................................................................................74
4
Background
The relational database management systems and services is on of the main branches of the
IT industry where technological developments are taking place at a very rapid pace. We see
hundreds of new database and related products being released every month. Major
Software vendors churning out database products with more and more features, with each
release of their database offerings. The competition in the database market segment is so
intense that survival itself is extremely difficult. Other than the database vendors there are
thousands of companies who developed applications, for example, ERP, e-commerce,
banking, etc., which are implemented in one of the relational database management
systems. Database is becoming prominent by the day. Today, almost all applications – from
spreadsheets and word processing to statistical analysis tools – have the capability to
seamlessly integrate with the databases, get the required data from the databases, and use it
for performing tasks from statistical analysis to mail-merging.
The name SQL is derived from Structured Query Language. Originally, SQL was called
SEQUEL (for Structured English Query Language) and was designed and implemented at
IBM Research as the interface for an experimental relational database system called
SYSTEM R. SQL is now the standard language for commercial relational DBMSs. A joint
effort by ANSI (the American National Standards Institute) and ISO (the International
Standards Organization) has led to a standard version of SQL (ANSI 1986) called SQL-86
or SQL1. A revised and much expanded standard called SQL2 (also referred to as SQL-92)
has subsequently been developed. Plans are already well underway for SQL3, which will
further extend SQL with object-oriented and other recent database concepts.
SQL is a comprehensive database language; it has statements for data definition, query, and
update. Hence, it is both a DDL and a DML. In addition, it has facilities for defining views
on the database, for specifying security and authorization, for defining integrity constraints,
and for specifying transaction controls. It also has rules for embedding SQL statements into
a general-purpose programming language such as C++ or Java and etc.
This manual has 15 laboratory sessions (lessons). Each laboratory session has objectives,
description of the lab lessons, and exercises. Students are expected to read the lab manual
thoroughly and do the exercises.
Laboratory Session 1: Introducing Microsoft SQL Server
2000 Environment
Objectives: At the end of this laboratory session students will be able to:
Describe how SQL Server can be installed
Use SQL Server database environment effectively and efficiently
Describe the basic type of Transact-SQL.
Use Query Analyzer and Enterprise manager easily
To install Microsoft SQL Server 2000 Enterprise Edition, follow these steps on the
database server and the history server:
1. If Microsoft SQL Server 2000 Enterprise Edition is already installed, uninstall it,
and install it using these instructions to set the correct installation parameters for
Tivoli Business Systems Manager.
2. Insert the Microsoft SQL Server 2000 Enterprise Edition CD and click SQL Server
2000 Components.
3. Click Install Database Server.
a. The Microsoft SQL Server 2000 Enterprise Edition setup begins. Click
Next.
4. From the Welcome window, click Next.
5. From the Computer Name window, click Local Computer and Next.
6. From the Installation Selection window, click Create a new instance of SQL
Server or Install Client Tools. Click Next.
7. From the User Information window, type your name and company. Click Next.
8. From the Software License Agreement window, read the agreement, and click Yes
if you agree with the terms.
9. From the Installation Definition window, click Server and Client Tools. Click
Next.
10. From the Instance Name window, make sure the Default check box is selected and
click Next.
11. From the Setup Type window, click Custom, click both Browse buttons and use
D:\ as the destination directory for the program files and data files. This causes your
SQL Server 2000 program files and data files to be placed in the D:\MSSQL
directory.
12. Click Next.
13. From the Select Components window, accept all the default components and
subcomponents. Click Next.
14. From the Services Accounts window, keep the default value Use the same account
for each service.
a. For Service Settings, click Use a Domain User account. Type the
username, password and domain information for a user that has
administrative rights across all Tivoli Business Systems Manager servers.
b. Click Next.
15. From the Authentication Mode window, click Mixed Mode (Windows
Authentication and SQL Authentication) and type the SQL sa password.
16. From the Collation Settings window, click Collation designator and click
Latin1_General. Select Binary as the Sort Order.
17. From the Network Libraries window, accept the default values for Named Pipes and
Named Pipe name and TCP/IP Sockets. Select both Multi-Protocol and Enable
Multi-Protocol encryption. Click Next.
18. When the Start Copying Files window opens, click Next to continue with the
installation. If you want to change any parameters, click Back.
a. When you click Back, selections reset back to their default values. If you
click Back at any time during the installation, make sure you reselect the
values you wanted before clicking Next.
19. From the Choose Licensing Mode window, click Processor License for. Type the
number of processors you need for your machine. Click Continue.
20. From the Setup Complete window, click Finish.
Query Analyzer and Enterprise Manager are the two frequently used tools for most SQL
Server 2000 client users.
1. Query Analyzer:
The SQL Server Query Analyzer is your primary interface for running SQL queries or
stored procedures. You will be using this utility throughout your database courses.
2. Enterprise Manager:
SQL Server 2000 Enterprise Manager is the primary graphical administrative and
development interface for SQL Server. There is very little SQL Server Enterprise Manager
can do that you can't accomplish from a SQL command. However, using the Enterprise
Manager is sometimes more convenient (especially when you are new to SQL Server
2000). You can use Enterprise Manger to create your own database, cope / delete tables,
query / update tables without writing SQL commands.
• login Query Analyzer: click Start / Programs / Microsoft SQL Server / Query
Analyzer:
• Select your target SQL Server: click the browser button (right to SQL Server input)
and select ORADEV (Note, if you have a SQL Server database running on your
local pc, the default SQL Server is your local SQL Server database).
• Under Connect using, select SQL Server Authentication mode and type in your
user id and password ( you may obtain your userid/password from your instructor),
click OK.
• Congratulations!....you are in Query Analyzer now:
The right pane is Query Analyzer where you write your SQL command, the left pane is
Object Browser window (if you don't see this, just click Tools / Object Browser /
Show/hide to display the window).
• Please note: Northwind and pubs are the two default sample databases for learning
purposes. You can practice your SQL command by using these two sample
databases. However, it is strongly recommended that you create your own database
for all your purposes, to know how, please see the next section How to use
Enterprise Manager. Most importantly, don't try to query, update, delete or modify
master, msdb, tempdb databases, these databases are system databases and not
supposed to be used by client users.
• Write your first SQL query command: in Query Analyzer, with Northwind database
selected from dropdown list above the window, and type in: select * from
Customers, and click Query -> Execute from the toolbar:
• Registering a Server: In order to use Enterprise Manger, you must register a server.
to do so, click Start / Programs / Microsoft SQL Server / Enterprise Manager:
• click Plus sign of Microsoft SQL Servers, select and right-click SQL Server Group
-> New SQL Server Registration, you will see Register SQL Server Wizard:
• At next screen, select The SQL Server login information that was assigned to me by
system administrator (SQL Server Authentication).
• Next screen, select Prompt for the SQL Serve account information when
connecting:
• Next screen, select Add the SQL Server(s) to an existing SQL Server Group:
• To use Enterprise Manager, under SQL Server Group click ORADEV (Windows
NT), and type in your user id/password:
• After connecting the SQL Server, you will see the following screen, and you can do
most activities graphically that you do with in Query Analyzer with SQL
Command.
• To create your own database: right click Databases, click New databases:
Just type in your new database name you choose, then you are done!
Exercise:
1. Using Enterprise manager try to create SQL Server Group called
‘SQL2001’ and try to register your database
2. Under the SQL2001 Server group, create a database called ‘MyDB’
3. Open Microsoft Access and create some tables using Design View and
populate the tables with a data using the Worksheet View
Laboratory Session 2: Creating, Modifying and Deleting
Databases
Objective: The objective of this laboratory session is to create, modify and delete a
database in SQL server 2000.
I. Creating a Database
You can create a database by using
1. Create a database by using the create database wizard in SQL Server
Enterprise Manager
Start SQL Server Enterpriser Manager
Click your database server
On the Tools menu click Wizard
In the Select Wizard dialog box, expand Database, and then double
Click Create Database Wizard
Complete the wizard by using the information in the following table.
Use defaults provided by the wizard for any options that the table does
not specify
Database Name: Library
In the SQL server Manager Console tree, right click Database and then
click New Database
Use the information in the following table to create a new database. Use
the defaults for any options that the table does not specify.
Database Name: Library1
3. Create a database by using Transact- SQL statements in SQL Query
Analyzer
Note: When you create a database you need to use the Master database.
Exercises:
1. Create a database called library in options given below.
2. Modify the database file: increase the size of the data file and decrease the size of
the log file.
3. Delete the database that you have already created.
Laboratory Session 3: Creating Tables and data types
Objective: The main objectives of this laboratory session are:
to create a table and data types in SQL Server 2000
defining the data types for the table
specify the type of information (characters, numbers, or dates) that a column can
hold as well as how the data is stored.
Deleting records ,dropping, altering tables
Creating Tables
Consider the following facts when you create tables in SQL Server. You can have up to:
Two billion tables per database
1,024 columns per table
8060 bytes per row(this approximate maximum length does not apply to image,
text and ntext data types).
Column Collation
SQL Server supports storing objects with different collations in the same database.
Separate SQL Server collations can be specified at the column-level, so that each column in
a table can be assigned a different collation.
Specifying NULL or NOT NULL
You can specify in the table definition whether to allow null values in each column. If you
do not specify NULL or NOT NULL, SQL Server provides the NULL.
The following example creates the table called Product, specifying the columns of the
table, a data type for each column, and whether that column allows NULL values.
)
Example: Create the following tables
CREATE TABLE Employee
(
Emp_no int not null,
Emp_Name varchar(30),
Address varchar (30)
)
Create table Product
(
Product id int not null ,
Product_name varchar (20),
Quantity int ,
Manu_date datetime,
Price money
)
Deleting a Table
Deleting a table removes that table definition and all data, as well as the permission
specification for that table.
Before you delete a table, you should remove any dependencies between the table and other
objects.
Modifying a table
You can modify the table by adding a new column and deleting a column from the table.
Adding a Column
The type of information that you specify when you add a column is similar to that which
you supply when you create a table.
In addition to this, if we need to modify (change ) the data type of the already created
column we can use the following syntax.
ALTER TABLE table_name ALTER COLUMN column_name data type // new data type
For example if we want to change the manufacturing_date from a date data type in to
charcter data type we use the following SQL statements
Deleting a Column
Deleting columns are unrecoverable. Therefore, be certain that you want to remove a
column before doing so.
Syntax: ALTER TABLE table_name DROP COLUMN column_name
This example deletes a column from a table
ALTER TABLE product DROP COLUMN manufacturing_date
Exercise
1. Create table whose name is employee with attributes like name, Id, sex, salary,
Nationality and age.(Using different methods that we have seen).
2. Modify the employee table by adding a column named Qualification.
3. Modify the employee table by modifying a column named age.
4. Delete the table Employee.
Laboratory Session 4: Retrieving Data
Objectives: The main objectives of this laboratory session are:
Retrieving all the information of the table.
Specifying the row by using the where clause.
Specifying the column by selecting individual columns.
Being familiar with different data filtering mechanisms.
Specifying columns
You can retrieve particular columns form a table by listing them in the select list.
The select list contains the columns, expressions, or keywords to select or the local
variable to assign. The options that can be used in the select list include:
SELECT Publisher
FROM BOOk
To eliminate the duplicates from the result ser we use the key word DISTINCT.
SELECT DISTINCT
Publisher
Using the WHERE clause, you can retrieve specific rows based on given
search conditions. The search conditions in the WHERE clause can obtain an
unlimited list of predicates.
Syntax
<search_condition> uses expression {=|<>|>|>=|<|<=}expression
String expressions [NOT]LIKE string_expression
Expressions [NOT |BETWEEN]expression AND expression
When you specify rows with the WHERE clause, consider the following facts
and guidelines:
Place single quotation marks around all char, nchar,varchar,
nvarchar, text, datetime, and smalldatetime data
Use a WHERE clause to limit the number of rows that are returned
when you use the SELECT statement.
This example retrieves the productID and ProductName from the product
table in which its price is more than 1000 birr
SELECT ProductID, ProductName
FROM Product
WHERE price >1000.00—search conditions
Laboratory Session 5: Filtering Data
Objective: The main objectives of this laboratory session are:
Being familiar with different types of filtering
Using comparison operators
Using Logical Operators
You sometimes want to limit the results that a query returns. You can limit the results
by specifying search conditions in a WHERE clause to filter data. There is no limit to
the number of search conditions that you can include in a SELECT statement. The
following table describes the type of filter and the corresponding search condition that
you can use to filter data.
Type of filter Search Condition
Comparison Operators =, <, >, >=, <=, and <>
String comparisons LIKE and NOT LIKE
Logical Operators: combination of conditions AND, OR
Logical Operators: negations NOT
Range of values BETWEEN and NOT BETWEEN
List of values IN and NOT IN
Unknown values IS NULL and IS NOT NULL
Note: Avoid the use of NOT in search conditions. They may slow data retrieval
because all rows in a table are evaluated.
Wildcard Description
% Any string of zeros or more characters
_ Any single character
[] Any Single character within the specified ranges or set
[^] Any single character not within the specified range or set
Example
Expression Returns
LIKE ‘BR%’ Every name beginning with the letters BR
LIKE ‘Br%’ Every name beginning with the letter Br
LIKE ‘%een’ Every name ending with the letter een
LIKE ‘%en%’ Every name containg the letters en
LIKE ‘_en’ Every three letter name ending in the letters en
LIKE ‘[CK]%’ Every name beginning with the letter C or K
LIKE ‘[S-V]ing’ Every four letter name ending in the letters ing and
beginning with single letter from S to V
LIKE ‘M[^c]%’ Every name beginning with the letter M that does not have
letter c as the second letter
Using Logical Operators
Use the logical operators AND, OR, and NOT to combine a series of expressions
and to refine query processing. The results of a query may vary depending on the
grouping of expressions and the order of the search conditions.
When you use logical operators:
Use the AND operator to retrieve rows that meet all of the search criteria
Use the OR operator to retrieve rows that meet any of the search criteria
Use the NOT operator to negate the expressions that follows the operator.
Microsoft SQL Server 2000 evaluates the NOT operator first, followed by the AND
operator and then the OR operator
The Precedence order is from left to right if all operators in an expression are of the
same level
EXAMPLE 1
EXAMPLE 2
EXAMPLE 3
EXAMPLE 4
USE Northwind
SELECT companyname, fax
FROM Suppliers
WHERE fax IS NULL
Laboratory Session 6: Formatting Result Sets
Objective: The main objectives of this laboratory session are:
Sorting Data
Use the ORDER BY clause to sort rows in the result set in ascending (ASC) or descending
(DESC) order. When you use the ORDER BY clause, consider the following facts and
guidelines:
Execute the sp_helpsort system stored procedure to determine the sort
order that was defined for the database during installation
Sort is in ascending order by default
You can sort by column names, computed values, or expressions
Columns that are included in the ORDER BY clause do not have to appear
in the select list.
You can not use text, ntext, or image columns in the ORDER BY clause
If the ORDER BY clause is used with a UNION statement, then the
columns on which you sort must be the column names or aliases specified
in the first SELECT statement.
This statement succeeds because col1 belongs to the first table (t1)
This statement fails because col3 does not belong to the first table (t1)
Using Literals
Literals are letters, numbers, or symbols that are used as specific values in a result set. You
can include literals in the select list to make result sets more readable.
Syntax: SELECT column_name | ‘string literal’[, column_name|’string_literal’…] FROM
table_name
USE northwind
SELECT firstname, lastname,’Identification number:’, employeeid
FROM employees
Exercise:
Create the following tables:
Customer (customer_ID, Customer_name, Customer_address, city, state,
postal_code)
Product (product_ID, product_description, product_finsih, standardprice,
product_line_id)
Order_line (oreder_ID, product_ID, ordered_quatity)
Q2. What is the address of the customer named Home Furnishings? Use an alias
NAME for customer name.
Q3. Which orders have been placed since 10/24/2000?
Q4. List product name, finish, and unit price for all desk and all tables that cost more than
$300 in the product
Q5. Which products have a standard price between $ 200 and $300
Q6. Retrieve the unique order numbers in the Order_line table
Q7. List all customers who live in warmer states
Q8. List all customers city whose address is Florida, California, Texas, or Hawaii. List the
customers alphabetically by state, and alphabetically by customer within each state.
Q9. List the name of customers that begins in AB
Q10. List the name of products that does not contain c as the second letter.
Laboratory Session 7: Grouping and summarizing Data
This lab session provides students with the skill to group and summarize data by using
aggregate functions.
Objectives: at the end of this lesson the students will be able to:
Use the TOP n keyword to retrieve a list of the specified top values in a table.
Generate a single summary value by sing aggregate functions .
Organize summary data for a column by using aggregate functions with the
GROUP BY clauses and the ROLLUP or CUBE operator.
Generate control break reports by using COMPUTE and COMPUTE BY clauses.
USE Northwind
SELECT TOP 5 WITH TIES orderid, productid, quantity
FROM order_details
ORDER BY quantity DESC
Go
This example calculates the average age of all players in the player table
USE FOOBALL_LEAGUE
Select AVG(age)
From player
GO
This example adds all rows in the won column in the Match table.
USE FOOBALL_LEAGUE
Select sum(won)
From Match
GO
USE Northwind
Select Productid, orderid, sum(quantity) as [total quantity]
From orderhist
Group by productid, orderid
WITH ROLLUP
ORDER BY productid, orderid
GO
When you use the GROUP BY clause with CUBE operator, consider the following
facts and guidelines:
If you have n columns or expressions in the GROUP BY clause, SQL Server returns
2n possible combinations in the result set.
The NULLs in the result set indicate that those particular rows are created a result
of the CUBE operator.
You can use the ALL keyword with the CUBE operator.
Example This example returns a result that provides the quantity for each product for
each order, total quantity for all products for each order , total quantity for
each product for all orders , and a grand total quantity for all products for all
orders.
USE Northwind
Select Productid, orderid, sum(quantity) as [total quantity]
From [order details]
Where orderid< 10250
Group by productid, orderid
WITH CUBE
ORDER BY productid, orderid
GO
USE Northwind
SELECT productid, GROUPING(productid), orderid,
GROUPING (orderid), SUM (quantity) as [total quantity]
FROM orderhist
GROUP BY productid, orderid
WITH CUBE
ORDER BY productid, orderid
GO
Exercises:
1. Show the different years in which players joined the club, use the PLAYRS table.
2. For each year, show the number of players that joined the club
3. For each player who has incurred at least one penalty, give the player number, the
average penalty amount and the number of penalties.
4. For each team that has played in the first division, give the team number, the
number of marches and the total number of sets won.
5. Fro each player who lives in Addis Ababa, list the name, initials, and the number
of penalties incurred by him or her
6. For each team, show the team number, the division and the total number of sets
won.
Laboratory Session 8: Implementing data
integrity/Specifying Constraints\
Objective: After the end of this session, students will be able to:
Describe the types of data integrity
Describe the methods to enforce data integrity
Determine which constraint to use, and create constraints.
Define and use Primary key, foreign key, Check, Unique, and Default constraints.
Disable constraints
Introduction
An important step in database planning is deciding the best way to enforce the integrity of
the data. Data integrity refers to the consistency and accuracy of data that is stored in a
database. The different types of data integrity are: Domain Integrity, Entity Integrity, and
Referential Integrity
Constraints are the preferred method of enforcing data integrity.
Constraints are an ANSI- standard method of enforcing data integrity. Each type of data
integrity – domain, Entity, and referential – is enforced with separate types of constraints.
Constraints ensure that valid data values are entered in columns and that relationship are
maintained between tables.
Creating Constraints
You create constraints by using the CREATE TABLE OR ALTER TABLE statement. You
can add constraints to a table with existing data, and you can place constraints on single or
multiple columns:
If the constraint applies to a single column, it is called a column-level constraint
If a constraint references multiple columns, it is called a table-level constraint, even
if it does not reference all columns in the table.
CREATE TABLE table-name
Column_definition
<table_constraint >
<column_definition>= column_name data type
Default constant_expression
< column_constraint>
CONSTRAINT constraint_name
[Primary key| Unique ]
[clustered | Nonclustered]
Foreign key References ref_table [ref_column]
ON DELETE {CASCADE| NO ACTION}
ON UPDATE {CASCADE| NO ACTION}
CHECK (logical_expression)
Example1. This example creates a constraint in student table.
Create table student
(
StudentID int IDENTITY (1,1) NOT NULL,
StudentName varchar(30) constraint DF_NAME DEFAULT ‘Unknown’
Age int constraint CK_age CHECK (age >=18)
Sex char,
DNO int ,
CONSTRAINT PK_STUDENT PRIMARY KEY(StudentID)
CONSTRAINT FK_STUDENT FOREIGN KEY (Dno) references Department
(Dnumber) ON UPDATE CASCADE ON DELETE CASCADE
)
GO
Consider the following facts when you implement or modify constraints:
You can create, change and drop constraints without having to drop and
recreate a table.
You must build error-checking logic into your applications and transactions
to test whether a constraint has been violated.
SQL Server verifies existing data when you add a constraint to a table.
You must specify names for constraints when you create them, because SQL
Server provides complicated, system-generated names. Names must be
unique to the database object owner and follow the rules of SQL Server
identifiers.
For help with constraints, execute the :
sp_helpconstraint or sp_help system stored procedure
The following system tables store constraint definitions: syscomments,
sysreferences, andsysconstraints
Types of Constraints
1. DEFAULT Constraints
A default constraint enters a value in a column when one is not specified in an INSERT
statement. Default constraint enforce domain integrity
Syntax: CONSTRAINT [constraint name] DEFAULT [constraint expression]
This example adds a DEFAULT constraint that inserts the UNKOWN value in the student
table if a student name is not provided.
USE Northwind
ALTER TABLE Employees
ADD
CONSTRAINT CK_birthdate > ’01-01-1990’ and birthdate < getdate())
Consider the following facts when you apply a PRIMARY KEY constraint:
The values entered must be unique
Null values are not allowed
It creates a unique index on the specified columns. You can specify a clustered or
nonclustered index. Clustered is the default.
The index created for a PRIMARY KEY constraint cannot be dropped directly. It is
dropped when you drop the constraint.
If you want to assign more than one column as a Primary key constraint , you can define
the primary keys when you create the table.
This example creates two primary keys(composite keys) for the CourseRegestraion table.
4. UNIQUE Constraints
A unique constraint specifies that two rows in a column cannot have the same value. This
constraint enforces entity integrity with a unique index.
A unique constraint is helpful when you already have a primary key, such as an employee
number, but you want to guarantee that other identifiers, such as an employee’s driver
license number , are also unique.
Disabling Constraints
When you define a constraint on a table that already contains data, SQL Server check the
data automatically to verify that it meets the constraint requirements. However, u can
disable constraint checking on existing data when you add a constraint to the table.
Consider the following guidelines for disabling constraint checking on existing data:
You can disable only CHECK and FOREIGN KEY constraints. Other constraints
must be dropped and then added again.
To disable constraint checking when you add a CHECK or FOREIGN KEY
constraint to a table with existing data, include the WITH NOCHECK option in
the ALTER TABEL statement.
Use the WITH NOCHECK option if existing data will not change. Data must
conform to CHECK constraints if the data is updated.
Be certain that it is appropriate to disable constraint checking. You can execute a
query to change existing data before you decide to add constraint.
Syntax: ALTER TABLE table
[WITH CHECK| WITH NOCHECK]
ADD CONSTRAINT constraint_name
[FROEIGN KEY ] (column)
REFERENCES ref_table (rer_column)
[CHECK (logical condition)]
In this example, you add a FROEIGN KEY constraint that verifies that all employees are
associated with a valid manager. The constraint is not enforced on existing data at the time
that the constraint is added.
Use Northwind
ALTER TABLE Employees
WITH NOCHEK
ADD CONSTRIANT FK_Employees
FOREIGN KEY (ReportsTo)
REFERENCES Employees(EmployeeID)
Disabling Constraint Checking When Loading New Data
You can disable constraint checking on existing CHECK and FOREIGN KEY constraints
so that any data that you modify or add to the table is not checked against the constraint.
To avoid the costs of constraint checking, you might want to disable constraints when:
You already have ensured that the data conforms t the constraints
You want to load data that does not conform to the constraints. Later, you can execute
queries to change the data and then re-enable the constraints.
Disabling constraints on one table does not affect constraints on other tales that reference
the original table. Updates to a table still can generate constraint violation errors.
Enabling a constraint that has been disabled requires existing another ALTER TABLE
statement that contains either a CHECK or CHECK ALL clause
Syntax: ALTER TABLE table
[CHECK | NOCHECK] CONSTRIANT
ALL| constraint
This example disables the FK_Employees constraint. It can be reenabled by executing
another ALTER TABLE statement with the CHECK clause.
USE Northwind
ALTER TABLE Employees
NOCHECK
CONSTRAINT FK_Employees
Grade
Department
Student
Exercises
You join tables to produce a single result set that incorporates rows and columns from two
or more tables.
Syntax: Select columnName
From table name INER, LEFT, RIGHT, FULL, OUTER, CROSS JOIN
On table name
A join allows you to select columns from multiple tables by expanding FROM clause of the
SELECT statement. Two additional keywords are included in the FROM clause: - JOIN
and ON
The JOIN keyword specifies which tables are to be joined and how to join them
The ON keyword specifies which columns the tables have in common
Queries Two or More Tables to Produce a Result Set
A join allows you to query two or more tables to produce a single result set. When you
implement joins, consider the following facts and guidelines:
Whenever possible, specify the join condition based on the primary and foreign
keys; however, you may use any other columns if required.
It is advisable to use entire key in the ON clause when you join tables
Use columns common to the specified tables to join the tables. These columns should
have the same or compatible data types
Try to limit the number of tables in a join, since SQL takes to much time to process
the query
You can join one or more tables in a single SELECT statement
Example : Retrieve the employees name, salary and the employees department
Select, eName, salary, dName
From EMPLOYEE INNER JOIN DEPARTMENT ON
EMPLOYEE.Dnum =Department.DNO
Using Outer Join
Left or Right outer joins combine rows from two tables that match the join condition, plus
many unmatched rows of either the left or right table is specified in the JOIN clause.
Rows the do not match the join condition deplays NULL in the result set.
You can use full outer joins to display all rows in the joined tables, regardless of whether
the tables have any matching values.
Retrieve the name of project and its location and the name of the controlling department
Select ProiectName, location, DName
FROM Department LEFT OUTER JOIN Project
ON Department.Dno S
List all possible combinations of the values in the employee name and the department name
Exercises
1. Retrieve the name and address of all employees who work for the
‘Research’ department.
2. For each employee, retrieve the employee’s first and last name and the first
and last name of his or her immediate supervisor
3. For every project located in ‘Stafford’ list the project number, the
controlling department number, and the department manager’s last name,
address, and birthdates.
Laboratory Session 10: Subqueires
Objectives: At the end of this lesson students will be able to:
Describe when and how to use a subquery
Use subqueries to break down and perform complex queries
Discuss how correlated queries are processed.
A subquery is a SELECT statement nested inside a select , insert , update or Delete
statement or inside another subquery. Often you can rewrite subqueries as joins and use
subqueries in place of an expression.
An expression is a combination of identifiers, values, and operations that SQL server
evaluates to obtain a result.
You use subqueries to break down a complex query into a series of logical steps and, as a
result, to solve a problem with single statements. Subqueries are useful when your query
relies on the results of another query.
This example uses a subquery to create a derived table in the inner part of the query that the
outer part queries. The derived table itself is functionally equivalent to the whole query, but
it is separated for illustrative purposes
Use northwind
Select T. ordered, T. CusomerID
From (Seelct Orderid, customerid)
From Orders) as T
When used as a derived table, consider that a subquery;
Is a record set within a query that functions as a table
Takes the place of a table in the FROM clause
Is Optimized with the rest of the query
In Transact-SQL you can substitute a subquery wherever you use an expression. The
subquery mist evaluate to a scalar value, or to a single column list of values. Subqueries
that retune a list of values replace an expression in Where CLAUSE THAT CONATINS
the IN keyword.
When used as an expression, consider that a subquery:
Is evaluate and treated as an expression. The query optimizer often evaluates an
expression as equivalent to a join connecting to a table that has one row
Is executed once for the entire statement
This example returns the price of a popular computer book, the average price of all books
and the difference between the price of the book and the average price of all books.
Use pubs
Select title, price
(Select avg(price) from titles) as average
Price-(select avg(price From titles as difference )
From titles
Where type= ‘popular_comp’
Go
You can use a correlated subquery as a dynamic expression that changes for each row of an
outer query
The query processor performs the subqurey for each row in the outer query, one row at a
time, which is in turn evaluate as an expression for that row and passed to the outer query.
The correlated subquery is effectively a JOIN between the dynamically executed subquery
and the row from the outer query.
You can typically rewrite a query in a number of ways and still obtain the same results.
Correlated subqueries break down complex queries into tow or more simple, related
queries.
When you create a correlated subquery, the inner subqueries are evaluated repeatedly, once
for each row of the outer query:
SQL server executes the inner query for each row that the outer query selects.
SQL server compares the results of the subquery to the results outside the subquery
This example returns a list of customers who ordered more than 20 pieces of product
number 23.
Use Northwind
Select ordered, customerid
From orders as or1
Where 20< (select quantity
From [ofder_detaisl ] as od
Where or1.orderid = od. Ordered
AND od. Productid= 23)
Correlated subquery return a single value or a list of values for each row specified by the
FROM clause of the outer query. The following steps describe how te correlated subquery
is evaluated in the above example.
1. The outer query passes a column value to the inner query
The column value that the outer query passes to the inner query is the orderid. The
outer query passes the first orderid in the orders table to the inner query.
2. The Inner query uses the values that the outer query passes
Each ordered in the orders table sis evaluated to determine whether an identical
orderid in the order_detail table and that ordered purchased product number 23,
and then the inner query returns that orderid to the outer query.
3. The inner query returns a value back to the outer query.
The WHERE clause of the outer query further evaluates the orderid that purchased
product number 23 to determine whether the quantity ordered exceeds 20.
4. The Process is repeated for the next row of the outer query.
The outer query passes the second orderid in the orders table to the inner query,
and SQL Server repeats the evaluation process for that row.
Example 2: This example returns a list of products and the largest order ever placed
for each product in the order_details table. Notce that this correlated subquery
references the same table as the outer query; the optimizer will generally treat this
as a self- join.
USE NORTHWIND
SELECT DISINCT productid, quantity
FROM order_detail as od1
WHERE quantity = ( SELECT max(quantity)
FROM order_details as od2
WHERE od1.productid = ord2.productid)
GO
Similarly, an ANY condition evaluates TRUE if and only if the corresponding comparison
condition without the ANY evaluates to TRUE for any of the rows in the table represented
in the table expression. If the table is empty, then the ALL condition returns TRUE while
the ANY condition returns FALSE.
Consider the following query: Get the names of all the books whose price is greater than
the maximum of the category averages. For the above query, first you will have to find the
average price of the book in each of the categories, then the maximum fo those category
averages and then find the titles whose price is greater than the maximum category. Here is
how it is implemented.
Select title
From catalog
Where price > ALL (Select avg (price)
From catalog
Group by Category)
The format of ALL and ANY are, as we have seen , ‘ x comparison operator ALL.(table-
expression)’ and ‘ X comparison operator ANY(table expression)’
When a subquery is introduced with the EXISTS operator, SQL Server tests whether data
that matches the subquery exists. No rows are actually retrieved.
When SQL Server processes subqueries that use the EXISTS OR NOT EXISTS operator:
The outer query tests for the existence of rows that the subquery returns.
The subquery returns either a TRUE or FALSE VALUE based on the given
condition in the query.
The subquery does not produce any data.
Example 1: This example depicts that the player number 10 played team number and the
division the team is located.
Example 2: Find each player for whom no team exists in which the player concerned has
never played.
SELECT PLAYERNO
FROM PLAYER AS P
WHERE NOT EXISTS
(SELECT *
FROM TEAMS AS T
WHERE NOT EXISTS
(SELECT *
FROM MATCHES AS M
WHERE T.TEAMNO=M.TEANO
AND P.PLAYERNO=M.PLAYRno
)
Exercises
1. Give the name of each player who has played for a first division team, who has
won at least one match and who has not incurred a single penalty.
2. Give the number and name of each player who has played for both first and
second team
3. Find the team number and division of each team in which player 44 has played.
4. Retrieve the number and the name of each player who has not played matches
for team 1.
5. Give the team number of each team in which player 10 has not played.
6. Find the player number and name of each player who has won at least two
matches.
7. Give the name of each player who incurred no penalties between 1 January
2002 and 31 December 2002.
Laboratory Session 11: Modifying Data
Objectives: at the end of this lesson students will be able to:
Describe how students can use transactions to modify data.
Explain that rows can be inserted by using the DEFAULT values keywords to save
time during data entry
Describe modifying data by using the INSERT…SELECT statement, as well as
deleting and updating rows that are based on other tables by using subqueries
Discuss the use of the DELETE and TRUNCATE TABLE statement to remove
rows.
Use INSERT, UPDATE, and DELETE statement to modify the rows of data.
Using Transactions
A transaction is a sequence of operations performed as a single logical unit of work. SQL
programmers are responsible fro starting and ending transactions at points that enforce the
logical consistency of the data.
Starting Transactions
You can start transactions in MSSQL Server in one of three modes:
Explicit transactions start by issuing a BEGIN TRANSACTION statement
Autocommit transactions are the default for SQL Server. Each individual Transact-
SOL statement is committed when it completes. You do not have to specify any
statements to control transactions.
Implicit transactions mode is set by an application programming interface (API)
function or the Transact-SQL SET IMPLICIT_TRANSACTIONS ON statement.
Using this model, the next statement automatically starts a new transaction. When
that transaction completes, the next Transact_SQL statement starts a new
transaction.
Ending Transactions
You can end transactions by using a COMMIT or ROLLBACK statement.
The COMMIT statement indicates that if a transaction is successful, SQL Server
should commit it. A COMMIT statement guarantees that all of the transaction\s
modifications are permanently part of the database. A COMMIT statement also
frees resources, such as locks, that the transaction uses.
UPDATE Penalty
SET AMOUNT = AMOUNT *2
WHERE PlayerNo= 4
IF @@error <> 0
BEGIN
RAISERROR (‘Error, transaction not completed!’,16, -1)
ROLLBACK TRANSACTION
END
Inserting Data
You can insert data through a transaction by specifying a set of values or inserting the
results of a SELECT statement. You can create a table and insert a data simultaneously.
You do not have to insert values into all data fields within a row.
Use the INSERT statement with the VALUES clause to add rows to a table. When you
insert rows, consider the following facts and guidelines:
Must adhere to destination constraints or the INSERT transaction fails
Use the column_list to specify columns that will store each incoming value. You
must enclose the column_list in parentheses and delimit it by commas. If you are
supplying values for all columns, using the column_list is optional.
Specify the data that you want to insert by using the VALUES clause. The
VALUES clause is required for each column in the table or column_list.
The column order and data type of new data must correspond to the table column order
and data type. Many data types have an associated entry format. For example,
character data and dates must be enclosed in single quotation marks.
Deleting Data
The Delete statement removes one or more rows from a table or view by using a
transaction. You can specify which rows SQL Server deletes by filtering on the targeted
table, or by using a JOIN clause or a subquery. The TRUNCATE TABLE statement is used
to remove all rows from a table.
This example uses a join operation with the DELETE statement to remove rows
from the Penalty table for the players’ birth date on 4/14/1984.
USE FOOTBALL_LEAGUE
GO
DELETE FROM PENALTY
FROM player as PL
Inner join penalty as P
ON PL. PlayerNo = P.PlayerNo
WHERE birth_date = ‘4/14/1998’
USE FOOTBALL_LEAGUE
DELETE FROM [penalty]
WHERE PlayerNo IN (
SELECT PlayerNo
FROM Player
WHERE birthDate =’4/14/1984’)
Updating Data
The UPDATE statement can change data values in single rows, groups of rows , or all rows
in a table or view. You can update a table based on data in the table or on data in other
tables.
Updating Rows Based on Data in the Table
The UPDATE statement modifies existing data.
Exercises:
1. Create a table the same as TEAM table but with out the division column.
2. Populate the table that you created with the appropriate data
3. Using INSERT INTO command insert the values to the new table from the TEAM
table.
4. increase all penalties by 15%
5. Delete all penalties incurred by player 8 in 2002
6. Delete players who live in the same town as player 8, but keep the data about player 8
7. Change the value F in sex column of the players table to W (woman)
8. Increase by 20 percent all penalties higher than the average penalty
Laboratory Session 12: Virtual Table (Views)
Objectives: At the end of this lesson students will be able to:
A view provides the ability t store a predefined query as an object in the database for later
use. The tables queried in a view are called base tables. With a few exceptions, you can
name and store any SELECT statement as a view. Common examples of views are:
A subset of rows or columns of a base table
A union of two or more base tables
A join of two or more base tables
A statistical summary of a base table
A subset of another view, or some combinations of views and base tables
Advantages of Views
Views offer several advantages, including focusing data for users, making data complexity,
simplifying permission management, and organizing data for export to other applications.
Creating Views
You can create views by using the Create View Wizard, SQL Server Enterprise Manager,
or Transact-SQL. You can create views only in the current database.
When you create a view, MSSQL Server verifies the existence of objects that are
referenced in the view definition. Your view name must follow the rules for identifiers.
Specifying a view owner name is optional. You should develop a consistent naming
convention to distinguish views from tables.
Altering View
USE Football_league
GO
The ALTER VIEW statement changes the definition of a view, including indexed views,
without affecting dependent stored procedures or triggers. This allows you to retain
permissions of the view. This statement is subject to the same restrictions as the CREATE
VIEW statement. If you create a view and recreate it you must reassign permissions to it.
Syntax: CREATE VIEW owner view_name [column]
WITH ENCRYPTION
AS
Select_statement
[WITH CHECK OPTION]
Note: if you use the WITH CHECK OPTION, WITH ENCRYPTION, WITH SCHEMA –
BINDING, WITH VIEW_METADATA option when you create the view, you must
include it in the ALTER VIEW statement if you want to retain the functionality that the
option provides.
The following example alters Player_information view to add the name column
USE FOOTBALL_LEAGUE
GO
Dropping View
If you no longer need a view, you can remove its definition from the database by executing
the DROP VIEW statement. Dropping a view removes its definition and all permissions
assigned to it.
USE FOOTBALL_LEAGUE
GO
DROP VIEW Player_InformatGFion
The BEGIN_AGE column in the following view may not be updated (though the PlayerNo
column maybe updated):
Exercises:
1 Create a view called NUMBERPLS that contains all the team numbers and the
total number of players who have played for that team.
2 Create a view called WINNER tht contains the number and name of each
player who, for at least one team, has won one match.
3 Create a view called TOTALS that records the total amount of penalties for
each player who has incurred at least one penalty.
4 Remove the view called TOWN that you have created last time.
5 Does the following update operations (update, insert, and delete operations)
peroformed for the PenaltyStatusView?
Laboratory session 13: User Defined Function
Objectives: At the end of this lesson (lab session), students will be able to:
Create and alter used defined functions
Describe different types of functions
Use the functions in their daily life
Creating a Function
You create user-defined functions by using the CREATE FUNCTION statement. Each
fully qualified user defined function name (database_name.owner_name. function_name)
must be unique. The statement specifies the input parameters with their data types, the
processing instructions, and the value returned with each data type.
CREATE FUNCTION function_name
@parameter_name scalar_parametr_ data_type
RETURNS scalar_return_data_type
WITH <function_option>
AS
BEGIN
Function Body
RETURN sacalar_expression
END
This example creates a user defined function to replace a null value with the words Not
Applicable
USE Northwind
GO
CREATE FUNCTION fn_NewRegion
(@myinput varchar (30))
RETURNS varchar(30)
BEGIN
If @myinput is null
SET @myinput =’Not Applicable’
RETURN @myinput
END
When referencing a scalar user defined function, specify the function owner and the
function name in two-part syntax
SELECT LastName, City, dbo.fn_NewRegion(Region) AS Region, Country
FROM Employees
Restrictions of Functions
Nondeterministic functions are functions, such as GETDATE(), that could return different
results values each time that they are called with the same set of input values. Built-in
nondeterministic functions are not allowed in the body of user-defined functions. The
following built-in functions are nondeterministic.
@@ERROR FORMATMESSAGE USER_NAME
@@IDENTITY GETANSINULL NEWID
@@ROWCOUNT GETDATE PERMISSIONS
@@TRANCOUNT etc
Altering Functions
You modify a user-defined function by using the ALTER FUNCTION statement
Syntax : ALTER FUNCTION function_name
<New Function Content>
Dropping Functions
You can drop a user-defined function by using DROP FUNCTION statement.
END
You can call a scalar user-defined function in the same way that you do a built-in function.
You can create function by using many statements that perform complex operations.
This example creates a multi-statement table-valued function that returns thee last name or
both the first and last names of employees, depending on the parameter provided.
USE Northwind
GO
CREATE FUNCTION fn_Employees
(@length varchar(9))
RETURNS @fn_Employee TABLE
(EmployeeID int Primary Key Not Null,
[Employee Name] varchar (16) Not Null)
AS
BEGIN
IF @length =’ShortName’
INSERT @fn_Employees SELECT EmployeeID, LastName
FROM Employees
ELSE IF @length =’LongName’
INSERT @ fn_Employees SELECT EmployeeID,
(FirstName + ‘ ‘ + LastName) FROM Employees
RETURN
END
You can call the function instead of a table or view.
Exercises
11Create a function which gives GPA of a student when you give his/her Id no.
11Create a function that gives its factorial when you give the number..
11Create a function which gives you the maximum of the sequence of numbers.
11Create a function which displays the information of a student
Laboratory session 14: Stored Procedures
Objective: At the end of this lesson (lab session) students will be able to:
Describe how a stored procedure is processed
Create, execute, modify, and drop a stored procedure
Create stored procedures that accept parameters
Execute extended stored procedures
Create custom error messages.
Appreciate the performance of the stored procedures
A stored procedure is a certain piece of code (the procedure), consisting of declarative and
procedural SQL statements stored in the catalog of a database that can be activated by
calling it from a program, a trigger or another stored procedure.
Each stored procedure consists of at least three parts: a list of parameters, a body and a
name.
The procedure above has only one parameter called PNO_VAR (the player number). The
word IN indicates that this parameter is an input parameter. After the execution of the
procedure the value of PNO_VAR will be unchanged.
Between the keyword BEGIN and END the so-called procedure body of the procedure is
specified.
The names of the stored procedure within the database have to be unique, just like the name
of users.
Stored procedures are a method of encapsulating repetitive tasks. Stored procedures
support user declared variables, conditional execution, and other powerful programming
features.
SQL Server supports five types of stored procedures;
System stored procedure
Local stored procedure
Temporary stored procedure
Remote stored procedure
Extended stored procedure
Stored procedure in SQL Server is similar to procedures in other programming languages,
in that they can:
Contain statements that perform operations in the database, including the ability to
call other stored procedures
Accept input parameters
Return a status value to a calling stored procedure or batch to indicate success or
failure ( and the reason for failure)
Return multiple values to the calling stored procedure or batch in the form of output
parameters.
USE Northwind
GO
CREATE PROC OverDueOrders
AS
SELECT *
FROM orders
WHERE RequiredDate < GETDATE() AND ShippDate IS NULL
Example 2: This stored procedure removes all matches played by a specified player.
CREATE PROCEDURE DELETE_MATCHES
(PNO_VAR IN INT ) AS
BEGIN
DELETE
FROM MATFHES
WHERE PLAYERNO = PNO_VAR
END
WITH RECOMPILE
The following statement execute a stored procedure that lists all overdue orders in the
Northwind database.
EXEC OverdueOrders
USE Northwind
GO
Create proc EmploeeCustomer
As
Select
UPPER (SUBSTRING (LastName, 1,4) + SUBSTRING (FirstName, 1,1)
‘Northwind Traders’, RTRIM (FirstName) +’ “ + LastName, ‘Employee’, address,
City, Region, PostalCode, Country, (‘(206) 555-1234’ + x ‘+ Extension), null
FROM Employees
WHERE HireDate < GETDATE()
GO
The following statement execute the EmployeeCustomer stored procedure
AS
Sql_statement
Example: The following example modifies the OverdueOrders stored procedure to select
only specific column names rather than all columns from the Orders table, as well as to sort
the result set.
USE Northwind
GO
ALTER PROC OverdueOrders
AS
Select CONVERT (char (8), RequiredDate, 1) RequriedDate,
CONVERT (char (8), OrderDate, 1) OrderDate
OrderID, CustomeID, EmployeeID
FROM Orders
WHERE RequiredDate < GETDATE() AND ShipDate IS NULL
ORDER BY RequiredDate
GO
Exercises:
1. Create a stored procedure to calculate, for a player, the number of teams and the
number of actual positions on the committee. These two numbers must form the
output parameters of the stored procedure
2. Create a stored procedure that creates the TEAMS table of the user SQLDBA if
does not exist already.
3. Create a stored procedure that can show FiveMostExpensiveProducts in the
products table from the Northwind database.
4. Display the information of the FiveMsotExpensiveProducts
Laboratory session 15: Triggers
Objectives: At the end of this lesson students will be able to:
Create, alter and delete a trigger
Recognizes the use of a trigger in the database systems
Describe the use of triggers
Discuss some of the facts and guidelines that implementers must consider when
determining whether to use triggers instead of other tools.
Introduction
A Trigger is a special kind of stored procedure that executes whenever an attempt is made
to modify data in a table that the trigger protects. Triggers are defined to specific tables. It
is referred to as the trigger table.
When an attempt is made to insert, update, or delete data in a table, and a trigger for that
particular action has been defined on the table, the trigger executes automatically. It cannot
be circumvented.
Unlike standard stored procedures, triggers cannot be called directly and do not pass or
accept parameters.
Most triggers are reactive; constraints and the INSTEAD OF trigger are proactive.
Triggers are executed after an INSERT , UPDATE , or DELETE statement is
executed on the table in which the trigger is defined. For example, an UPDATE
statement updates a row in at able, and then the trigger on that table executes
automatically. Constraints are checked before an INSERT, UPDATE, or
DELETE statement executes.
Constraints are checked first.
If constraints exist on the trigger table, they are checked prior to the trigger
execution. If constraints are violated, the trigger does not execute.
Tables can have multiple triggers for any action
Triggers can handle multi-row actions.
o An INSERT , UPDATE , or DELETE action that invokes a trigger can
affect multiple rows. You can choose to :
Process all of the rows together, in which case all affected rows must
meet the trigger criteria for any action to occur
Allow conditional actions
Creating Triggers
Create triggers by using the CREATE TRIGGER statement. The statement specifies the
table on which a trigger is defined, the events for which the trigger executes, and the
particular instructions for the trigger.
The following example creates a trigger on the Employees table that prevents users from
deleting more than one employee at a time. The triggers fires every time a record or group
of records are deleted from the table. The triggers checks the number of records being
deleted by querying the Deleted table. If more than one record is being deleted, the trigger
returns a custom error message and rolls back the transaction.
Use Northwind
GO
Create TRIGGER Emp_Delete ON NewEmployees
FOR DELETE
AS
IF(SELECT COUNT(*) FROM Deleted) >1
Begin
RAISERROR (
‘You cannot delete more than one employee at a time.’,
16. 1)
ROLLBACK TRANSACTION
END
Altering a Trigger
If you want to change the definition of the existing trigger, you can alter it without having
to drop it.
The altering definition replaces the definition of the existing trigger with the new
definition. Trigger action also can be altered. For example, if you create a trigger for
INSERT and then change the action to UPDATE, the altered trigger executes whenever the
table is updated.
Sql_statement […n]}
FOR [INSERT],[UPDATE]
AS
IF UPDATE(column)
[{AND|OR} UPDATE(column)[,..n]]
Sql_statement […n]}
{FOR{[,] [INSERT] [,] [UPDATE]}
[NOT FOR REPLICATION]
AS
IF UPDATE(column)
[{AND|OR} UPDATE (column) [,…n]]
Sql_statement […n]}
}
This example alters the delete trigger created in the previous example. New trigger content
is provided, which changes the delete limit from one record to six records.
Use Northwind
Go
Create trigger empl_Delete ON Employees
FOR DELETE
AS
IF (Select count (*) From Deleted) > 6
Begin
Raiserror(
‘You cannot delete more than six employees at a time.’,
16,1)
Rollback Transaction
END
Dropping a Trigger
You can remove a trigger by dropping it. Triggers are dropped automatically whenever
their associated tables are dropped.
You can define a trigger to execute whenever an INSERT statement inserts data into a
table.
When an INSERT trigger is fired, new rows are added to both the trigger table and the
inserted table. The Inserted table is a logical table that holds a copy of the rows that have
been inserted. The inserted table allows you t reference logged data from the initiating
INSERT statement. The trigger can examine the inserted table to determine whether , or
how, the trigger actions should be carried out. The rows in the inserted table are always
duplicates of one or more rows in the trigger table.
The trigger in this example was created to update a column (UnitsInStock) in the products
table whenever a product is ordered (whenever a record is inserted into the ORDER
DETAILS table). The new value is set to the previous value minus the ordered amount.
Use Northwind
Create trigger orderDet_Insert
ON [Order Detail]
FOR INSERT
AS
UPDATE P SET
unitsInstock= (P.UnitsInStock – I. Quantity)
FROM Products AS P INNER JOIN Inserted AS I
ON P.ProductID = I.ProductID
Example: This trigger in this example was created to update a column (UnitsInStock) in
the Products table whenever a product is ordered (whenever a record is inserted into the
Order Details table). The new value is set to the previous value minus the ordered amount.
USE Northwind
CREATE TRIGGER OrdeDet_Insert
ON [Order Details ]
FOR INSERT
AS
UPDATE P SET
UnitsInStock = (P.UnitInStock – I. Quantity)
FROM Products as P INNER JOIN Inserted as I
ON P. ProductID= I.ProductID
When a row is appeared to the deleted table, it no longer exist in the database table,
therefore the deleted table and the database tables have no rows in common
Space is allocated from memory to create the deleted table. The deleted table is
always in the cache.
A trigger that is defined for a DELETE action does not execute for the
TRUNCATE TABLE STATEMENT because TRUNCATE TABLE is not logged.
The trigger in this example was created to update the Discontinued column in the
Products table whenever a category is deleted ( whenever a record is deleted from the
Categories table). All affected products are marked as 1, including they are discontinued.
USE Northwind
CREATE TRIGGER category_Delete
ON Categories
FOR DELETE
AS
UPDATE P SET Discontinued =1
FROM Products AS P inner join deleted as d
On p. categoriyID = d. categoryID
This example prevents a user form modifying the EmployeeIds column in the Employees
table
USE Northwind
GO
CREATE TRIGGER Employee_Update
ON Employees
FOR UPDATE
AS
IF UPDATE (EmployeeID)
BEGIN TRANSACTION
RAISERROR (‘Transaction cannot be processed.\
***** Employee ID number cannot be modified.’)
ROLLBACK TRANSACTION
END
1. Create a trigger that guarantees that the sum of all penalties for one player is not
more than 250 Birr
4. Create a trigger called BIRTHJOINED that the year of birth of a player is at least
lower than the year he or she joined the club
5. Remove the BIRTHJOINED trigger.
Appendix
A. Foot ball League Database
statement_no member_no
status
status_code
member_no member * payment_due_dt
statement_code state_prov
country
mail_code
phone_no