Implementing A Database Design Using Microsoft SQL Server
Implementing A Database Design Using Microsoft SQL Server
This course focuses on implementing a database design using Microsoft SQL Server. It begins with an
introduction to databases, and moves on to other features of SQL Server. Structured Query Language
(SQL) that is used to retrieve and maintain data is covered in great detail. The course also deals with
other features of SQL Server, such as constraints, rules, defaults, indexes, views, stored procedures,
triggers, and transactions.
A student should have knowledge on the following topics before starting with the SQL Server module:
Build Flowcharts – the student should be able to represent logic, sequence tasks for execution, and
implement conditional operations and iteration. This will be essential for programming using SQL
Server.
Work in a Windows environment – the student should be able to navigate in a Windows
environment. SQL Server is Windows-based and hence, knowledge of the same is critical.
Create and maintain documents – the student should be able to use an editor and should be able to
perform simple editing tasks. SQL server scripts will be stored in text files and hence, this
knowledge is essential.
• Querying Databases
• Subqueries
• Maintaining Databases
• Implementing Indexes
• Implementing Cursors
Objectives
Following are the objectives for the Microsoft exam on Designing and Implementing Databases with
Microsoft SQL Server 2000 Enterprise Edition.
Developing a Logical Data Model
Specify entity attributes.
Specify degree of normalization.
Specify attributes that uniquely identify records.
Specify attributes that reference other entities.
Specify scale and precision of allowable values for each attribute.
Allow or prohibit NULL for each attribute.
Specify allowable values for each attribute.
Implementing the Physical Databases
Specify space management parameters. Parameters include autoshrink, growth increment, initial
size, and maxsize.
Specify file group and file placement. Considerations include logical and physical file placement.
Specify transaction log placement. Considerations include bulk load operations and performance.
Specify table characteristics. Characteristics include cascading actions, CHECK constraints,
clustered, defaults, FILLFACTOR, foreign keys, nonclustered, primary key, and UNIQUE
constraints.
Specify schema binding and encryption for stored procedures, triggers, user-defined functions, and
views.
Specify recompile settings for stored procedures.
Specify index characteristics. Characteristics include clustered, FILLFACTOR, nonclustered, and
uniqueness.
Support merge, snapshot, and transactional replication models.
Design a partitioning strategy.
Design and create constraints and views.
Resolve replication conflicts.
Retrieving and Modifying Data
Import and export data. Methods include the bulk copy program, the Bulk Insert task, and Data
Transformation Services (DTS).
Manipulate heterogeneous data. Methods include linked servers, OPENQUERY, OPENROWSET,
and OPENXML.
Retrieve, filter, group, summarize, and modify data by using Transact-SQL.
Manage result sets by using cursors and Transact-SQL. Considerations include locking models
and appropriate usage.
To conduct the SQL 2000 course, the following databases need to be installed:
Recruitment
GlobalToyz
Note: Before you run these scripts, you need to edit the scripts and change the server name to the name of
the machine on which SQL Server is installed. You should back up these databases so that they can be
restored later.
A brief description of the various scripts and their content is given below.
Scripts Description
Before every OCR and Unguided Practice session, the faculty needs to drop the database and restore the
backed up copy using the Enterprise Manager of Microsoft SQL Server.
Note: You can also reinstall the database but it takes less time to restore a database than to install it.
You need to modify the script to be able to execute the script. For example, If the name of your server
is NIIT-RG-MR and the sa login does not have any password, you need to modify the script to:
Important: Even though sa has the password as secret, the last two lines do not have any passwords.
They just contain -P. This is because these would create the schema for all the users individually.
Q) Why should I execute the batch file and not directly execute the sql scripts?
Answer) The batch file uses a for loop to create 30 copies of the same tables. If you execute the script
by loading it in the Query analyzer, you would just get one copy of the tables. Thirty copies are
required as all the users should have there own copy of the tables. In case you don't create 30 copies, if
one person drops a table, the other person would not be able to use that table.
Q) If one user, say user1, drops a table, say Employee, then can another user, say user2, drop the same
table?
Q) Can students use the Enterprise Manager without using the sa login?
Answer) Yes, students should use logins user1, user2, user3... etc. to connect to the SQL server from
the Enterprise Manager. To change a user name while connecting to the server, right click the SQL
server and click the Edit SQL Server Properties option. In the dialog box, enter the new user name with
which you want to connect to the SQL server.
Q) What should I do if the table that needs to be created is already present in the database?
Answer) In case you have executed CREATERECRUITMENTDB.SQL or
CREATEGLOBALTOYZDB.SQL, you would not be able to drop any tables without removing the
constraints. In case you have executed
CREATEGLOBALTOYZOBJECTSWITHOUTCONSTRAINTS.SQL or
CREATERECRUITMENTOBJECTSWITHOUTCONSTRAINT.SQL you can drop any table as the
database does not contain any constraints.
Lesson 1, INSTALLRECRUITMENTDB.BAT It would create the tables along with all the
2, 3, and 4 constraints. You would not be able to delete any
table unless the relationships are deleted. You
should use this script for these lessons as these
lessons are related to queries and all the tables must
exist for the queries to be executed.
Lesson 6, INSTALLRECRUITMENTDBWIT When you execute this script all the tables would
7, 8, 9, 10, HOUTCONSTRAINT.BAT get created but without any constraints. They would
11, and 12 not have any primary key - foreign key relationship.
This is done so that you can alter the structure of the
tables. In case you are creating a table that already
exists in the database, you need to delete it.
Lesson One
Experiences
Simple Queries
Stress on the fact that if the student wants to visualize the output required, it would be easier to
create the query. Also, ask them to compare the output with the required results.
Stress on the fact that when specific columns are mentioned in the select list, then the output is
nothing but a column subset. Similarly, when the WHERE clause is used, the output is a row
subset.
Stress on writing the SQL statement in separate lines in the Query Analyzer window. It becomes
easy to read and debug.
Multiple Conditions
Mention that multiple conditions can be used to retrieve data from a table, and you can do this by
using the logical operators.
Cover an example where the AND and OR operators are used in a single query.
FAQ
Q: What is the difference between T-SQL and PL-SQL?
Transact- SQL (T-SQL) is a scripting language used in SQL Server 2000 for programming. T-
SQL confirms to the ANSI SQL-92 standard published by American National Standards Institute
(ANSI) and International Organization for Standardization (ISO) in the year 1992. PL-SQL on the
other hand is used for programming in Oracle.
Additional Inputs
The different types of DML statements are SELECT, INSERT, UPDATE, and DELETE.
Operator precedence levels are as follows: for arithmetic operators, the precedence is ‘*’, ‘/’, ‘,’,
‘%’, ‘-’, ‘+’. For logical operators, it is NOT, AND, and OR. As it is obvious, the precedence
levels can be changed by the use of ‘( )’.
vFirstName
vLastName
siTestScore
dTestDate
SELECT
vFirstName,vLastName,siTestScore,dTestDate
FROM ExternalCandidate
WHERE dTestDate between '03/05/01' and
'03/12/01'
Lesson Two
Experiences
ORDER BY Clause
Aggregate Functions
Tell the students that aggregate functions are used to count or to find out the average of a
particular column, do not forget to tell the students that these should only be used on numeric
columns. Besides, when an aggregate function is used on a column, NULL values are not
considered.
GROUP BY Clause
Tell the students that the GROUP BY clause is used to group the output of the SELECT statement
in several groups. If ALL is used, then it ignores the restriction provided by the WHERE clause.
Just like the WHERE clause, you can use the HAVING clause with the GROUP BY clause.
Examples
Example of the usage of the HAVING clause:
The following code displays the titles and types of all titles whose type is either business or
mod_cook grouped by type from the titles table:
select type,title from titles
group by type, title
having type = 'business'
or type = 'mod_cook'
TOP
Stress that the TOP keyword is used to retrieve the top few records, as they exist in the table. If
you require the top few records with respect to a sort order of a particular column, then you need
to include the ORDER BY…DESC keywords in the SELECT statement.
COMPUTE BY clause
Stress that the COMPUTE BY clause is used to generate totals and subtotals in a control break
report.
Additional Inputs
Image, text, and ntext columns cannot be used in an ORDER BY clause.
When using DISTINCT, only the name of a column can be used, an arithmetic expression gives an
error.
MAX and MIN functions cannot be used on the bit data type columns.
All columns mentioned in the GROUP BY clause have to be included in the SELECT list. If a
WHERE clause is present, then the GROUP BY clause groups only those rows which are satisfied
by the conditions used in the WHERE clause.
The TOP keyword displays records from the table as they exist in the table. Use the ORDER BY
clause to display the top few records based on the values of a particular column.
With the TOP keyword you can use the WITH TIES keywords to display rows having equal
values. This cannot be used without the ORDER BY clause.
The columns that are mentioned in the COMPUTE clause need to be part of the SELECT list.
Use an ORDER BY clause with the COMPUTE BY clause so that rows are grouped together.
Example
1 Question: Write a query to display the details of all the contract recruiters
whose names begin with “J”.
Answer:
Select * from ContractRecruiter
WHERE cName LIKE 'J%'
3 Question: A list of external candidates who took a test, along with their
test scores, is required. The average of the test scores needs to be printed
at the bottom of the list.
Answer:
SELECT vFirstName, siTestScore
FROM ExternalCandidate
COMPUTE AVG (siTestScore)
Lesson Three
Experiences
String Functions
Mention that the string functions are used to manipulate data of character type columns.
Date Functions
Tell the students that the date manipulation is done using the date functions.
Mathematical Functions
Mathematical calculations and manipulation can be done using the mathematical functions.
Wildcard Characters
Mention that if a particular character pattern is being searched for, the wildcard characters can be
used along with the LIKE keyword.
Inner Joins
The INNER JOIN returns all rows from both tables where there is a match. If there are rows in
Supplier that do not have matches in Orders, those rows will not be listed. It is the most common
type of join.
For Example,
SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date
FROM suppliers, orders
WHERE suppliers.supplier_id = orders.supplier_id;
The INNER JOIN operation can be used in any FROM clause to combine records from two tables.
There must be a matching value in a field common to both tables.
Equi Joins
Conceptually equijoin is same as inner join and is used to list all the columns from the joining
tables. The equi join joins tables across a foreign key link.
For Example,
SELECT * FROM authors A, titleauthor B WHERE A.au_id = B.au_ID
Output:
The output contains duplicate columns across join tables. To remove this ambiguity in the
output, you can use Natural join.
Additional Inputs
Text, ntext, and image data type columns cannot be joined directly.
An OUTER join can be performed between two tables only.
GROUP BY can have CUBE operators to generate aggregate values.
The HOST_ID() system function returns the identification number of you SQL Server terminal or
workstation.
The SUSER_SNAME() system function takes the login identification number of the user as a
parameter and returns the login name of the user.
The DB_NAME() system function takes the database identification number as a parameter and
returns the name of the database. For example, SELECT DB_NAME(1) returns Master.
3 Question: The names of candidates and the newspapers they referred for
recruitment advertisements are required for an analysis. A report
displaying these details is to be generated.
Answer:
SELECT vFirstName, vLastName, cNewspaperName
FROM ExternalCandidate JOIN NewsAd
ON ExternalCandidate.cNewsAdNo = NewsAd.cNewsAdNo
JOIN Newspaper
ON NewsAd.cNewspaperCode =
Newspaper.cNewspaperCode
Lesson Four
Experiences
Unions
Do not forget to mention the restrictions on unions to the students.
Example
The following example displays how the UNION operator can be used to insert records into a
table. First, create two tables Products and Suppliers and insert three records into each of these
tables, respectively.
create table products
(pcode char(4),descr char(10))
SELECT INTO
Please remember that in SQL 2000 the select into/bulkcopy statement given with SP_DBOPTION
has no effect on whether you can create a table or not. The option has been provided for backward
compatibility and affects only the amount of logging in transaction log for certain bulk operations
like select into depending on the type of recovery model.
Subqueries
Mention that in a subquery if the inner query is returning only one value, then use the =, >, <, >=,
and <= operators. If the inner query is returning more than one value, then use the IN operator.
In case of an error while executing a subquery, execute the inner query separately to check
whether there is any error in the inner query or not.
Additional Inputs
The SELECT INTO clause cannot be used with the same statement as the COMPUTE or
COMPUTE BY clause as a relational output is not produced.
You cannot use subqueries on columns that contain text and image.
Each nested subquery is evaluated only once.
If a subquery does not return a single value, you must introduce the subquery with the IN,
EXISTS, ANY, or ALL keyword.
For a UNION to generate a result set, the corresponding columns should have equivalent data
types. The ALL keyword when used with a UNION, displays duplicate rows if any.
In a subquery, if an ‘=’ operator is being used, the inner query should return a single value. If the
inner query is returning multiple values and the WHERE clause of the outer query has to match
with all the values returned by the inner query, then use the IN keyword.
While creating a database, it is a good practice to have multiple data files if the size of the
database is very big. You should also create the data files in different physical hard disk drives as
this implements faster Input-Output. The data files should also be put in NTFS partitions for better
performance. The following example creates a database Accounts with two data files on two
separate disks and two log files on another disk.
CREATE DATABASE Accounts
ON
PRIMARY ( NAME = Acct1,
FILENAME = 'c:\AcctDat1.mdf',
SIZE = 200MB,
MAXSIZE = 400,
FILEGROWTH = 20),
( NAME = Acct2,
FILENAME = 'd:\AcctDat2.ndf',
SIZE = 200MB,
MAXSIZE = 400,
FILEGROWTH = 20),
LOG ON
( NAME = Acctlog1,
FILENAME = 'e:\Acctlog1.ldf',
SIZE = 200MB,
MAXSIZE = 400,
FILEGROWTH = 20),
( NAME = Acctlog2,
FILENAME = 'e:\Acctlog2.ldf',
SIZE = 200MB,
Problem Solution
number
2 Question: Display the list of college names, newspaper names, and their
addresses in the following format:
Name
Address
Answer:
SELECT 'Name'=cCollegeName,
'Address'=vCollegeAddress
FROM College
UNION
SELECT cNewspaperName, vHOAddress
FROM Newspaper
4 Question: List the three types of operating system files that store the
data and objects of the SQL Server database.
Answer:
Primary
Secondary
Transaction Log
Table Creation
Before a table is created, tell your students that the database has to be created. The tables are
created in a database. Tell the students that the database has already been created for them. This
will not be covered in class. Normally, databases are created and managed by experienced
database administrators.
While creating a table, it is a good practice to explicitly mention whether an attribute allows null
or not null values.
Tell the students that it is a good practice to name the tables and attributes meaningfully, and that
they should follow the recommended naming conventions. SQL Server does not allow keywords
to be used as column names.
If a table already exists with a particular name, you will not be able to create another with the
same name. You need to drop the table and re-create it again with the same name.
Table Deletion
Tell the students that once a table is dropped, it cannot be referred to unless recreated.
User-defined Data types
Explain to the students that a user-defined data type is created for an attribute if the attribute
appears in more than one table. Besides, a user-defined data type is used to maintain consistency
of the system data type used for an attribute across tables.
Tell the students that a user-defined data type needs to be created before creating the table.
Before dropping a user-defined data type, ensure that it is not being used in any table.
Stress again the need for naming the data types meaningfully. Also, ask them to follow the
recommended naming conventions.
Primary Key
The easiest way to implement a primary key is by using a PRIMARY KEY constraint. It also
ensures entity integrity by not allowing duplicate values and null values.
Primary key and entity integrity can also be implemented using a unique clustered index, provided
the column is defined not to allow null values. Indexes are dealt with in more detail later in the
course.
Unique Constraint
Mention the fact that if the column having a unique constraint defined on it allows NULLs, then
only one row in the entire column can contain a NULL value.
The unique constraint can also be implemented using a unique clustered index on a column that
allows NULL values. However, only one row can contain a NULL value.
Foreign Key
Stress on the fact that a foreign key constraint can refer to another column of another table or
another column of the same table.
The easiest way to implement referential integrity is to define a PRIMARY KEY constraint on the
parent table and a FOREIGN KEY constraint on the child table. If an index is used to implement
the primary key and entity integrity on the parent table, then referential integrity can be
Check Constraint
A CHECK constraint on a column implements domain integrity on the column.
A column level CHECK constraint can refer to values of only that column. However, a table level
constraint can refer to values of other columns of the same table.
Default Constraint
Stress the fact that a default constraint is used for easing data entry.
Additional Inputs
When creating tables, these points can be discussed with students:
There can be two billion tables per database.
There can be 1024 columns per table.
Identity columns can be created to ensure that SQL Server inserts unique values
automatically. There can be only one column declared as an identity column. An identity
column cannot be updated. It does not allow null values. It can be of the int, smallint, tinyint,
and float data types.
Before dropping a table, you must remove any references between the table and any other
object.
User-defined data types created in the model database are automatically included in all
databases that are subsequently created.
Each user-defined data type when created adds a row to the systypes table.
The nullability of the column defined in the table, overrides that of the data type’s.
Domain integrity is implemented using the CHECK constraint.
Entity integrity is implemented using the PRIMARY KEY constraint.
Referential integrity is implemented using the FOREIGN KEY and PRIMARY KEY
constraints.
User-defined integrity is implemented in the form of business rules using CHECK constraints
or triggers.
Problem Solution
number
1 Question: Draft the statement to remove the College table from the
database.
Answer:
DROP TABLE College
2 Question: Which integrity ensures that the values in the foreign key
match with the value of the corresponding primary key?
Answer:
Referential integrity
Solutions: Practice
Problem Solution
number
--Implement
5.P.1
create table College
(
-- Implement
5.P.2
-- Primary key, default, check constraints on
College table.
create table College
(
cCollegeCode char(4) constraint ct_pk
primary key,
cCollegeName char(35) not null,
vCollegeAddress varchar(30),
cCity char(20) constraint
defCity default 'New Orleans',
cState char(20),
cZip char(10),
cPhone char(15) constraint
cph_ck check(cPhone like('([0-9][0-9][0-9])[0-
9][0-9][0-9]-[0-9][0-9][0-9][0-9]'))
)
CREATE TABLE CampusRecruitment
(cCampusRecruitmentCode char(4) primary key,
cCollegeCode char(4) References
College(cCollegeCode),
dRecruitmentStartDate datetime,
dRecruitmentEndDate datetime
)
--Verify checking for primary key
--Implement 7
7 a)
create table Category
(
cCategoryId char(3) constraint pkCategoryId
primary key,
cCategory char(20) constraint unqCategory
unique,
vDescription varchar(100) null
)
--Implement 7
7 b)
create table ToyBrand
(
cBrandId char(3) constraint pkBrandId
primary key,
cBrandName char(20) constraint
unqBrandName unique
)
--Implement 7
7 c)
create table Toys
(
cToyId char(6) constraint
pkToyid primary key clustered,
vToyName varchar(20) not null,
vToyDescription varchar(250)not null,
cCategoryId char(3) references
Category(cCategoryId) ,
mToyRate money not null,
--Implement 8
8
SELECT * INTO CaliforniaShopper
FROM Shopper
WHERE cState = 'California'
--Implement 9
9
DROP TABLE CaliforniaShopper
--Implement 10
10
select vFirstName,vLastName from shopper where
cCity in ('Woodbridge','San Jose','Las Vegas')
--Implement 11
11
select vToyName from toys
where cToyId in (select cToyId from
orderdetail where cWrapperId is NULL)
--Implement 12
12
select cOrderNo from orders
where exists(select * from shipment
where orders.cOrderNo = cOrderNo
and cDeliveryStatus = 's')
Lesson Six
Inserting Rows
While inserting rows into a table, remember to put the values for the columns with the char and
varchar data types within single quotes.
While inserting values into a column, which has a default defined on it, if you want the default to
be inserted for that column, you can use the DEFAULT keyword.
Tell the students that while entering data, the column-list needs to be specified when the data
being entered is not in the order of the columns in the table or when the data is not being entered
for all the columns.
Tell the students that SQL Server will automatically generate values for an Identity column. It’s
not a good practice to insert values for the same.
Tell the students that while inserting partial data, the columns for which data is not being inserted
should support NULL or default values.
You cannot insert rows into two tables using a single INSERT statement.
Updating Rows
Stress on the fact that whenever data is updated, the modified value should adhere to the business
rules that were effective when the row was entered.
You cannot update columns from two different tables using a single UPDATE statement.
Deleting Rows
You cannot delete rows from two different tables using a single DELETE statement.
Truncating Table
The TRUNCATE TABLE command deletes data from a table page wise and this operation is not
logged in the transaction log. This is the reason a delete operation in a transaction can be rolled
back, but a TRUNCATE TABLE command cannot be rolled back. Transactions are dealt with in
detail later in the course.
The WHERE clause cannot be used in the TRUNCATE TABLE statement.
Tell the students to follow naming conventions for constraints, rules, and defaults.
FAQ
Q: When would you use a CHECK constraint, and when would you use a rule?
If the same domain or user-defined integrity applies to multiple columns of the same table or
different tables, then you should create rules. Otherwise, if the integrity applies only to one
column of one table, use a constraint. The same is the case with defaults.
Q: If a rule and a constraint exist on a column, which one will be effective?
The rule is applied before the constraint. Let us understand this using an example:
Create table Products
(code char(4),
qoh int
CHECK (qoh > 10))
Additional Inputs
A rule and default can be separately created using the CREATE RULE and the CREATE
DEFAULT statement, respectively. After creation, these need to be bound to the specified
columns. If any of these are bound to a table, then before dropping the rules and defaults, unbind
these rules and defaults.
The FUTUREONLY option of sp_bindrule applies to only user-defined data types. If this option is
specified, then the rule does not apply for the data in those columns, which are already using this
user- defined data type. It is only applicable to all those columns which will be created in future
and which will use this data type.
While inserting rows, it is a good practice to mention the column list.
Data in a text or an image column can be entered using Writetext(). The following example
explains the usage of the Writetext() function.
Create a table called supplier with attributes suppcode (char(4)) and suppdescr (text) and insert the
three records as shown below:
Suppcode suppdescr
P001 Supplies the raw materials in record time and is
the most preferred supplier
P002 Supplies the raw materials in time and can be
informed in case of emergency
P003 Has delayed supplies on a number of occasions so
is not a preferred supplier
Now set the select into/bulk copy option for the database to true. Next, declare a variable
@suppdescr of binary(16) data type and put the handle of the text data into this variable using the
TEXTPTR() function. This handle belongs to the suppdescr for the supplier P001. Now, use the
WRITETEXT() to write this text to the Supplier table for supplier P003. The code for this is given
below:
DECLARE @suppdescr binary(16)
SELECT @suppdescr = TEXTPTR(suppdescr)
FROM supplier
Problem Solution
number
2 Question: Which statement allows you to copy contents of one table into
another table?
Answer:
The INSERT INTO statement allows you to copy contents of one table
into another table.
Lesson Seven
Experiences
Stress on the importance of naming conventions while creating indexes.
Stress on the advantages of using indexes.
Stress on the concept of creating appropriate indexes for appropriate columns.
Do mention that indexes are used to speed up queries and are created on columns that are used in
joins, the WHERE clause, the ORDER BY clause, or the GROUP BY clause.
Note: To explain the diagram for clustered and non-clustered index, faculty needs to follow
all the given steps in the student guide. Faculty also needs to ask students to do the same
thing.
The diagram contained in the slide has simplified the Nonclustered index diagram given in the
student guide This diagram depicts the reference of only one record (EID E005) from Root Page
to the Data Page.
Note: Faculty can ask students to note down the diagram for their reference.
FAQ
Q: Can all columns of a table be indexed?
Yes, but it is not very beneficial. Index only those columns, which are used in a WHERE clause,
joins, the ORDER BY clause or the GROUP BY clause.
Q: Can a single column be indexed more than once?
Yes, but it is not very beneficial.
Additional Inputs
Problem Solution
number
Problem Solution
number
--Implement 1
1 a)
create table Category
(
cCategoryId char(3),
cCategory char(20),
vDescription varchar(100)
)
--Implement 1
1 b)
create table ToyBrand
(
cBrandId char(3),
cBrandName char(20)
)
--Implement 1
1 c)
create table Toys
(
cToyId char(6),
vToyName varchar(20),
vToyDescription varchar(250),
cCategoryId char(3),
mToyRate money,
cBrandId char(3),
imPhoto image null,
siToyQoh smallint ,
siLowerAge smallint ,
siUpperAge smallint ,
siToyWeight smallint,
vToyImgPath varchar(50) null
--Implement 1
1 d)
create rule rulRate
as
@rate>0
sp_bindrule rulRate,'Toys.mToyRate'
--Implement 1
1 g)
insert into toys
values(‘000001’,’Robby the Whale’,’A giant
Blue Whale with two heavy-duty handles that
allow a child to ride on its back.’, ‘001’,
8.99, ‘001’,NULL,50,3,9,1,null)
--Implement 1
1 h)
update toys
set mToyRate=mToyRate+1
WHERE cToyId='000001'
--Implement 1
1 i)
DELETE ToyBrand
WHERE cBrandName='Largo'
--Implement 2
2
Create nonclustered index idxshopper
on Orders(cShopperId)
--Implement 3
3
CREATE unique clustered index idxToys
on Toys(cToyId)
--Implement 4
4
CREATE unique nonclustered index idxCategory
ON Category(cCategory)
--Implement 5
5
Declare @objid int
SET @objid = OBJECT_ID('Shopper')
DBCC SHOWCONTIG (@objid)
--Implement 6
6
Declare @objid int
SET @objid = OBJECT_ID('Wrapper')
DBCC SHOWCONTIG (@objid)
--Implement 7
7
CREATE NONCLUSTERED INDEX idx_cState
ON Recipient (cState)
--Implement 8
8
INSERT ShoppingCart VALUES('000010','000013',2)
Lesson Eight
Experiences
Create Views
Variable Declaration
A variable can be declared using the DECLARE keyword. Follow the naming conventions as
recommended.
Conditional Execution
One or more SQL statements can get executed depending on a condition. The IF statement can be
used for doing so. If the same condition has to be tested for different values, tell your students to
use the CASE construct instead of the IF statement.
The WHILE construct can be used to repeatedly execute a block of SQL statements.
FAQs
Q What are the restrictions on views?
The ORDER BY, COMPUTE or COMPUTE BY, and the INTO statements cannot be used in a
CREATE VIEW statement.
Views cannot reference temporary tables.
The CREATE VIEW statement cannot be combined with other T-SQL statements.
Additional Inputs
Rows can be updated, deleted, and inserted using a view if they affect a single table.
If a computed column exists in the view definition, the header for the same needs to specified.
Computed columns, summary data, and aggregate values cannot be updated using a view.
Avoid using OUTER JOINS in views.
If a base table is dropped before dropping the view, it does not generate an error, but if the view is
referenced after this, it generates an error. So before dropping the base table, drop the view first.
If a stored procedure is to be executed in a batch, execute it with the EXECUTE statement.
Multiple updates, inserts, and deletes can be done in a batch.
You can use the CASE statement in a DML statement when conditional query or updates have to
be done.
In SQL Server 2000, you can create indexes on views. When a clustered index is created on a
view, the data is stored in the database instead of online generation of the result-set. This improves
data retrieval time. Just like clustered indexes on tables, every time there is a modification of data
in the base table(s), the clustered index on the view also gets updated. As this updatation
consumes a lot of time, it affects the database performance negatively. So such indexes should be
created only on views that are read-intensive and not write-intensive.
Problem Solution
number
Solutions: Practice
Problem Solution
number
--Implement
2
UPDATE vwNewspaperNewsad
SET cZip='88993-4532'
WHERE cNewspaperName='Daily News'
UPDATE vwNewspaperNewsad
SET dAdStartDate='01/09/99'
-- Verify
SELECT * FROM vwNewspaperNewsad
WHERE cNewspaperName='Daily News'
Lesson Nine
Experiences
Procedures
Discuss the benefits of procedures – modularity, speed, security, reduced network congestion and
consistency of usage across applications and users.
Tell the students that since stored procedures have so many benefits, all operations and
transactions from the client such as queries, updation, insertion, and deletion of rows are done
using stored procedures. Even if the insert, update, delete, or query operation is very simple, a
stored procedure must be created. This improves performance of the application. Hence,
programmers simply execute the stored procedures, which are stored at the backend instead of
sending SQL statements from the client.
If the definition of the stored procedure needs to be modified, then use the ALTER PROCEDURE
statement.
Types of Procedures
Tell your students that an extended stored procedure is used to activate a function in a DLL
residing outside the database.
A temporary stored procedure is accessible to a user as long as he or she does not log out.
A temporary stored procedure can be of two types, local or global. A global stored procedure is
available to all users as long as the last user has not logged out. The name of a global stored
procedure is prefixed by ##.
Tell the students that the difference between a system-defined stored procedure and a user-defined
stored procedure is that a system defined stored procedure is provided by SQL Server and a user-
defined stored procedure is what the user creates.
Parameters
After explaining the two types of parameters, tell the students that a procedure with output
parameters is typically executed from another calling procedure.
Mention that the ‘return’ keyword is used when a single value needs to be returned to the calling
program.
Output parameters are used when multiple values of any data type have to be returned.
Tell the students that apart from explicitly executing a stored procedure it can be executed
automatically, for example, at the start-up of SQL Server. This can be done by using a system
stored procedure called sp_procoption for only objects of master database, which are owned by
dbo. The syntax for sp_procoption procedure is shown below:
where,
@ProcName defines the procedure for which to set the option
@OptionName defines the option to set for the procedure that can only be ‘startup’, which will set
the procedure for autoexecution
@OptionValue defines whether to set the option as true or false
Procedure Usage
Mention in the class that if data changes and indexes are updated, the execution plan for the SQL
statements in a stored procedure will become outdated. In this kind of a situation, the SQL
statement needs to be recompiled every time the stored procedure gets executed. This is done
using the WITH RECOMPILE option of the CREATE PROCEDURE statement.
Remember to use naming conventions while creating procedures.
FAQ
Q: What are the different types of procedures?
System stored procedures, Local stored procedures, Temporary stored procedures, Remote stored
procedures, and Extended stored procedures.
Additional Inputs
Stored procedures can be nested upto 32 levels.
When designing an application, stored procedures can significantly reduce the network
requirements. Use stored procedures for long, complicated, and frequently repeated queries. This
reduces the traffic from the client to the server because only the stored procedure name and its
associated parameters are passed across the network to the server, where it is executed. In
addition, multi-step queries that perform additional filtering or processing based upon the response
to initial queries, run much more efficiently as a stored procedure. By using a stored procedure, it
is not necessary to pass the results of the initial query to the client in order that a second query can
be passed to the server.
The sp_depends stored procedure can be used to find out the dependencies of a stored procedure.
The syntax is as given below:
sp_depends object_name
Extended stored procedures can be used to execute commands that are external to SQL Server.
These commands can be operating system level commands or those created by a user using a
programming language such as c or c++. These commands need to be created as part of a DLL for
Problem Solution
number
Question: What are the benefits of using stored
1
procedures?
Answer:
Improved performance
Reduction in network congestion
Better consistency
Better security mechanism
Problem Solution
number
--Implement 1
1
Create view vwShopperToy
as
SELECT Shopper.vFirstName,
vToyName,siQty,mToyCost
FROM Shopper JOIN Orders
ON Shopper.cShopperId= Orders.cShopperId
JOIN OrderDetail
ON Orders.cOrderNo=OrderDetail.cOrderNo
JOIN Toys
ON OrderDetail.cToyId=Toys.cToyId
--Verify
SELECT * from vwShopperToy
--Implement 2
2
Update vwOrderWrapper
SET siQty=2
FROM vwOrderWrapper
WHERE cOrderNo='000001'
Update vwOrderWrapper
SET mWrapperRate=mWrapperRate + 1
FROM vwOrderWrapper
WHERE cOrderNo='000001'
--Implement 3
3
DECLARE @deliverystatus char(1)
SELECT @deliverystatus=cDeliveryStatus FROM
Shipment WHERE cOrderNo='000003'
IF @deliverystatus='d'
Print 'The order has been delivered'
--Verify
exec prcAddBrand '009','Fun World'
--Implement 10
10
CREATE PROCEDURE prcAddCategory
@CategoryId char(3),
@Category char(20),
@Description varchar(100)
as
INSERT Category
VALUES (@CategoryId,@Category,@Description)
--Verify
exec prcAddCategory '018','Electronic
Games','These games contain a screen with
which children interact.'
--Implement 11
11
drop procedure prcAddCategory
--Implement 12
12
CREATE PROCEDURE prcCharges
@OrderNo char(6),
@ShippingCharges money OUTPUT,
@GiftWrapCharges money OUTPUT
as
SELECT
@ShippingCharges=mShippingCharges,@GiftWrapCha
rges=mGiftWrapCharges
FROM Orders
Triggers
Stress on the fact that triggers are used when complex business rules have to be implemented.
While constraints can be used to maintain referential integrity, triggers can also be used if
required.
Mention that triggers are a special type of stored procedure, but cannot be executed explicitly.
Mention that the overhead involved with a trigger is very high, but the functionality provided is
also very good.
You also need to touch upon the cascade delete, restrict delete, and nullify delete rules in your
class. If a record is deleted from the master table, then the corresponding records from the
transaction table also get deleted. This is the cascade delete rule. In the restrict delete rule, if an
open transaction exists in the transaction table, then the corresponding records in the parent table
cannot be deleted. In the nullify delete rule, if a record is deleted from a parent table, then the
corresponding values in the foreign key column of the child tables is replaced by NULL.
Discuss the concept of nesting levels of triggers.
Follow naming conventions for triggers. Prefix a trigger name with ‘trg’.
Multiple Triggers
Tell the students that multiple triggers for a DML operation can be created on the same table. For
instance, in a table called TAB1 you can create two triggers TRIG1 and TRIG2, both for update
operation. Also, mention that this facility was not available in the earlier versions of SQL Server.
The benefit of using multiple triggers is that you can implement multiple business rules using
different triggers. However, you can incorporate all the rules in a single trigger. Having multiple
triggers helps in maintenance, readability, and documentation. The triggers are executed in the
order they have been created.
Instead Of Triggers
Tell the students that in SQL Server 2000, you have a new variation of the database object trigger.
This type of trigger is used to update the base tables of a view when a view is created on multiple
tables. This type of trigger is particularly useful for validating insert values before inserting in the
base tables. The instead of triggers can be created on tables or views. In case a table contains
primary key or foreign key constraints that implement with cascade delete or cascade update
functionality, then the instead of delete and instead of update triggers cannot be defined on them.
FAQ
Q: When does a trigger get executed?
After a DML (update, insert, or delete) transaction.
Q: If there exists a trigger and a rule, which will get executed first?
The rule will get executed first.
Additional Inputs
The maximum nesting level for triggers is 32.
You cannot create triggers on system tables.
Triggers unlike stored procedures do not return values or result sets.
If multiple business rules need to be applied when a DML operation is underway use multiple
triggers for implementing the same. For example, if three columns are being updated and different
business rules have to be applied for each, use three different update triggers for each business
rule.
Problem Solution
number
1 Question:
a. What are magic tables?
Answer:
Magic tables are conceptual tables and are similar in structure to the table
on which the trigger is defined. Whenever a trigger fires in response to
the INSERT, DELETE, or UPDATE statement, two special tables are
created. These are the inserted and the deleted tables. These tables are
referred to as the magic tables.
Question:
b. Which statement is used to create triggers?
Answer:
CREATE TRIGGER
Solutions: Practice
Problem Solution
number
--Implement
10.P.1
Create trigger trgInsertEmployee
on Employee
for insert
as
update Position
set iCurrentStrength= iCurrentStrength + 1
from inserted JOIN Position
ON
Position.cPositionCode=inserted.cCurrentPositi
on
print 'Position table updated'
return
--verify
Update employee
set dResignationdate=getdate()
where cEmployeeCode='000016'
select * from Position
Lesson Eleven
Experiences
Transaction
Stress on the fact that a transaction is an atomic unit of work, which either happens completely or
does not happen at all. If an insert operation in one table and two update operations in two
different tables constitute a logical unit of work, then the three operations can be termed as a
transaction. If only one insert happens and the other two updates do not happen, the transaction is
not complete and may result in inconsistency of data. Hence, it is essential that all the operations
happen or none of them happens at all. Explicit statements like BEGIN TRANSACTION and
COMMIT TRANSACTION ensure that all statements in a transaction are completed successfully
or do not take place at all in case there is a system crash while the transaction is running.
By default SQL Server uses a row level lock.
Tell the students that the transactions should be as short as possible, and table level locks should
be avoided as this locks the entire table.
If multiple transactions refer to the same tables, then refer them in a specific order to minimize
deadlocks.
While creating a transaction, follow the naming conventions. Prefix the transaction name with a
‘trn’.
Transaction Log
Tell the students that the transaction log is like a huge ‘security register’ where any activity on the
database gets recorded. The log is used to roll forward or rollback transactions in case of a system
failure. Tell them that the transaction log plays a big role in transaction management.
Distributed Transactions
Unlike normal transactions, a distributed transaction is processed on more than one database
server.
Concurrency Problems
Find below the examples for each of the concurrency problems:
Lost updates
Lost updates occur when two or more transactions select the same row and then update the row
based on the value originally selected. Each transaction is unaware of the other transaction. The
last update overwrite updates made by the other transaction, which results in lost data.
Let us assume that both Sam and Anne are simultaneously trying to update the price of all the
“Business” books in the Titles table. Sam is trying to update the price by 10% while Anne is trying
to update the price by 15%.
Now, the table will get updated by the changes of the query that will get completed last. That
means, if Sam’s query is executed later than Anne’s query, then the price column in titles table
will get increased by 10% and the changes made by Anne’s query will be lost.
Uncommitted dependency
Uncommitted dependency occurs when a second transaction selects a row that is being updated by
another transaction. The second transaction is reading data that has not been committed yet and
may be changed by the transaction updating the row.
Let us assume User A and B are working on titles table. User A had increased the price of title_id
‘BU1032’ by Rs. 10. But user A does not commit the transaction. Now User B tries to execute a
query on title_id ‘BU1032’. User B is accessing old record as the transaction handle by user A is
not yet complete. Therefore user B also updates the price of title_id ‘BU1032’ by Rs. 5. These
transactions will update the record by Rs 15. Such kind of problems leads to inconsistency in the
table.
Inconsistent Analysis
Inconsistent analysis occurs when a second transaction accesses the same row several times and
reads different data each time. Inconsistent analysis is similar to uncommitted dependency in that
another transaction is changing the data that a second transaction is reading. However, in
inconsistent analysis, the data read by the second transaction was committed by the transaction
that made the change. Also, inconsistent analysis involves multiple reads (two or more) of the
same row and each time the information is changed by another transaction; thus, the term
nonrepeatable read.
For example:
Let us assume that you are accessing the online reservation system to check the status of your
ticket. The site showed the status as ‘Waiting’. Just a little later, when you refreshed the page, you
found that the status is ‘confirmed’. This shows that while you were browsing thru the
information, some procedure was updating the record information.
Phantom reads
LOCKS
Discuss the types of locks in detail. Also, discuss when each of these locks are used by SQL
Server.
SQL Server uses row lock by default.
The concept of deadlock needs to be explained to the students.
Tell the students that if the deadlock priority is set low for a transaction, then the transaction has a
higher probability of becoming the deadlock victim in a deadlock situation.
Mention that lock_timeout is used on a transaction if you do not want a transaction to wait for an
indefinite period. Using lock_timeout you can mention in milliseconds how long a transaction will
wait for a lock to open.
Tell the students that whenever an ad hoc DML statement is executed, SQL Server, by default,
treats the statement as a transaction and commits the transaction. This mode is called the auto
commit mode.
Tell the students that although SQL Server 2000 uses dynamic locking, it is still very important for
you to differentiate between the different locking modes. The different types of locks used by SQL
Server 2000 are shared, update, exclusive, intent, schema, and bulk-update.
Deadlock
Suppose a delete trigger called Trigger1 has been defined on a table called Table1 and there is a
delete trigger called Trigger2 on another table called Table2. Trigger1 deletes a row on Table2 and
Trigger2 deletes a row on Table1. If you delete a row in Table1, then Trigger1 will try to obtain an
exclusive lock on Table2 and Trigger2, which will be fired now, will try to acquire an exclusive
lock on Table1 that is already locked. Both these transactions wait for the other to release the
locks imposed by them. This causes a stalemate because neither application can release its locks
and finish its session while waiting for the other application to release its locks. SQL Server
automatically fixes this by choosing one application, forcing it to release the lock and allowing the
other session to continue. By setting the DEADLOCK PRIORITY, you can decide which session
is more likely to be the next deadlock looser. SQL Server will release the lock of the session that
has lower priority. Set the DEADLOCK PRIORITY using the following syntax: SET
DEADLOCK_PRIORITY {LOW | NORMAL}.
FAQ
Q: What are the different types of transaction modes available in SQL Server 2000?
Implicit and explicit.
Q.: How does the transaction log help in transaction management?
Every transaction is recorded in the transaction log to maintain database consistency and aid in
recovery.
Q: When will SQL Server use an update lock?
When updating rows, SQL Server first searches for the records and uses a shared lock in the
process. Once the records are located, the shared lock is upgraded to an exclusive lock. If another
transaction has applied a shared lock on the resource, the shared lock imposed while searching for
the records cannot be upgraded. To avoid this SQL Server uses an update lock while updating
records.
Q: In case there are a lot of transactions, which lock will you request for while updating a row in a
table?
You should request for an intent lock. Intent locks impose locks higher up in the hierarchy and
only those locks are compared instead of comparing locks in the lower level.
Additional Inputs
Timeouts can be used to prevent deadlocks.
For multiple transactions running simultaneously on a SQL Server, you can define their isolation
level to balance between concurrency and data integrity. By choosing the right transaction,
isolation level can improve performance of the SQL Server queries. There are four transaction
isolation levels:
Problem Solution
number
Problem Solution
number
---Implement 1
1
declare @fname char(20)
declare @lname char(20)
declare @testscore int
declare @msg varchar(120)
declare candidatechk cursor
for
select vfirstname,vlastname,sitestscore from
externalcandidate
open candidatechk
fetch candidatechk into @fname,@lname,@testscore
Print 'First Name Last Name
Marks Result'
Print '------------------------------------------
------------------------------------------------'
While (@@fetch_status = 0)
begin
if(@testscore >= 90)
begin
SELECT @msg = 'Selected for the Interview'
end
else
if(@testscore < 90)
begin
SELECT @msg = 'Not Selected for the
Interview'
end
print @fname + @lname +
CONVERT(char,@testscore)+@msg
fetch next FROM candidatechk INTO
@fname,@lname,@testscore
end
close candidatechk
deallocate candidatechk
--Implement 2
2
'00000'+Convert(char,@OrderNo+1)
WHEN @OrderNo>=9 and @OrderNo<99 Then
'0000'+Convert(char,@OrderNo+1)
WHEN @OrderNo>=99 and @OrderNo<999 Then
'000'+Convert(char,@OrderNo+1)
WHEN @OrderNo>=999 and @OrderNo<9999 Then
'00'+Convert(char,@OrderNo+1)
WHEN @OrderNo>=9999 and @OrderNo<99999 Then
'0'+Convert(char,@OrderNo+1)
WHEN @OrderNo>=99999 Then
Convert(char,@OrderNo+1)
END
RETURN
Update OrderDetail
SET mToyCost=mToyRate*siQty
FROM OrderDetail JOIN Toys
--Verify
exec prcOrder '000001','000001'
--Implement 3
3
CREATE PROCEDURE prcOrderDetail
@OrderNo char(6),
@ToyId char(6),
@WrapperId char(3)
as
BEGIN TRANSACTION
Update OrderDetail
SET cGiftWrap='Y', cWrapperId=@WrapperId
WHERE cOrderNo=@OrderNo and cToyId=@ToyId
Update Orders
Set
mGiftWrapCharges=mGiftWrapCharges+mWrapperRate
*siQty
FROM Orders JOIN OrderDetail
ON Orders.cOrderNo=OrderDetail.cOrderNo
JOIN Wrapper
ON OrderDetail.cWrapperId=Wrapper.cWrapperId
and Orders.cOrderNo=@OrderNo and cToyId=@ToyId
COMMIT TRANSACTION
RETURN
--Verify
exec prcOrderDetail '000010','000020','005'
SELECT * from Orders
--Implement 4
4
CREATE Trigger trgOrderQty
ON OrderDetail
FOR UPDATE
--Verify
Update OrderDetail
SET siQty=3
WHERE cOrderNo='000002'
Lesson One
Problem Solution
number
SELECT 'Candidate Code'= cCandidateCode,
1a 'Candidate Name'= vFirstName + vLastName
FROM ExternalCandidate
SELECT 'Department Code' = cDepartmentCode,
1b 'Department Name' = vDepartmentName
FROM Department
Select cToyId, mToyRate, vToyName
2a From Toys
Where vToyName='Baby Minnie' or vToyName='Dune
Racer'
SELECT *
2b FROM Toys
WHERE vToyName = 'Large Duck'
SELECT *
2c FROM Toys
WHERE mToyRate >19.0000 and mToyRate <30.0000
SELECT 'Toy ID' = cToyId,
2d 'Month' = siMonth, 'Year' = iYear,
'Total Toys Sold' = iTotalSold
FROM PickOfMonth
Lesson Two
Problem Solution
number
SELECT *
1 from department
where vdepartmentname Like 'T%'
2 Check the output in the Query Analyzer.
Select *
3 From Department
Where vDepartmentHead IS NULL
Select Top 5 *
4 From ExternalCandidate
Where cRating >=5 and cRating <=7
Order by vFirstName
Select ccategoryid, ctoyid, vtoyname, mtoyrate
5 from toys
order by ccategoryid
compute avg (mtoyrate) by ccategoryid
Lesson Three
Problem Solution
number
SELECT DISTINCT 'Employee Name'= vFirstName +
1 vLastName, 'Department Name '= vDepartmentName,
'Annual Salary'=mAnnualSalary
From Employee
join Department
on Employee.cDepartmentCode =
Department.cDepartmentCode
join Annualsalary
on Employee.cEmployeeCode =
Annualsalary.cEmployeeCode
2 It displays the redundant column data from the three tables.
Select cCountry, cEmployeeCode, vFirstName,
3 vLastName
From Country left outer join Employee
On Country.cCountryCode = Employee.cCountryCode
select s1.vFirstName, s1.vLastName, s1.cCity,
4 s2.vFirstName,s2.vLastName
from shopper s1
join shopper s2
on s1.cCity=s2.cCity
and s1.cShopperId>s2.cShopperId
Lesson Four
Problem Solution
number
2 When two tables are joined using the UNION operator, the data is
displayed in the sequence in which the fields are mentioned.
3 The initial size and the maximum size of the database have not been
mentioned.
Lesson Six
Problem Solution
number
CREATE RULE rulCollegeCode
1 AS
@CollegeCode LIKE '[0-9][0-9][0-9][0-9]'
sp_bindrule rulCollegeCode,
'College.cCollegeCode'
CREATE DEFAULT defBrandId AS '001'
2
Lesson Seven
Problem Solution
number
CREATE NONCLUSTERED INDEX idxEmployeeFirstName
1
ON Employee (vFirstName)
CREATE UNIQUE NONCLUSTERED INDEX
2 idxSocialSecurityNo
ON Employee (cSocialSecurityNo)
CREATE NONCLUSTERED INDEX idxRequisition
3. ON Requisition (cRequisitionCode, cPositionCode)
Lesson Eight
Problem Solution
number
CREATE VIEW vwToyDescriptionRate
1 WITH ENCRYPTION
AS
SELECT vToyDescription, mToyRate
FROM Toys
CREATE VIEW vwShopper AS
2 SELECT vFirstName, vLastName, vEmailId from
Lesson Nine
Problem Solution
number
CREATE PROCEDURE prcEmployeeName
1 AS
BEGIN
SELECT vFirstName, vLastName
FROM Employee
END
CREATE PROC prcShopperDetails @ShopperState
2 char(15)
AS
BEGIN
SELECT vFirstName, vLastName, vAddress, cState
FROM Shopper
WHERE cState = @ShopperState
END
ALTER PROCEDURE prcCategoryDetails
3. WITH RECOMPILE
AS
SELECT cCategory, vDescription FROM Category
Lesson Ten
Problem Solution
number
CREATE TRIGGER trgInsertOrderDetail
1 ON OrderDetail
FOR insert
AS
IF NOT EXISTS (SELECT * FROM Toys JOIN Inserted
on
Toys.cToyId = Inserted.cToyId)
BEGIN
PRINT 'Toy not found in the Toys table.'
ROLLBACK TRANSACTION
END
RETURN
Lesson Eleven
Problem Solution
number
BEGIN TRANSACTION
1 UPDATE Toys
SET mToyRate = mToyRate + 5
IF (SELECT SUM(mToyRate) FROM Toys) > 100
BEGIN
ROLLBACK TRANSACTION
END
ELSE
BEGIN
COMMIT TRANSACTION
END
declare @cToyId char(6)
2 declare @siQty int
declare Toychk cursor
for select cToyId,siQty
from ShoppingCart
open Toychk
fetch Toychk into @cToyId,@siQty
While (@@fetch_status = 0)
begin
Update Toys
set siToyQoh = siToyQoh - @siQty
from Toys
where cToyId = @cToyId
fetch next FROM Toychk into @cToyId,@siQty
end
close Toychk
deallocate Toychk
CREATE Trigger trgOrderDetail
3 ON OrderDetail
for insert
as
UPDATE Toys
SET siToyQoh=siToyQoh-siQty
FROM Toys
JOIN INSERTED
ON Toys.cToyId=Inserted.cToyId
--Verify
insert into OrderDetail
values('000009','000001',2,'N',NULL,NULL,39.9800)
select * from toys
Cycle6 OCR1
Lesson 6: Objectives 5
6.D.1 15
6.D.2 15
Maintaining Data 5
6.D.3 10
6.D.4 10
6.D.5 5
6.D.6 5
Truncating a Table 5
Summary 10
Total 115
OCR2
Lesson 7: Objectives 5
Getting Started 20
7.D.1 15
Index Tuning Wizard 10
7.D.2 20
Index Enhancements 35
Summary 10
Total 115
Cycle7
OCR1
Lesson 8: Objectives 5
Getting Started 15
8.D.1 12
Altering, Dropping, and Renaming 15
Views
8.D.2 12
8.P.1 12
Programming in SQL Server 10
OCR2
Lesson 9: Objectives 5
Getting Started 15
9.D.1 15
9.D.2 15
**9.D.3 5
9.D.4 15
**9.D.5 5
9.D.6 25
Summary 10
Total 110
Cycle8
OCR1
Lesson 10: Objectives 5
10.D.1 15
10.P.1 15
10.D.2 10
10.D.3 10
10.P.2 10
10.D.4 10
10.D.5 10
Enforcing Data Integrity Through 10
Triggers
Summary 5
Total 100
OCR2
Lesson 11: Objectives 5
11.D.1 10
11.D.2 15
11.D.3 10
11.D.4 25
Deadlock 10
Cursors 5
11.D.5 15
11.P.1 15
Summary 5
Total 115