SQL Server 2005 Concepts

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 65

Microsoft SQL Server - Concepts 2

005

1 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

SQL Server Overview

SQL Server 2005 Overview


2 Taught by: Aiman Mobarak Elkhalifa
Microsoft SQL Server - Concepts 2
005

Microsoft SQL Server 2005 is a database platform for large-scale Online Transaction Processing
(OLTP) and Online Analytical Processing (OLAP). The following table lists the components that
provide various database services in SQL Server 2005:

Component Description
The SQL Server Database Engine is a service that you can use to store, process, and
secure your data in a relational or XML format. Starting an instance of SQL Server
Database Engine starts the SQL Server service which allows users to connect to the
server. SQL Server Database Engine includes features such as:

SQL Server • Controlled access


Database • Replication
Engine • Full-text search
• Relational data management tools
• XML data management tools
• Rapid transaction processing for data-consuming applications

• Outstanding support to sustain availability


SQL Server Analysis Services (SSAS) provides Online Analytical Processing (OLAP)
and data mining functionality for business intelligence solutions. You can use SSAS to
design, create, maintain, and visualize:
SQL Server
Analysis • OLAP multi-dimensional structures that contain aggregated data from
Services relational databases or additional sources.

• Data mining models that are constructed from data sources by using industry-
standard algorithms.
SQL Server Reporting Services is an extensible, web-enabled platform that includes
server and client components that allow you to:

• Create, manage, and deploy a variety of reports such as:


o Tabular reports
SQL Server o Matrix reports
Reporting
o Graphical reports
Services
o Free-form reports
• Publish reports in a variety of formats
• Develop report applications

• Manage security and subscriptions centrally


SQL Server SQL Server Notification Services allow you to develop and deploy applications that
Notification generate and send notifications. You can use SQL Server Notification Services to:
Services

3 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

• Generate and send timely, personalized messages to millions of subscribers

• Deliver messages and notifications to a wide variety of devices


SQL Server Integration Services (SSIS) is a platform for building high-performance
data integration solutions. SSIS provides tools and programmable objects for
extracting, loading, and transforming (ELT) services for data integration and
workflow solutions including updating data warehouses, mining data, and processing
analytic objects. SSIS includes:

• Tools and wizards for building and debugging packages


• A management service
SQL Server • An Integrations service
Integration • Tasks for performing workflow functions such as:
Services
o FTP operations
o Executing SQL statements
o Sending e-mail messages
• Application programming interfaces for programming the Integration Services
object model
• Data sources and destinations for extracting and loading data

• Transformers for cleaning, aggregating, merging, and copying data

4 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

SQL Server Editions

SQL Server 2005 has different editions to meet the needs of businesses of varying sizes and varying
database requirements. The table below describes the various SQL Server 2005 editions.

Edition Description
Enterprise Edition includes the complete set of enterprise data management and business
intelligence features. SQL Server Enterprise offers the highest levels of scalability and
availability. Enterprise Edition supports:

SQL Server 2005 • Data warehousing systems


Enterprise Edition • Enterprise online transaction processing (OLAP)
• Large Web sites

Enterprise Edition is optimized to run on x64- and Itanium-based servers and is typically used on
a production database server.
Standard Edition is an affordable option for small- and medium-sized organizations. It includes
the core functionality needed for non-critical e-commerce, data warehousing, and line-of-
SQL Server 2005 business solutions.
Standard Edition
Standard Edition is optimized to run on win32, x64, and Itanium-based servers.
Workgroup Edition is the data management solution for small organizations or workgroups
SQL Server 2005 within larger entities. It includes all the core database features needed for data management.
Workgroup Edition
Workgroup Edition is available only on a 32-bit platform.
Express Edition is a replacement for Microsoft Desktop Engine (MSDE). SQL Server Express is
free and can be redistributed (subject to agreement). It functions as the client database, as well as
SQL Server 2005 a basic server database.
Express Edition
Express Edition is available only on a 32-bit platform.
Developer Edition is designed for application developers. It includes all the functionality of
Enterprise Edition. License restrictions limit the use of this version to application development
SQL Server 2005 and testing only. It is not for use as a production server.
Developer Edition
Developer Edition runs on win32, x64, and Itanium-based servers.
Mobile Edition allows organizations to extend enterprise data management and business
intelligence capabilities to mobile devices. Mobile Edition can replicate to a SQL 2005
SQL Server 2005 Enterprise or Standard Edition environment.
Mobile Edition
Mobile Edition is only available on a 32-bit platform.

5 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

Ma na gem ent T ool s

SQL Tool Facts

6 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

SQL Server 2005 has enhanced tools for easier, more efficient management. SQL Server 2005 tools
can manage all features of SQL Server 2000; however, you cannot use SQL Server 2000 tools to
manage SQL Server 2005. When SQL Server 2005 and SQL Server 2000 are installed on the same
computer, both of their respective tool sets remain fully functional.

The following table identifies SQL Server 2005 management tools and their respective features. It
also identifies any SQL Server 2000 tools that have been replaced.

Tool Description
SQL Server Management Studio provides an integrated environment to manage
a SQL Server implementation. Using its graphical interface and script editors,
you can use SQL Server Management Studio to perform such tasks as:

• Create databases, tables, indexes, views, etc.


• Perform database maintenance
• Perform server maintenance on servers
• Manage security
SQL Server • Register multiple servers
Management Studio • Build SQL Server projects

SQL Server Management Studio replaces the following tools in previous


versions of SQL Server:

• SQL Server Enterprise Manager


• SQL Query Analyzer

• Analysis Manager
SQL Server Business Intelligence Development Studio provides tools, wizards,
and templates to enable organizations to gather business intelligence and create
business solutions. It integrates into Microsoft Visual Studio with project types
specifically designed for business intelligence. The primary components of SQL
SQL Server Business Server Business Intelligence Development Studio are:
Intelligence
Development Studio
• Analysis Services
• Integration Services

• Reporting Services
SQL Server SQL Server Configuration Manager enables you to manage SQL Server
Configuration services. SQL Server Configuration Manager is a Microsoft Management
Manager Console snap-in that is available from the Start menu, or can be added to any
other Microsoft Management Console display. Tasks you can perform with SQL
Server Configuration Manager are:

7 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

• Change the account used by the SQL Server or SQL Server Agent
services.
• Configure network protocols.
• Manage network connectivity configuration from SQL Server client
computers.

SQL Server Configuration Manager replaces the following SQL Server tools:

• Server Network Utility


• Client Network Utility

• Service Manager
SQL Server Profiler provides a graphical user interface to SQL Trace. It is a
valuable tool for analyzing database performance issues. You can use it for:

• Monitoring an instance of the SQL Server Database Engine or Analysis


SQL Server Profiler
Services.
• Analyzing query patterns.

• Capturing event data to a file or table.


Surface area refers to the exposure of the SQL System by enabled components,
services, protocols, and open ports. Using the SQL Server Surface Area
Configuration Tool you can:

• Enable and disable features, services, and network protocols for remote
SQL Server Surface
connections to help reduce the surface area of your SQL Server
Area Configuration
installations.
Tool
• Export SQL surface area settings created using SQL Server Surface Area
Configuration Tool to another server. The SQL Server Surface Area
Configuration Tool works in conjunction with the Surface Area
Configuration (SAC) utility to export settings.
Database Engine The Database Engine Tuning Advisor analyzes the performance effects of
Tuning Advisor workloads ran against one or more databases and provides recommendations to
improve performance. Tuning your databases with Database Engine Tuning
Advisor requires no expertise in database structure, workloads, or the internal
workings of SQL Server.

Database Engine Tuning Advisor provides two interfaces:

• A standalone graphical user interface tool for tuning databases and for

8 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

viewing tuning recommendations and reports.

• A command-line utility program, dta.exe, for Database Engine Tuning


Advisor functionality in software programs and scripts.
Report Manager is a Web-based report access and management tool that you can
use to manage a report server over an HTTP connection. You can use Report
Manager to:

• View, search, and subscribe to reports.


• Configure site properties and defaults.
• Configure role-based security that determines access to items and
Report Manager
operations.
• Configure report execution properties, report history, and report
parameters.
• Create report models.

• Create linked reports to reuse and repurpose an existing report in


different ways.

9 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

Database Concepts

Relational Database Concepts

Relational databases apply mathematical theories to efficiently organize and retrieve data within a
database. Database information is stored in tables, which are made up of rows and columns. The
following graphic shows several components of a database.

10 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

The following table describes common relational database components.

Component Description
A table is a collection or set of related data within a database and is known as a database
object. A database can contain one or more tables. Data within the table is organized as
follows:

• The table itself defines an object class. Data within the table is a collection of
discrete items that share common characteristics. In the example above, the table
contains data related to employees.
• Rows represent unique records in the database. In the above example, each row
Table
identifies a distinct employee.
• Columns represent fields within the record. Columns identify attributes that
describe, define, or are associated with the record. In this example, each
employee has common attributes of EmployeeID, LastName, FirstName, and
Extension.

• Values for each row and column identify the exact characteristics of each record.
For example, the LastName of the second employee in the table is King.
A primary key is a column guaranteed to have a unique value for each row in a table. A
primary key can be multiple columns which together have a unique value. In the table
Primary Key
above, the EmployeeID column is the primary key. The primary key column in each row
identified will contain a unique ID number for each employee.
A foreign key defines the relationship and correspondence between a column in one table
and primary key in another table. For example, another table might use the Extension
Foreign key
value as its primary key. In this situation, the Extension value would be a foreign key for
the table in the example.
Database The database organizes logical entities into database objects such as tables, indexes,
Objects views, and other objects.

• Tables, indexes, text data, ntext data, or image data are associated with a
filegroup.

11 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

• The data that is part of the database object is then striped across all physical files
in the filegroup.

In addition to the database itself, a relational database system includes a Database Management
System (DBMS). The role of the DBMS is to define the database structure, maintain relationships
within the database, control data access and modification, interact with physical server resources, and
define data recovery methods. The following table describes several common features of a DBMS.

Feature Description
A query is a statement containing one or more commands for a database. The
commands typically are a request to view or modify data. Queries are:

• Written in a structured language that is understood by the DBMS. For


example, SQL server uses Transact-SQL as the query language.
Queries
• Submitted by client applications to the DBMS. For example, database
management tools are client applications that connect to and submit queries to
the DBMS.

• Executed by the DBMS and returns the result to the client.


A search is performed by the DBMS for information requested in a query. The data
Searching and might be stored in multiple rows within a table or across tables or databases. An index
Indexing is used by a DBMS to organize data for frequent searches to improve performance and
data access.
Locking is used to coordinate changes in data management systems that support
multiple user access to a single database. At any time, the host system can have
multiple clients connected, all accessing different portions of the same database.
Locking:

• Prevents multiple users from changing the same piece of data at the same time.
Locking
• Allows only one client at a time to make changes to a table or row. Other
clients will be unable to modify the data while it is locked, although in many
cases they will still be able to see it while it is locked.

• Is released after the changes are made, at which time other clients can lock the
data for modification.
Transactions A transaction is a group of actions that are treated as a single unit. Transactions ensure
data integrity. The success of the entire transaction depends on the success of each of
the actions that are part of a transaction. None of the changes are made if errors are
encountered in any part of the transaction. When using transactions:

• The application signals the start of the transaction.


• The application submits the series of actions that are part of the transaction.
12 Taught by: Aiman Mobarak Elkhalifa
Microsoft SQL Server - Concepts 2
005

Each action is executed by the DBMS. All actions performed by the


application are considered part of the same transaction.
• The application signals the end of the transaction. If the end of the transaction
has been reached without error, the transaction is committed and the changes
become permanent.
• If there is an error during the transaction, the DBMS rolls back the changes,
putting the database in its original (unchanged) state.

Transactions are particularly useful in processing changes that are made across
databases or across servers. For example, if you were transferring money from one
bank account to another account, the transaction might involve servers at two different
banks. The transaction would not be completed unless the withdrawal from one
account and the deposit into the other account were both successful.

SQL Databases

SQL Server has two types of databases:

• System databases are used to store information about SQL Server and are essential for the
operation of a server instance.
• User databases are the databases created by users for storing their unique data.

The following table identifies specific databases used by SQL Server.

13 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

Database Database
Description
Type Name
The master database records all system-level information for the SQL Server system,
including the existence of all other databases and the location of their files, login account
master
information, and system configuration settings. A backup of this database should always be
available.
The model database is used as the template for all new databases. A backup of this database
model
should always be available.
The msdb database is used by SQL Server Agent for recording operators and scheduling
msdb jobs and alerts. This database also contains backup and restore history tables. A backup of
this database should always be available.
System The resource database contains all objects that ship with SQL Server. You must use a file-
resource
based or disk-based backup for this database and you cannot restore the file using SQL
(RDB)
Server restore.
The tempdb database is a temporary database that is used as a holding area for all
temporary tables, stored procedures, and temporary worktables used by the relational
tempdb
database engine. This database is recreated each time SQL Server is started–no data is saved
from one session to another.
The distribution database stores metadata and history data used in replication. A distribution
database is not created during installation–instead, it is created when SQL Server is
Distribution
configured for replication activities. In some instances, multiple distribution databases may
be used. A backup of this database should always be available.
User databases are created for use in your organization and hold data that you supply.

User A sample user database, AdventureWorks, is provided during installation as a learning tool
and model for creating user databases. AdventureWorks contains sample sales data for a
fictitious multinational manufacturing company. These databases and their tables are
frequently used as examples in SQL Server Books Online.

Database Objects

The various components of a database are known as objects. Databases can contain the following
objects:

Object Description
Database tables typically consist of columns and rows of data. The rows represent
Tables
unique records in the database, while the columns represent fields within the record.
Views Views identify the specific data that is displayed at any given time. Views can:

14 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

• Specify that only certain rows or columns are visible.


• Aggregate (summarize) data.

• Collect data from more than one table and present it as though it were from a
single table.
A database index is a structured list of the values in the table or view and the row
location of the value.

• Indexes can be clustered, where the data is sorted and stored based on the index
key.
Indexes
• A nonclustered index is separate from the data rows. Row locators in the index
point to the location of the data in either a clustered index key or in a heap.

• A table that is created with no index is called a heap, and the data rows are
stored in no particular order.
A stored procedure is a group of Transact-SQL statements compiled into a single
Stored execution plan. Stored procedures are typically used to achieve consistent
procedures implementation, improved performance, and a single point of control for commonly
performed tasks.
Constraints allow you to define the rules for the values allowed in columns. While
Constraints there are other methods of enforcing data integrity (i.e., triggers, rules, and defaults),
using constraints is the standard method for enforcing data integrity.
Defaults specify the values to be used in a column when no value is specified when a
Defaults
row is inserted.
A role is a profile that defines the security access controls and permissions. Assigning a
Roles
user to a role, gives that user the security privileges for the role.
An assembly is a .dll file created using .NET Framework common language runtime
Assemblies (CLR). Assemblies are used in an instance of SQL Server to deploy functions, stored
procedures, triggers, user-defined aggregates, and user-defined types.
Triggers are a special class of stored procedures defined to execute automatically
whenever an UPDATE, INSERT, or DELETE statement is issued against a table or
Triggers
view. Tables can have multiple triggers. Triggers can be used to enforce business rules
and automate processing for a company.
User-defined data types are based on pre-defined SQL Server 2005 data types. User-
User-defined defined data types are typically used when columns holding similar classes of data
data types must have the same base data type, length, and nullability. User-defined data types are
not supported in table variables.
User-defined User-defined functions are uniquely-named subroutines made up of one or more
functions Transact-SQL statements customized by the user for a specific purpose.

Additional objects are used by Analysis Services. The following table lists these objects.
15 Taught by: Aiman Mobarak Elkhalifa
Microsoft SQL Server - Concepts 2
005

Object Description
A data source is used by Analysis Services to identify the connection string that defines
Data Sources how Analysis Services connects to a physical data store using a managed Microsoft
.NET Framework or native OLE DB provider.
A data source view is a metadata definition of the schema objects used by Analysis
Data Source
Services. These schema elements are used by Unified Dimensional Model (UDM) and
Views
by the mining structures.
A cube is an arrangement of data in an array that allows for fast analysis. The
Cubes arrangement of data into cubes avoids a limitation of relational databases which are not
well suited for analysis of large amounts of data almost instantaneously.
A database dimension is a collection of attributes. These attributes provide information
Dimensions about fact data in one or more cubes. The attributes are bound to one or more columns
in one or more tables in a data source view.
A data mining model defines the algorithm used for data mining and how each column
is used by the model. A mining model inherits the values of the properties that are
Mining Model
defined by the mining structure. The model can use all the columns that the mining
structure contains or a subset of the columns.
Mining A mining structure defines the data domain from which mining models are built. A
Structures single mining structure can contain multiple mining models that share the same domain.
A role is a profile that defines the security access controls and permissions. Assigning a
Roles
user to a role, gives that user the security privileges for the role.
An assembly is a .dll file created using .NET Framework common language runtime
Assemblies (CLR). Assemblies are used in an instance of SQL Server to deploy functions, stored
procedures, triggers, user-defined aggregates, and user-defined types.
A measure represents a column of data (usually numeric) that can be aggregated --
Measures
processed as a set of values rather than as individual data values.
A measure group contains multiple measures that associate dimensions with measures.
Measure You can also use measure groups for measures that have distinct count as their
groups aggregation behavior. You can optimize aggregation processing by putting each distinct
count measure into its own measure group.
A hierarchy establishes the priority of entities used. Hierarchies can be established for
Hierarchies
attributes, data types, dimensions, cubes, etc.

16 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

Data Type Facts

As you define tables and other database objects and as you construct Transact SQL statements, the
data type is identified by using a keyword. The following table lists many common data type
keywords. Note: This list is not comprehensive.

Class Keyword Description


Integer (whole number) data from -263
bigint (-9,223,372,036,854,775,808) through 263-1
(9,223,372,036,854,775,807).
Integer Integer (whole number) data from -231 (-2,147,483,648) through
int
231-1 (2,147,483,647).
smallint Integer data from -215 (-32,768) through 215-1 (32,767).
tinyint Integer data from 0 through 255.

17 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

bit Integer data with either a 1 or 0 value.


Fixed precision and scale numeric data from -1038+1 through
decimal
1038-1.
Fixed precision and scale numeric data from -1038+1 through
Bit, Decimal, numeric
1038-1.
Numeric, and
Approximate Floating precision number data with the following valid values:
Numerics float -1.79E + 308 through -2.23E - 308, 0 and 2.23E + 308 through
1.79E + 308.
Floating precision number data with the following valid values:
real -3.40E + 38 through -1.18E - 38, 0 and 1.18E - 38 through 3.40E
+ 38.
Monetary data values from -263 (-922,337,203,685,477.5808)
money through 263-1 (+922,337,203,685,477.5807), with accuracy to a
ten-thousandth of a monetary unit.
Money
Monetary data values from -214,748.3648 through
smallmoney +214,748.3647, with accuracy to a ten-thousandth of a monetary
unit.
Date and time data from January 1, 1753, through December 31,
datetime 9999, with an accuracy of three-hundredths of a second, or 3.33
Date/Time milliseconds.
Date and time data from January 1, 1900, through June 6, 2079,
smalldatetime
with an accuracy of one minute.
Fixed-length non-Unicode character data with a maximum
char
length of 8,000 characters.
Variable-length non-Unicode data with a maximum of 8,000
varchar
characters.
Variable-length non-Unicode data with a maximum length of 231-
text
1 (2,147,483,647)
Character Strings Fixed-length Unicode data with a maximum length of 4,000
and Characters nchar
characters.
Variable-length Unicode data with a maximum length of 4,000
characters. sysname is a system-supplied user-defined data type
nvarchar
that is functionally equivalent to nvarchar(128) and is used to
reference database object names.
Variable-length Unicode data with a maximum length of 230-1
ntext
(1,073,741,823) characters.

18 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

binary Fixed-length binary data with a maximum length of 8,000 bytes.


Variable-length binary data with a maximum length of 8,000
varbinary
Binary Strings bytes.
Variable-length binary data with a maximum length of 231-1
image
(2,147,483,647) bytes.
cursor A reference to a cursor.
A data type that stores values of various SQL Server-supported
sql_variant
data types, except text, ntext, timestamp, and sql_variant.
Other Data Types table A special data type used to store a result set for later processing.
A database-wide unique number that gets updated every time a
timestamp
row gets updated.
uniqueidentifier A globally unique identifier (GUID).

In addition to the system-supplied data types, user-defined data types, which are based on system
data type, can be created for specific needs. When you create a column, you can specify the
maximum size of the data type using precision and scale.

• Precision is the total number of digits in a number.


• Scale is the number of digits to the right of the decimal point in a number.
• For example, the number 531.24 has a precision of 5 and a scale of 2.
• A column created as a numeric data type containing values similar to 531.24 would be
designated as Col_name (5,2). A column created as an integer containing values similar
to 5324 would be designated as Col_name (4).

Note: The primary and foreign keys of a table must be the same data type.

Transact-SQL Overview

19 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

Query Facts

A query is a request for data from a database. Client computers, whether running on the same
computer as SQL Server 2005 or on a separate client computer, do not access SQL Server directly.
Instead, they use applications written to access the data stored in SQL Server databases. Client
applications submit queries to SQL Server using one of the following formats:

Format Description
The primary database query and programming language used by
Transact-SQL
SQL Server.
A hypertext programming language used to return data from
Extensible Markup Language queries and stored procedures using URLs or templates over HTTP.
(XML) Also used to insert, delete, and update database values. The results
from these queries are returned as XML documents.
Multidimensional Expressions Syntax used to define multidimensional objects and queries and

20 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

(MDX) manipulate this data in an OLAP database.


Programming interfaces used to send Transact-SQL commands to a
OLE DB and ODBC APIs
database.
ADO wraps OLE DB for use in other programming languages;
used to access data in OLTP databases.
ActiveX Data Objects (ADO) and
ActiveX Data Objects
ADO MD is a language-independent set of object-based data access
(Multidimensional) (ADO MD)
interfaces optimized for multidimensional data applications; used to
access data in Analysis Services data cubes.
Application type using an automation API that lets users use natural
English Query language questions instead of more complex queries to access
database information.

Transact-SQL statements are a common way to interact with SQL server, view or modify data, or
change the configuration of the server. Queries are built using a series of statements, much like lines
of programming code. Even when you use a graphical management tool or submit queries using
another supported language, the queries are translated into Transact-SQL statements and then
executed. SQL Server 2005 uses the SQL-92 standard.

Queries can be simple or quite complex. The following example shows a simple query statement that
selects all columns from the Customers table for rows that match USA as the country:

SELECT *
FROM Customers
WHERE Country = 'USA'

Note: The example shown above is a single query statement. Statements can be written all on one
line or broken into several lines as shown above. When SQL server parses the query, it identifies all
elements that are part of the statement and executes one statement at a time.

Query statements can contain the following elements:

Component Description
Commands perform functions on the server or the database. Each statement begins with a
command. Four common commands are:

• SELECT retrieves rows from a table.


Commands
• UPDATE changes data in a table.
• INSERT adds a row to a table or a view.

• DELETE removes rows from a table.


Keywords Keywords are commands or command parameters used by SQL. In the example shown
above, the FROM and WHERE are keywords.
21 Taught by: Aiman Mobarak Elkhalifa
Microsoft SQL Server - Concepts 2
005

Note: Within documentation, keywords are written in all capital letters. When you write
Transact-SQL statements, case does not matter.
Identifiers are names of objects such as the server, a database, a table, or an index. In the
Identifiers
example above, Customers is an identifier that identifies the table used within the query.
Functions are collections of commands defined on the SQL server. When functions are
executed, they return a value. SQL Server comes with pre-defined functions (called
system functions), or you can define your own functions. Examples of functions include:

• DB_ID and DB_NAME return the database ID or name.


• OBJECT_ID and OBJECT_NAME return the object ID or name.
• COL_NAME returns the column name.
• COL_LENGTH returns the length of a column.
Functions • INDEX_COL returns an index column name.

When calling functions, follow the function name with parenthesis ( ). Inside include any
parameters that must be passed to the function. For example:

• The SELECT SUSER_NAME() statement returns the currently logged on user.

• The SELECT DB_ID('AdventureWorks') statement returns the ID of the


AdventureWorks database.
An expression is a combination of identifiers, values, and operators that SQL server can
Expressions evaluate to get a result. In example above, both * and Country = 'USA' are
expressions.
Operators perform actions on data. For example, you can use arithmetic operators to
Operators
perform mathematical operations on the data.
Datatypes define the format of the data used by table columns or variables. Each data
Datatypes type is identified by a keyword. In some cases, you have to identify the data type of any
variables used within the statement.
Comments Comments are nonexecuting remarks in a statement. Comments are indicated in one of
two ways:

• Double hyphens ( -- ). Any text on a line following the double hyphen will not
be included as part of the statement. Text on a new line that is not preceded by the
double hyphens is not commented.
• Forward slash-asterisk pairs ( /* ... */ ). Any text inside the character pair
will not be executed, even if it spans multiple lines.

For example, the following statement:


--get the list of names
SELECT Firstname /*, Lastname */
FROM Customers

22 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

WHERE Language = 'Spanish' --test for language


With the comments removed becomes:
SELECT Firstname
FROM Customers
WHERE Language = 'Spanish'

Be aware of the following when working with command syntax in documentation:

• Keywords are in all capital letters.


• Italics indicate identifiers, expressions, or functions.
• Items in brackets [ ] are optional. Do not type the brackets.
• Item in braces { } are required. Do not type the braces.
• Bolded items indicate items that must be typed exactly as shown such as databases, tables,
stored procedures, and utilities.
• Underline indicates the default value applied.
• Vertical bar | separates keywords enclosed in brackets or braces. You select only one.
• [,...n] indicates the preceding item can be repeated n number of times, separated by commas.
• [...n] indicates the preceding item can be repeated n number of times, separated by blank
spaces.
• <label>::= specifies the name for a block of syntax.

Batch Facts

A batch is a set of Transact-SQL statements that are executed together. For example, when you
submit a query from SQL Server Management Studio, the statements in the query are processed as a
batch. SQL server processes the batch as follows:

1. The batch statements are compiled into a single executable unit called an execution plan.
During compilation, the syntax of each statement is checked. If any statement has a syntax
error, the execution plan cannot be created and none of the statements are executed.
2. After the execution plan is created, each statement in the batch is executed one at a time, in
order. If a runtime error occurs, one of the following actions may be taken:
o Most run-time statements stop the current statement and the statements that follow it.
o Some run-time errors, such as constraint violations, stop the statement with the run-
time error and execute the remaining statements.
3. The statements executed before the runtime error are not affected unless the batch is a
transaction and the error causes the transaction to be rolled back.
4. SQL Server 2005 provides statement-level recompilation--the statement triggering a
recompilation is recompiled and not the whole batch.

You can save groups of SQL statements for later use by using one of the following methods:
23 Taught by: Aiman Mobarak Elkhalifa
Microsoft SQL Server - Concepts 2
005

Method Description
A script is a series of Transact-SQL statements stored in a file. The file can be used as
Scripts input to the sqlcmd utility or SQL Server Management Studio Code editor. The utilities
then execute the Transact-SQL statements stored in the file.
A stored procedure is a set of defined precompiled SQL statements stored on the server.
When you create the stored procedure, the execution plan is created and saved. When
you call the stored procedure, the saved execution plan is run. The stored procedure can
accept parameters, and can return result sets, return codes, and output parameters to the
calling application. Key facts about stored procedures are:

• SQL server comes with many pre-defined stored procedures (called system
stored procedures) for common tasks.
• System stored procedures begin with sp_.
Stored • Common system stored procedures include:
Procedures
o sp_helpdb returns information about databases on the server.
o sp_help returns a list of objects for the current database.
o sp_helpindex obj_name returns a list of indexes for the object.
• You can also define your own custom stored procedures.
• Do not name stored procedures you create beginning with sp_. Use another
unique prefix that will allow you to distinguish between system stored
procedures and the ones you create.

• To run a stored procedure, use the EXECUTE (or EXEC) command.


A trigger is a special type of stored procedure that is not called directly by a user. When
Triggers the trigger is created, it is defined to fire when a specific type of data modification (such
as when a DELETE action takes place) is made against a specific table or column.
A user-defined function is a routine that you can create to accept parameters, perform a
task, and return a result set. User-defined functions are stored in the database as reusable
code.
User-defined
A table valued function is a special type of user-defined function that returns results
functions
formatted in a table. The advantage of using table-valued user-defined functions is that
they can be referenced in a FROM clause of a Transact-SQL transaction whereas stored
procedures cannot. Also, you can use table-valued user-defined functions to perform
more complex logic than views.

Keep in mind the following when working with batches of commands:

• If a stored procedure is the first or only statement in a batch, you can omit the EXECUTE
statement.
• Some statements must be the first statement in a batch and cannot follow other statements in
a batch. These include CREATE DEFAULT, CREATE PROCEDURE, CREATE RULE,

24 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

CREATE TRIGGER, and CREATE VIEW. All other statements that follow in that batch will
be interpreted as part of the definition of the first CREATE statement.
• You cannot alter a table and then reference the new columns in the same batch.
• You can write scripts or create sets of statements in SQL Server Management Studio that
include multiple batches. Use the GO command to signal the end of a batch.
• Batch files may contain credentials stored in plain text. Credentials may be echoed to the
user's screen during batch execution.

When you look up stored procedures in the SQL documentation, you will see something like the
following:

sp_defaultlanguage [@loginame = ] 'login'


[,[@language = ] 'language']

Be aware of the following when working with commands and documentation:

• Items in brackets [ ] are optional. In this example, only the 'login' parameter is required.
• Parameters are values passed to the program. Parameters can be identified by a name and
value (such as @loginame = 'login'), or the parameter name can be omitted.
• If you omit the parameter name, you must enter parameters in the order shown.

SQL S er ver Installa tio n

25 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

Installation Requirements

SQL Server 2005 must run on a computer that has a version of the Windows operating system
installed. The following table summarizes the operating system requirements for a 32-bit installation
of SQL Server.

Windows Version(s) Supported SQL Version(s)


Express Edition and Express with
Windows 2003 Web Edition SP1
Advanced Services
Developer Edition
Windows XP Home Edition SP2 Express Edition and Express with
Advanced Services
Developer Edition
Windows 2000 Professional Edition SP4 Standard Edition
Windows XP Professional Edition SP2 Workgroup Edition
Windows XP Media Edition SP2 Express Edition and Express with
Windows XP Tablet Edition SP2 Advanced Services
Evaluation Edition
Windows 2000 Server SP4 Enterprise Edition
Windows 2000 Advanced Server SP4 Developer Edition
Windows 2000 Datacenter Edition SP4 Standard Edition
Windows 2003 Server SP1 Workgroup Edition
Windows 2003 R2 Express Edition and Express with
Windows 2003 Datacenter Edition SP1 Advanced Services
Windows Small Business Server 2003 Standard Edition SP1 Evaluation Edition
Windows Small Business Server 2003 Premium Edition SP1
26 Taught by: Aiman Mobarak Elkhalifa
Microsoft SQL Server - Concepts 2
005

Windows 2003 64-Bit X64 Standard Edition SP11


Windows 2003 64-Bit X64 Datacenter Edition SP11
Windows 2003 64-Bit X64 Enterprise Edition SP11
Developer Edition
Windows XP x64 Professional 20031
Standard Edition
1 Workgroup Edition
You can install SQL Server on Windows on Windows
Express Edition and Express with
(WOW64) 32-bit subsystem of a 64-bit server.
Advanced Services

The following table summarizes the operating system requirements for a 64-bit installation of SQL
Server.

Windows Version(s) Supported SQL Version(s)


Windows 2003 64-Bit Itanium Datacenter Edition Enterprise Edition (IA64)
SP1 Developer Edition (IA64)
Windows 2003 64-Bit Itanium Enterprise Edition Standard Edition (IA64)
SP1 Evaluation Edition (IA64)
Enterprise Edition (X64)
Windows 2003 64-Bit X64 Standard Edition SP15
Developer Edition (X64)
Windows 2003 64-Bit X64 Datacenter Edition
Standard Edition (X64)
SP15
Express Edition and Express with Advanced
Windows 2003 64-Bit X64 Enterprise Edition SP15
Services
Windows XP x64 Professional 2003
Evaluation Edition (X64)

Other requirements for a SQL Server 2005 installation are identified in the following table.

Component Supported SQL Version(s)


Client software requirements are:

• SQL Server 2005 32-bit client components can be installed on Windows


Client Software 2000 Professional SP4 or later.

• SQL Server 2005 64-bit client components can be installed on Windows


2003 (64-bit).
Installation SQL Server Setup requires:
Software
• Microsoft Windows Installer 3.1 or later and Microsoft Data Access
Components (MDAC) 2.8 SP1 or later.
• Microsoft Windows .NET Framework 2.0. (Automatically installed by
SQL Server 2005).
• Microsoft SQL Server Native Client. (Automatically installed by SQL

27 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

Server 2005).

• Microsoft SQL Server Setup support files. (Automatically installed by


SQL Server 2005).
Failover clusters require Microsoft Cluster Server (MSCS) on at least one node of
Clustering the server cluster. MSCS must be installed on a hardware configuration that has
been tested for compatibility with the MSCS software.
Integration Services (SSIS) programming, Analysis Management Objects (AMO),
Programming
and ADOMD.NET require Windows XP, Windows 2000, or Windows 2003.
Native Web Service
Windows 2003 is required for Native Web Service (SOAP/HTTP).
(SOAP/HTTP)
SQL Server (32-Bit and 64-Bit) requires the following hardware:

• Monitor - SQL Server graphical tools require VGA or higher resolution: at


least 1,024x768 pixel resolution.
• Pointing Device - A Microsoft mouse or compatible pointing device is
required.
• CD or DVD Drive - A CD or DVD drive, as appropriate, is required for
installation from CD or DVD media.
• Cluster Hardware Requirements - On both 32-bit and 64-bit platforms, up
to eight-node clusters are supported.
Hardware
• Processor (32-bit) - Pentium III-compatible processor or higher.
• Processor (64-bit) - exact requirements vary by edition. General
requirements are: IA64 minimum; Itanium processor or higher; X64
minimum: AMD Opteron, AMD Athlon 64, Intel Xeon with Intel EM64T
support, Intel Pentium IV with EM64T support.
• Processor speed 1 GHz or higher recommended.
• RAM - 1 GB recommended. For SQL Server 2005 Express Edition, 512
MB or higher is recommended.

• Hard disk space - 1.6 GB.


Internet Software The following Internet software is required:

• Microsoft Internet Explorer 6.0 SP1 or later is required for all installations
of SQL Server 2005. Internet Explorer 4.01 with Service Pack 2 or higher
is required when you are installing client components only and you are
connecting to a server that does not require encryption.
• Internet Information Services (IIS) 5.0 or later is required for Reporting
Services (SSRS) installations.
• ASP.NET 2.0 is required for Reporting Services. When installing
Reporting Services, SQL Server Setup will enable ASP.NET if it is not
already enabled.

28 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

• The 64-bit version of ASP.NET must be installed for a 64-bit installation


of Reporting Services on a 64-bit server. For (32-bit) installations of
Reporting Services on the 32-bit subsystem (WOW64) of a 64-bit server,
the 32-bit version of ASP.NET must be installed.

Installation Facts

Microsoft SQL Server 2005 Setup provides an integrated environment in which you can install a new
instance of SQL Server, upgrade existing instances, or perform maintenance tasks. As part of the
installation process:

• A system configuration check ensures that the computer has all required components for the
SQL Server installation.
• You can create a report that identifies the components required for installation and the results
of the configuration check.
• SQL Server Component Update installs the following components required for SQL Server
Setup:
o .NET Framework 2.0.
o Microsoft SQL Native Client - client network tool used by applications interfacing
with SQL Server and the SQL Server Management Tools.
o Microsoft SQL Server 2005 Setup Support Files.

By default, the SQL service runs under the MSSQLAct user account. The following table identifies
permissions required for installation based on the installation type.

Type of installation Permissions


Installing on the local Administrator permission on the computer on which SQL Server is being
computer installed.
Installing on a remote
Domain account with read and execute permissions on the remote share.
share
Installing a failover Local administrator with permission to logon as a service and act as part of the
cluster operating system for all nodes of the virtual server.

Before installation, select the method you will use for the installation.

• With a Standard installation, you are physically present, entering your selections directly
during the installation process. This type of installation allows you to select between a typical
and a custom installation, and make selections during the installation regarding specific
components to be installed.
• You can run the installation directly at the command prompt or by using an .ini file to specify
installation options.
• With SQL Server 2005, you can use scripts to perform remote installations.
29 Taught by: Aiman Mobarak Elkhalifa
Microsoft SQL Server - Concepts 2
005

During the installation process, you will need to be prepared to make the following choices:

Installation Step Description


You use the same setup program to install SQL Server as well as additional services
and client components. During installation, you can choose to install any of the
following components:

• SQL Server Database Services


• Analysis Services
• Reporting Services
• Notification Services
Components • Integration Services
• Client components
• Management tools
• SQL Server Books Online
• Sample databases, code, and applications

For example, to install the workstation components and management tools, run the
setup program and choose only those components (do not install the database engine
or other services).
You can install multiple instances (occurrences or installations) of SQL Server 2005
on the same computer. Each instance will operate independently, with its own
program and data files. All instances on a computer also share a set of common files.
Each instance is identified as either the default or a named instance.
Instance
• The default instance is called MSSQLServer. Only one default instance per
server is allowed.

• A named instance is identified by a custom instance name. Multiple named


instances may run on the same server, together with the default instance.
Service Accounts SQL Server runs as a set of services. As part of the installation process, you identify
and Services the user account that will be used for running the various services. By default, you
configure a single service account to be used by all services. When configuring the
service account, you have the following options:

• Domain user account–a dedicated domain user account, created exclusively


for the SQL Server and SQL Server Agent services. This account allows
communication with other SQL Server installations, Microsoft Exchange
Servers, and network resources within the domain environment. This
account needs special access rights on the local computer, but does not need
to be a domain administrator.
• Built-in system account–the two types of built-in system accounts are:
o Local Service account has the same level of access to resources and

30 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

objects as members of the Users group. Services using this account


access network resources as a null session with no credentials. This
account has no network access rights.
o Network Service account–Microsoft recommends that you do not
use this account.

You can also configure the following service options during setup:

• By default, all services use the same service account. During setup, you can
configure each service to use a different user account.

• You can selectively identify the services that will start up automatically
following the SQL Server installation.
The SQL Server authentication mode controls how SQL server validates server login
credentials. You configure the server to use one of two authentication modes.

• Windows Authentication Mode–Only users who have been previously


authenticated by the Windows operating system will be able to connect to
Authentication
SQL Server 2005. This is the recommended mode.
Mode
• Mixed Mode–Users connecting through a Microsoft Windows account will
be authenticated by the Windows operating system; other users will use SQL
Server Authentication which will require them to enter a username and
password to login to SQL Server 2005.
The collation type defines the language-based rules for your locale that will
determine how Unicode and non-Unicode data (which is specific to a particular
language) is sorted based on character sequence, character width, case-sensitivity,
accent marks, kana character types, etc. It also determines the rules for comparing
Unicode and non-Unicode data.

• The collation setting you choose during installation becomes the default
collation type for all databases and tables.
Collation Setting • Choose the collation type for the server based on the language and region by
most users.
• When you create a database, you can choose a collation setting that is
different from the default setting.
• To change the server default setting after installation, run Setup.exe with the
REBUILDDATABASE option.

All databases that are created without specifying the Windows collation name are
assigned Latin1_General, the default collation.

Security for your database is important. Consider the following to protect your data and your
network:
31 Taught by: Aiman Mobarak Elkhalifa
Microsoft SQL Server - Concepts 2
005

• Enhance physical security for servers and computers on which databases reside.
• Use firewalls between the server and the Internet.
• Create service accounts with least privileges.
• Require strong passwords.
• Implement strict ACL control.
• Disable server message block (SMB), NetBIOS, and ports used by NetBIOS. It is especially
important to disable these protocols and ports on servers.
• Never install databases on computer connected directly to the Internet.
• Whenever possible, do not install SQL Server on a domain controller.
• Ensure that all application backdoors are closed and default passwords are changed or
disabled.
• Maintain physical access control for device backdoors.
• Use Windows authentication mode.

32 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

Databases

33 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

Data File Facts

The following diagram shows the logical and physical components that make up a SQL database.

The various database components are described in the following table:

Component Description
A database is a logical collection of related data, organized into one or more tables.
Database Databases also include additional objects that are used by SQL server for defining the
database structure, improving performance, and performing locking and transactions.
File A file is a physical allocation of space on disk. Each database has two or more files,
and each file can be part of only one database.

• Data files hold the actual database objects and the data. Data files can be one
of two types:
o The primary data file is required.

34 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

 It contains startup information for the database catalog


and points to the other database files.
 The primary data file can also contain objects and user data.
 The recommended extension is .mdf.
o A secondary data file is optional, user-defined and stores user data.
 Each secondary data file can be put on a different disk drive to
boost performance.
 A database can contain a maximum of 32,766 secondary data
files. The recommended extension is .ndf.
 You can reduce disk access contention by storing all data and
objects in secondary files.

Note: Use a RAID 10 or a RAID 5 configuration to protect data files.

• Log files contain the transaction log for recovering the database's transactions.
o You must have at least one log file for each database.
o You can create multiple log files per database to facilitate faster
recovery.
o The recommended extension for log files is .ldf.

Note: Create log files on a different disk than data files. Use disk
mirroring (RAID) to protect log files.
A filegroup is collection of data files that are managed as a single unit. You can
increase performance by assigning different database objects (tables, indexes, etc.)
across several filegroups on different disk subsystems. Multiple filegroups allow for
selective back up and restore. You can also assign data files within the same filegroup
to different disks. The types of filegroups are:

• A primary filegroup contains the primary data file and secondary data files not
stored in another filegroup. All system tables are allocated to the primary
filegroup.
Filegroup
• A secondary filegroup contains secondary data files and database objects. A
database can contain up to 32,767 user-defined filegroups.
• The default filegroup contains objects that were created without an assigned
filegroup. The primary filegroup is the default filegroup unless another
filegroup is specified. You can specify the default filegroup by using the
ALTER DATABASE command.

Note: If a default filegroup other than the primary filegroup is specified, system
objects and tables are still created in the primary filegroup.

The placement of these files plays a key role in:

35 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

• Performance of your system.


• The capacity to provide data and operational processing even during a disruptive event
(high availability).
• The ability to function seamlessly in the event of a component failure (fault tolerance).

36 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

Create Database Facts

You can use one of the following methods to create a database:

• Create Database Wizard


• SQL Server Management Studio
• Scripts
• Transact-SQL

To create a database using Transact SQL, use the CREATE DATABASE statement followed by
the database name (all other parameters are optional). The following example creates a database
called MyDataBase:

CREATE DATABASE MyDataBase


ON
( NAME = 'DataFile1',
FILENAME = 'd:\dbfiles\MyDataFile.mdf',
SIZE = 10,
MAXSIZE = 100,
FILEGROWTH = 10 )
LOG ON
( NAME = 'LogFile1',
FILENAME = 'e:\logfiles\MyLogFile.ldf',
SIZE = 512KB,
MAXSIZE = 2MB,
FILEGROWTH = 512KB )

The following table describes each option in the CREATE DATABASE statement for creating
data and log files. Other options, such as specifying collation type, can be entered in the
CREATE DATABASE statement.

Transact-SQL
Description
Keyword
The ON keyword is followed by blocks (surrounded by parenthesis) that
define the datafile(s) for the database.

• The ON portion is optional. If not specified, the database will be


ON created with a single data file in the default location.

• Use the PRIMARY keyword after the ON keyword to identify the


primary data file. If PRIMARY is not used, the first file listed will be
the primary.
NAME Identifies the logical name for the file.
FILENAME Identifies the path and filename for the database or log file.

37 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

Configures the size of the data or log file.

Note: The SIZE, MAXSIZE, and FILEGROWTH values have the following
common characteristics:

• Numbers must be whole numbers (no decimals).


• Numbers can be followed by a suffix that identifies the unit of
measure (KB, MB, GB, or TB). If no suffix is used, MB is assumed.
SIZE
Following are additional considerations for the SIZE parameter:

• If the parameter is not included, the size for the primary datafile comes
from the size of the model database. Secondary files and log files
default to 1 MB.
• If included, the size for the primary datafile must be equal to or larger
than the primary datafile for the model database.

• The minimum size is 512 KB.


Configures the maximum size of the file. If no maximum size is specified, the
file can grow until the disk is full.
MAXSIZE
Note: If a transaction log file runs out of space, no further transactions can be
performed on that database until more space is made available.
Identifies the amount that a file can grow.

• In addition to unit suffixes (KB, MB, etc.), you can also specify a
percentage (%). If a suffix is not included, the default is MB.
FILEGROWTH • If the parameter is not included, the default is 10%.
• The minimum value is 64 KB. The maximum value is the same as
MAXSIZE.

• Set this value to 0 to prevent a file from growing automatically.


The LOG ON section identifies the log file(s) for the database. If not
LOG ON
specified, a single log file will be created in the default location.

Create Database Facts

38 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

You can use one of the following methods to create a database:

• Create Database Wizard


• SQL Server Management Studio
• Scripts
• Transact-SQL

To create a database using Transact SQL, use the CREATE DATABASE statement followed by
the database name (all other parameters are optional). The following example creates a database
called MyDataBase:

CREATE DATABASE MyDataBase


ON
( NAME = 'DataFile1',
FILENAME = 'd:\dbfiles\MyDataFile.mdf',
SIZE = 10,
MAXSIZE = 100,
FILEGROWTH = 10 )
LOG ON
( NAME = 'LogFile1',
FILENAME = 'e:\logfiles\MyLogFile.ldf',
SIZE = 512KB,
MAXSIZE = 2MB,
FILEGROWTH = 512KB )

The following table describes each option in the CREATE DATABASE statement for creating
data and log files. Other options, such as specifying collation type, can be entered in the
CREATE DATABASE statement.

Transact-SQL
Description
Keyword
The ON keyword is followed by blocks (surrounded by parenthesis) that
define the datafile(s) for the database.

• The ON portion is optional. If not specified, the database will be


ON created with a single data file in the default location.

• Use the PRIMARY keyword after the ON keyword to identify the


primary data file. If PRIMARY is not used, the first file listed will be
the primary.
NAME Identifies the logical name for the file.
FILENAME Identifies the path and filename for the database or log file.
SIZE Configures the size of the data or log file.

39 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

Note: The SIZE, MAXSIZE, and FILEGROWTH values have the following
common characteristics:

• Numbers must be whole numbers (no decimals).


• Numbers can be followed by a suffix that identifies the unit of
measure (KB, MB, GB, or TB). If no suffix is used, MB is assumed.

Following are additional considerations for the SIZE parameter:

• If the parameter is not included, the size for the primary datafile comes
from the size of the model database. Secondary files and log files
default to 1 MB.
• If included, the size for the primary datafile must be equal to or larger
than the primary datafile for the model database.

• The minimum size is 512 KB.


Configures the maximum size of the file. If no maximum size is specified, the
file can grow until the disk is full.
MAXSIZE
Note: If a transaction log file runs out of space, no further transactions can be
performed on that database until more space is made available.
Identifies the amount that a file can grow.

• In addition to unit suffixes (KB, MB, etc.), you can also specify a
percentage (%). If a suffix is not included, the default is MB.
FILEGROWTH • If the parameter is not included, the default is 10%.
• The minimum value is 64 KB. The maximum value is the same as
MAXSIZE.

• Set this value to 0 to prevent a file from growing automatically.


The LOG ON section identifies the log file(s) for the database. If not
LOG ON
specified, a single log file will be created in the default location.

40 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

Database Objects

Table Facts

41 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

After the database has been designed, you can then add the tables that will hold the data. Tables
can be created using SQL Server Management Studio, Transact-SQL scripting, or Table Objects
(SQL-SMO).

When you create a table, you define the columns on the table. A table can have up to 1,024
columns. The following table describes some properties you can set for a column.

Property Description
Column names must be unique within a specific table (however, you may have
the same column name in a different table). While table names must be unique
Name
for each owner in the database, different owners can have tables of the same
name. Column names must follow SQL Server 2005 naming rules.
The data type defines the characteristic of the data that is stored in the column.
Data types are defined using the standard SQL data type keywords (see Data
Data type Type Facts). The data type should be chosen based on the information you wish
to store. For example, you would not use an integer data type for an employee
name column.
The data length defines the size of the data string that can be held in the
column. The data length is automatically defined for most data types. You may
Data length
modify the data length property for binary, char, nchar, varbinary, varchar,
and nvarchar data types.
When turned on, the NULL value property allows the rows in that table to have
a null value for that column. NULL is not the same thing as a zero (0) or blank
data. Instead, NULL represents a value that is as yet undefined.

• You can allow or disallow NULL values for columns.


• When NOT NULL is defined, users must enter a value when a new row
is added.
NULL/NOT
• If NULL is allowed, SQL Server automatically supplies NULL when
NULL
you insert a row with no value for a column that allows null values. A
user can also explicitly enter NULL.

Allowing NULL values in columns can cause problems with data integrity. It
also makes queries and updates more complex. However, you can only modify
an existing column to disallow NULL if no null values exist in the column and
there is no index created on the column.
The DEFAULT property defines a value that is automatically added to the
DEFAULT
column when a new row is defined.
IDENTITY Use the IDENTITY property to define an identifier column. An identifier
column holds system-generated sequential values that identify each row in the
table. Use the following two values with the IDENTITY property:

42 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

• The seed property defines the starting number.


• The increment property defines the increment to be added to the seed
for each subsequent identity number.

Be aware of the following when using the IDENTITY value:

• Each table can have only one identifier column, and the column cannot
allow NULL values or contain a DEFAULT.
• If you choose not to define the seed and increment values, the default for
each is 1. However, if you define the seed value, you must define the
increment value (and vice versa).
• An IDENTITY column must use one of the following data types:
decimal, int, numeric, smallint, bigint, or tinyint.

• SQL Server ensures that each value in the IDENTITY column is unique.
However, uniqueness is enforced only within the column. Uniqueness is
not enforced between other columns or tables.
The ROWGUIDCOL property identifies a column as a global identifier column.
This means that the values in the column can be used across tables within the
database.

• You can only have one ROWGUIDCOL column.


• The data type must be set to uniqueidentifier.
ROWGUIDCOL
• The setting does not automatically generate values. You must use a
DEFAULT with a NEWID function to generate automatic values if
desired.

• ROWGUIDCOL does not guarantee uniqueness. You must use a


UNIQUE constraint to ensure uniqueness.

The following example creates a table called Tbl_BldgStarts with five columns. Note the data
type and length specified for each.

CREATE TABLE Tbl_BldgStarts


(
Col_StAddr nvarchar (20),
Col_City nvarchar (20),
Col_State nvarchar (12),
Col_BlgdNum int IDENTITY (1001,1) NOT NULL,
--Create global identifier column. Values are generated automatically
Col_MyConstrNum uniqueidentier ROWGUIDCOL NOT NULL DEFAULT (newid ())
)

43 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

Constraint Facts

A constraint is a table column property that performs data validation. Using constraints, you can
maintain database integrity by preventing invalid data from being entered.
44 Taught by: Aiman Mobarak Elkhalifa
Microsoft SQL Server - Concepts 2
005

Note: Rules are objects used in previous versions of SQL Server to enforce data integrity. You
should use constraints instead of rules.

Data validation can be performed on the row level or the column level.

• The row-level constraints are PRIMARY KEY and FOREIGN KEY.


• The column-level constraints are NOT NULL, DEFAULT, UNIQUE, and CHECK.

The table below describes the classes of constraints:

Constraint
Description
Class
A NOT NULL constraint restricts users from entering null values into the
NOT NULL column. Do not confuse a NULL with a zero (0) or a blank space. A NULL
represents an unknown value.
A CHECK constraint limits the values that are accepted by a column. CHECK
constraints determine the acceptable value by using a logical expression that
evaluates to a true or false condition. If the conditions are not met, the input is
rejected. For example, you can define a CHECK constraint to make sure that the
value contains the correct number of digits (such as 5 digits for a zip code) or that the
value is within a certain range (such as between 1 and 1,000). When using CHECK
constraints:
CHECK
• You can have multiple CHECK constraints for a column.
• Create the constraint at the table level to apply a single CHECK constraint to
multiple columns.

Note: If necessary, you can temporarily disable a CHECK constraint. However, data
integrity will not be enforced while the constraint is disabled.
A PRIMARY KEY constraint enforces unique values for each row in a column (or
set of columns). If a value is entered that already exists in the column, it is rejected.
Facts about PRIMARY KEY constraints are:

• PRIMARY KEY constraints do not support NULL values.


• The PRIMARY KEY setting defines the identity column. Because the values
PRIMARY
are guaranteed to be unique, the PRIMARY KEY can be used for row
KEY
identifiers.
• Each table can have only a single PRIMARY KEY (although the key may use
multiple columns as long as the combination of column values is unique for
each row).

• The PRIMARY KEY is used when defining inter-table relationships.

45 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

A UNIQUE constraint enforces unique values for each entry in a column. If a value
is entered that already exists in the column, it is rejected. Facts about UNIQUE
constraints are:

• UNIQUE constraints are implemented as unique indexes.


• A UNIQUE constraint allows one NULL value per column.
UNIQUE
• You can have multiple UNIQUE constraints for a table.
• Columns included in the UNIQUE constraint cannot be part of the
PRIMARY KEY.
• UNIQUE constraints are also used when defining inter-table relationships.

• UNIQUE constraints can be referenced by FOREIGN KEY constraints.


FOREIGN A FOREIGN KEY is a column (or set of columns) used to establish a relationship
KEY between columns in two different tables. Click Foreign Key Relationship to view a
diagram of two related tables.

• The FOREIGN KEY identifies a column that is linked to another column


with a PRIMARY KEY or a UNIQUE constraint.
• All columns in the relationship must be the same data type, but they do not
need to have the same name.
• FOREIGN KEY constraints are used to coordinate data between the columns
defined in the relationship. You can use a FOREIGN KEY to specify that a
column allows only the values contained in the referenced table column.
• A self-referencing table is a table with a foreign key that references columns
in other tables in the same database or other columns in the same table.

When configuring a FOREIGN KEY constraint, you can use the following settings to
customize how referential integrity is enforced:

• Check Existing Data on Creation or Re-Enabling ensures that data


integrity exists when the FOREIGN KEY is first established.
• Enforce for Replication applies the constraint when a replication agent
performs an insert, update, or delete.
• Enforce Foreign Key Constraint prevents changes that would invalidate the
integrity of the foreign key relationship.
• Enforce for INSERTS and UPDATES specifies what happens if a user tries
to insert or update a row with data that is involved in a foreign key
relationship.
o No Action generates an error message and rolls the delete or update
back.
o Cascade inserts or updates data in one column when data is changed
in the other column.

46 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

o Set Null sets the value to null if all foreign key columns for the table
can accept null values.

Set Default sets the value to the default value for the column if all
o
foreign key columns for the table have defined defaults (SQL Server
2005 only).
The DEFAULT keyword defines a value that is used if the user doesn't specify a
DEFAULT value for the column. The default value can be a constant or the result of a built-in
function or mathematical expression (getdate( ) for example).

You should know the following facts about constraints:

• Constraints can be created when the table is created or added later using the ALTER
TABLE statement.
• SQL Server will automatically create a randomly generated name for each constraint
unless you specify a name.
• The recommended approach is to add the constraints later with ALTER TABLE
statements and name the constraints. It is easier to modify or drop constraints if they were
added using ALTER TABLE. This example uses the ADD CONSTRAINT keyword to
create a PRIMARY KEY constraint:
• ALTER TABLE MyTable
• ADD CONSTRAINT PK_MyTable_CustID
PRIMARY (custid)

• Constraints can be created on columns or on tables.


• A table constraint is the only way to apply a single constraint to more than one column.
• A column cannot be deleted if it is referenced by a FOREIGN KEY constraint. Drop the
FOREIGN KEY constraint in order to delete columns (including columns with a
PRIMARY KEY constraint) referenced by a FOREIGN KEY.
• If you change the data type in one column, the data type in the other column will be
changed as well.

Use constraints to enforce data integrity. Data integrity includes the following types:

• Entity integrity ensures that all database rows have a PRIMARY KEY value, that the
value is not NULL, and that the values are not duplicated (are unique). Entity integrity is
enforced by setting a PRIMARY KEY for the table.
• Domain integrity ensures that values within a column are valid (for example, data type,
format, and value range). Use CHECK constraints to enforce the format or the range of
possible values. You can also use FOREIGN KEY and NOT NULL constraints to restrict
the range of possible values.
• Referential integrity ensures that defined relationships between tables are preserved when
rows are updated or deleted. In SQL Server 2005, relationships are defined between
47 Taught by: Aiman Mobarak Elkhalifa
Microsoft SQL Server - Concepts 2
005

foreign keys and primary keys or between foreign keys and unique keys, using
FOREIGN KEY and CHECK constraints. Referential integrity prevents user changes that
would affect the relationship between the tables, such as dropping a foreign key table
while the FOREIGN KEY constraint exists.
• User-defined integrity ensures that data meets specific user-defined business rules that are
added to the constraints.

Constraint Management Facts

You can use constraints to create rules that allow SQL Server 2005 to maintain the integrity of
your database automatically. You can create constraints using:

• The CONSTRAINT keyword in the CREATE TABLE statement as you create the table.
• The CONSTRAINT keyword in the ALTER TABLE statement after you have created the
table.

48 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

The table below gives you code examples for creating each type of constraint supported by SQL
Server 2005.

Method Description
In the following example, the photos table uses photo_id as the primary
key.
CREATE TABLE photos
(
photo_id int PRIMARY KEY,
photo_title char(50),
Create a type char(10),
PRIMARY KEY date_prod date,
constraint camera char(25),
lens char(15),
publisher_id int,
pub_date date,
);
You can also use the ALTER TABLE statement.
ALTER TABLE photos ADD PRIMARY KEY (photo_id);
In the following example, the photos table is created with a UNIQUE
constraint for the photo_title, date_prod, and pub_date columns.
CREATE TABLE photos
(
photo_id int,
photo_title char(50),
type char(10),
Create a date_prod date,
camera char(25),
UNIQUE
lens char(15),
constraint publisher_id int,
pub_date date,
CONSTRAINT PhotoConstraint UNIQUE (photo_title, date_prod,
pub_date)
);
You can also use the ALTER TABLE statement.
ALTER TABLE photos ADD CONSTRAINT
PhotoConstraint UNIQUE (photo_title, date_prod, pub_date);
Create a CHECK In the following example, the photos table is created with a CHECK constraint
constraint named colortype for the type column.
CREATE TABLE photos
(
photo_id int,
photo_title char(50),
type char(10),
date_prod date,
camera char(25),
lens char(15),
publisher_id int,
pub_date date,
49 Taught by: Aiman Mobarak Elkhalifa
Microsoft SQL Server - Concepts 2
005

CONSTRAINT colortype CHECK (type IN ('bw','color'))


);
You can also use the ALTER STATEMENT table.
ALTER TABLE photos ADD CONSTRAINT
colortype CHECK (type IN ('bw','color));
In the following example, a FOREIGN KEY constraint is created for the
photos table by referencing a pub_id column in the publishers table.
Deleting rows from this column is not allowed. Transactions that would delete
rows from the table with the PRIMARY KEY are rolled back.
CREATE TABLE photos
(
photo_id int,
photo_title char(50),
type char(10),
Create a date_prod date,
FOREIGN KEY camera char(25),
constraint lens char(15),
publisher_id int FOREIGN KEY REFERENCES publishers(pub_id)
ON DELETE NO ACTION,
pub_date date,
);
You can also use the ALTER TABLE statement.
ALTER TABLE photos
ADD CONSTRAINT publisher_id
FOREIGN KEY (pub_id)
REFERENCES publishers (pub_id) MATCH FULL;
This creates two NULL constraints.
CREATE TABLE photos
(
photo_id int NO NULL,
photo_title char(50) NO NULL,
type char(10),
date_prod date,
Create a NULL camera char(25),
constraint lens char(15),
publisher_id int,
pub_date date,
);
You can also use the ALTER TABLE statement.
ALTER TABLE photos ALTER COLUMN photo_id SET NOT NULL,
photo_title SET NOT NULL;

50 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

DML Trigger Facts

A DML trigger is a type of stored procedure that executes when the DML (Data Manipulation
Language) statements UPDATE, INSERT, or DELETE run against a table or a view. You can use
DML triggers in the following ways:

• To define error messages and display them if a particular action is performed.


• To perform additional inserts into tables.
• To store application logic.
• To compare data before modification (for example, verifying that an action is allowed,
and if it is not, to perform a rollback of the database to the previous values).

51 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

• To enforce complex data integrity, such as looking at other values in the database before
completing an action.

The table below describes the types of DML triggers you can execute.

Trigger Type Description


An AFTER trigger executes after the statement that triggered it completes.

• Multiple AFTER triggers can be specified for each INSERT, UPDATE, or


DELETE triggering action.
• AFTER triggers can be specified for tables but not for views.
AFTER
• When creating a trigger, the trigger is created as an AFTER trigger unless
trigger
you specify INSTEAD OF.

• An AFTER trigger executes after the successful execution of a Transact-


SQL statement including all referential cascade actions and constraint
checks associated with the object updated or deleted.
An INSTEAD OF trigger executes in place of the triggering action.

• Only one INSTEAD OF trigger can be specified for each INSERT,


UPDATE, or DELETE triggering action.
INSTEAD OF
• When the action takes place, the trigger executes instead of the normal
trigger
action that would take place for the action.

• Unlike AFTER triggers, INSTEAD OF triggers can be specified for both


tables and views.

Much like constraints, it is possible to enforce data integrity through triggers. However, you
should use constraints whenever possible. Listed below are some conditions when you might
need to use a trigger instead of a constraint:

• A CHECK constraint uses a true/false condition to allow or reject changes. Triggers can
execute more complex checking that does not evaluate to a true/false condition or that
can take multiple actions besides a simple accept or reject.
• A CHECK constraint can accept or reject changes based on a simple comparison between
data in two columns within a table. A trigger can compare values in columns in different
tables.
• A FOREIGN KEY constraint can accept or reject updates based on data comparison
between tables, but can only look for an exact match unless cascading referential actions
are used. Triggers can implement more complex conditions.

52 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

• Constraints can use system messages only for reporting errors. With triggers, you can
customize error messages and mechanisms. For example, you can send a message
through e-mail when the trigger executes.

You should also know the following facts about triggers:

• Triggers run automatically when the specified action takes place.


• You must have permissions to all objects referenced by the trigger.
• Triggers can be linked, if necessary, to perform a series of actions in a particular situation.
• Triggers are reactive (meaning the action has already taken place before the trigger is
fired).
• When an INSERT or DELETE trigger is associated with a table, any data inserted or
deleted from the table will be written to a corresponding temporary table.
• Use ALTER TRIGGER to modify a trigger.
• Use ENABLE and DISABLE TRIGGER to control whether a trigger fires without
dropping the trigger. For DML triggers, you can also use ALTER TABLE to enable or
disable a trigger.
• Use DROP TRIGGER to delete a trigger.
• You should not use a trigger on a system table.

In the following example, a trigger fires when the specified conditions are met.

GO
--create trigger
CREATE TRIGGER BlgComplete.EscrowReturn ON Tbl_Complete
AFTER UPDATE (EscrowAmt)
AS
DECLARE @escwamt numeric,
@workorders tinyint
--specify conditions for firing trigger
SELECT @escwamt = b.EscrowAmt, @workorder = w.WorkOrders
FROM BldgComplete.Tbl_Complete AS b, BldgProgress.Tbl_Workorders AS w
IF @workorder >= 1
BEGIN
--specify actions when trigger is fired
INSERT INTO BldgComplete.Tbl_Funds (EscrowHold)
VALUES @escwamt
END

When implementing triggers, be aware of the following:

• Triggers perform in the following ways when a constraint exists on the table the trigger is
acting on:
o The constraint is checked after the INSTEAD OF trigger execution. If constraints
are violated, the actions executed by the INSTEAD OF trigger are rolled back.

53 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

o The constraint is checked before the AFTER trigger execution. The AFTER
trigger is not fired if the constraint has been violated.
• You can specify the first and last trigger to execute on a table by using the
sp_settriggerorder stored procedure. When using AFTER triggers, only one first and
one last trigger for each INSERT, UPDATE, and DELETE operation is allowed.
• Triggers not specified as first or last are randomly executed.
• Using ALTER TRIGGER eliminates first and last trigger designations.
• The UPDATE( ) function allows you to define a trigger based on an update or insertion
into a column. The COLUMNS_UPDATED keyword allows you to define a trigger
based on an update or insertion into multiple columns.
• You cannot use INSTEAD OF DELETE/UPDATE triggers when a table has a foreign
key with a cascade on DELETE/UPDATE action defined.
• Qualify the table name in the same way that you qualify the trigger name. For example,
when you use MySchema.MyTrigger, use MySchema.MyTable.
• A SET statement in a trigger, reverts to its former setting after the trigger is executed.
• A DELETE trigger will not catch a TRUNCATE TABLE statement.

The following Transact-SQL statements are not allowed in a DML trigger:

• ALTER DATABASE
• CREATE DATABASE
• DROP DATABASE
• LOAD DATABASE
• LOAD LOG
• RECONFIGURE
• RESTORE DATABASE
• RESTORE LOG

In SQL Server 2005, you cannot use the following Transact-SQL statements inside the body of a
DML trigger used against the table or view that is the target of the triggering action.

• CREATE INDEX
• ALTER INDEX
• DROP INDEX
• DBCC DBREINDEX
• ALTER PARTITION FUNCTION
• DROP TABLE
• ALTER TABLE when used to do the following:
o Add, modify, or drop columns
o Switch partitions
o Add or drop PRIMARY KEY or UNIQUE constraints

54 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

View Facts

A view is a stored SELECT statement that works like a virtual table. The data available through
the view continues to reside in the base table (or tables). When the view is referenced, it returns
a virtual table that can be referenced and manipulated much like an actual table.

Common uses for views include the following:

55 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

• Hiding the complexity of the database by showing only the data a user needs instead of
entire tables.
• Securing the database by granting permissions to the view. Users need permissions only
to the view, not to the underlying table objects.
• Combining data from multiple tables, columns, or sources into what looks like a single
table.
• Aggregate data by, for example, showing the sum of a column rather than individual
values in the column.
• Exporting data by using the bcp (bulk copy) utility to send the view results to an outside
application (such as a spreadsheet application).

Be aware of the following when using views:

• Views are objects stored in the database.


• When a view is used, it is compiled and executed at the server, returning the data.
• Views can reference data in multiple tables and across multiple databases on the same or
even remote servers. In addition, views can reference other views.
• Modifying a view does not change the permissions of the view. If you drop a view,
however, the permissions must be reassigned.
• Views have the following restrictions:
o Views cannot use ORDER BY, COMPUTE, or COMPUTE BY clauses.
o Views cannot use the INTO keyword.
o Views cannot update data if the update affects more than one base table
referenced in the view.
• You can bind the view to the table schema with the SCHEMABINDING keyword. When
using SCHEMABINDING:
o You must include the owner name with SELECT statements (such as
dbo.tbl_composers). One, three, or four-part names are not allowed.
o Tables cannot be altered if the changes affect columns referenced in the view. You
must drop the view before modifying the table structure.
o Other views used by the view cannot be dropped. Remove the schema binding
first.

Views simplify data access and can be used for security administration. They do not, however,
increase performance by themselves. To improve performance, you can create an index of the
view. Keep in mind the following when using indexes for views:

• Indexes for views are clustered.


• Once the index is created, SQL Server may use the index for other queries, not just for
accessing the view.
• Because of the system load imposed in maintaining indexes for views, you should limit
their use to views that reference columns that change infrequently. Do not index views
where the data has many writes or updates.
56 Taught by: Aiman Mobarak Elkhalifa
Microsoft SQL Server - Concepts 2
005

• Use indexes for views that include many JOIN statements across many rows.
• Indexed views are only supported on the Enterprise or Developer editions of SQL Server.
• The view must use the SCHEMABINDING statement.
• Be aware of the following limitations:
o You cannot create an index on a view that references tables in more than one
database.
o You cannot index views that include UNION statements.
o You cannot index views that use other views.

In the following example, the PhotoSold view is created in the WeingholdGallery


schema:

CREATE VIEW WeingholdGallery.PhotoSold


WITH SCHEMABINDING
AS
--identify columns to return
SELECT (p.pk_photo_id , p.photo_name , p.photographer_name ,
s.purchaser_name , s.purchase_date )
--identify the table
FROM WeingholdGallery.Sales_info AS s
INNER JOIN WeingholdGallery.Photos AS p
--return where the following two values are equal
WHERE p.pk_photo_id = s.fk_photo_id

For a view to be updatable, it must meet the following criteria:

• Changes can be made to only one base table.


• The table has a primary key defined.
• You cannot change columns with derived data (e.g., from aggregate functions).
• The columns being modified are not affected by GROUP BY, HAVING, or DISTINCT
clauses.
• The select statement that creates the view cannot contain a TOP keyword with a WITH
CHECK OPTION clause.

Stored Procedure Facts

A stored procedure is precompiled code that can be reused. It is precompiled, stored as an object
in the database under a single name, and is processed as a unit. Like other kinds of programs, a
stored procedure can:

• Use input parameters and return multiple values in the form of output parameters.
• Contain programming statements that perform operations in the database, including
calling other procedures.
• Perform calculations.

57 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

• Invoke data definition language (DDL) and data manipulation language (DML)
statements.
• Return a status value to a calling procedure or batch to indicate success or failure (and the
reason for failure).

Stored procedures are useful for:

• Ensuring consistent implementation of a task across applications. All of the logic needed
to perform the task can be created and verified once and then saved as a stored procedure
for reuse as necessary.
• Improving performance. The execution plan is stored in cache. Also, the results of one
procedure can be coded to determine which of the subsequent procedures should be
performed next and automatically move through the predetermined steps of the execution
plan with no user intervention required.
• Protecting the contents of the database. Users with authorization to run the procedure
have no need to view or access underlying tables to find the information they require.

The following table describes the types of stored procedures available in Microsoft SQL Server
2005.

Type Description
System stored procedures are stored procedures supplied by SQL Server. They
perform common administrative activities.

System stored procedures are stored in the Resource database and have the sp_
prefix. System stored procedures logically appear in the sys schema of every
system- and user-defined database. In SQL Server 2005, GRANT, DENY, and
System Stored REVOKE permissions can be applied to system stored procedures.
Procedures
Commonly used system stored procedures include:

• sp_help provides information on the specified database object or data type.


• sp_helpdb provides information on the specified database.

• sp_helpindex provides information on the index for the specified table.


User-defined User-defined stored procedures are stored procedures created to perform specific
Stored tasks to meet the needs of a particular environment. There are two ways to create
Procedures stored procedures:

• Using traditional Transact-SQL statements. This method is preferred when


the stored procedure accesses data using little or no procedural logic.

58 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

• Using CLR (common language runtime) managed code such as the .NET
Framework languages Visual Basic, .NET, or Visual C#. This method is
preferred when the stored procedure performs CPU-intensive functions,
calculations, and complex logic. CLR is also the choice when accessing
objects such as the network or file system, or to run processor-intensive
code on the client computers.
Extended system stored procedures (xp_ prefix) are stored procedures that
interface between SQL Server and external programs for maintenance activities.
Extended
Extended stored procedures can be written using a programming language like C.
Stored
Procedures
Note: Extended stored procedures will be dropped in a future release. Use user-
defined, CLR-created stored procedures instead of extended stored procedures.
SQL Server also supports temporary stored procedures that are deleted
automatically when you disconnect from the server. These may occasionally be
Temporary
useful when working with applications that build dynamic Transact-SQL
Stored
statements that need to be executed multiple times, or for working with earlier
Procedures
versions of SQL Server. CLR stored procedures cannot be created as temporary
stored procedures.

The following guidelines apply to both CLR managed code and Transact-SQL stored procedures.

• You can create a stored procedure only in the current database.


• Validate all user input before you use it.
• Use the EXEC keyword to call a stored procedure.
• CREATE PROCEDURE statements cannot be combined with other SQL statements in a
single batch.
• Stored procedures must be recompiled if the database structure changes. If performance
begins to decline, recompile stored procedures. Using the sp_recompile system stored
procedure forces a recompile of a stored procedure the next time it is run.
• The following statements cannot be used in a stored procedure:

CREATE AGGREGATE
CREATE RULE
CREATE DEFAULT
CREATE SCHEMA
CREATE or ALTER FUNCTION
CREATE or ALTER TRIGGER
CREATE or ALTER PROCEDURE
CREATE or ALTER VIEW
SET PARSEONLY
SET SHOWPLAN_ALL

59 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

SET SHOWPLAN_TEXT
SET SHOWPLAN_XML
USE database_name

Follow these rules when using stored procedures to create and use database objects:

• You can reference an object created in the same stored procedure as long as you create it
before it is referenced.
• You can create and reference temporary tables. The temporary table is no longer available
when you exit the stored procedure.
• If you execute a stored procedure that calls another stored procedure, the called stored
procedure can access all objects created by the first stored procedure, including
temporary tables.
• If you execute a remote stored procedure that makes changes on a remote instance of
Microsoft SQL Server 2005, those changes cannot be rolled back. Remote stored
procedures do not take part in transactions.
• If you have permission to execute a stored procedure, you don't need permissions to the
underlying tables that the stored procedure uses or modifies.

The following example creates a stored procedure called uspDailyGalleryNumbers.

GO
--create the stored procedure
CREATE PROCEDURE GalleryInfo.uspDailyGalleryNumbers
AS
BEGIN
--variable for storing a date
DECLARE @ReportDate
--Recompile the stored procedure
WITH RECOMPILE
--identify table and columns to insert data into
INSERT GalleryDailyFinancial
(
Col_SalesForDay ,
Col_BeginInv ,
Col_EndInv ,
Col_NetCash ,
Col_DateTotal
)
GO
--join tables and identify columns to choose data from
SELECT DailySales, StartInv, EndingInv, NetSales , TotalForDay
SUM(SaleTotal)
FROM NewYorkGallery n
FULL JOIN PhiladelphiaGallery p
ON n.SaleDate = p.SaleDate
FULL JOIN Baltimore b
ON p.SaleDate = b.SaleDate

60 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

WHERE SaleDate = @ReportDate


END
GO

Note: You can use the WITH ENCRYPTION clause to prevent information about the stored
procedure from being returned when sp_helptext is executed.

The following example shows how to execute the stored procedure created above. The value
'20051025' is a constant for the declared variable in the stored procedure.

Use ConsolidatedGalleries
GO
EXEC GalleryInfo.uspDailyGalleryNumbers '20051025'
GO

Managed Code Facts

Code that runs in Microsoft's common language runtime (CLR) is called managed code. You can
create managed code using a .NET Framework language such as Visual Basic .NET or Visual
C#. In SQL Server you can use managed code to write:

• Stored procedures
• Triggers
• User-defined functions, aggregates, and types

Although you can write the same type of code using Transact-SQL, managed code does a better
job of handling calculations and complex execution logic. The table below identifies situations to
use managed code and situations to use Transact-SQL.

Type of
Decision Criteria
Code
Use managed code when:

• You want to access the functionality of the .NET Framework.


Managed
• The code performs complex logic that is CPU-intensive.
Code
•You want the code to run on the client side to leverage the processing power of
the client computer rather than tax the server.
Transact- Use Transact-SQL when:
SQL

61 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

• The code primarily accesses data and has little or no procedural logic.

• The code can run on the server without impacting performance.

By default, SQL Server does not allow you to run managed code. To run managed code, enable
the CLR by running the sp_configure system stored procedure or using the SQL Server Surface
Configuration Tool.

Permission levels for managed code are specified when the assembly for the code is created. The
three permission levels for managed code are specified below.

• Safe code can be run only by SQL Server. It has programming model and verifiability
restrictions and cannot call unmanaged code.
• External code can run outside of SQL Server against other programs or entities such as
the file system. The code has programming model and verifiability restrictions and cannot
call unmanaged code. In order to execute managed code that will execute outside of SQL,
you must use the ALTER DATABASE statement to set TRUSTWORTHY to on.
• Unsafe code does not have any access, programming model, or verifiability restrictions.
The code has the ability to call unmanaged code. This permission is for highly trusted
code.

Data Manipulation

62 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

DML Statement Facts

Data Manipulation Language (DML) refers to a family of computer languages of which


Transact-SQL is a member.

The most commonly used DML statements are INSERT, UPDATE, and DELETE. You can also
use SELECT statements with INTO clauses to insert data into a table. The statements have
keywords, clauses, and operators that enable you to perform a variety of functions using these
four statements. The following table describes actions that maybe commonly used in databases.

Action Example
63 Taught by: Aiman Mobarak Elkhalifa
Microsoft SQL Server - Concepts 2
005

In the following example, three records are added to the CrewList table.
Each record contains values for the CrewName, the CrewForeman and
the CrewSize columns. The table is in the MyConstruction
database.
USE MyConstruction
GO
Insert data into a table INSERT INTO CrewList (CrewName , CrewForeman , CrewSize)
VALUES 'CrewD' , 'Samuel Smith', 22
INSERT INTO CrewList (CrewName , CrewForeman , CrewSize)
VALUES 'CrewE' , 'Miguel Gomez', 43
INSERT INTO CrewList (CrewName , CrewForeman , CrewSize)
VALUES 'CrewF' , 'Jacob Ouahib', 37
GO
In the following example, the data inserted in the previous example is
updated. You will change the CrewSize for CrewD to be 31.
USE MyConstruction
Update data in a table GO
UPDATE CREWLIST
SET CrewSize = 31
WHERE CrewForeman = Samuel Smith
GO
In the following example, the record (row) for CrewG is deleted from the
CrewList table.
Delete a record in a USE MyConstruction
GO
table
DELETE CREWLIST
WHERE CrewName = CrewG
GO
In the following example, a record for each unique value in the BldgTyp
column of the CrewReport table in the MyConstruction database is
inserted into the BldgTypsInProg column of the CrewBldgTyp
Use the DISTINCT
table.
operator to return only USE MyConstruction
unique values. GO
SELECT DISTINCT BldgTyp
FROM Building.CrewReport
INTO CrewBldgTyp AS BldgTypsInProg

The following table identifies terms you may encounter while working with DML statements.

Term Definition
Ad hoc names Ad hoc names allow SQL logins to query an OLE DB database source that is
not defined as a linked server. Facts about ad hoc names are:

• When ad hoc names are enabled, any authenticated SQL login can

64 Taught by: Aiman Mobarak Elkhalifa


Microsoft SQL Server - Concepts 2
005

access the OLE DB database source.


• This type of access should be used infrequently, if at all.

• These types of queries use OPENROWSET and


OPENDATASOURCE functions.
An aggregate function performs a calculation on several rows or cells of
data and returns a single result. Examples of aggregate functions are AVG
Aggregate function
(returns the average of the group), COUNT (returns the number in the
group), MAX (returns the highest value in the group).
Common table
A common table expression (CTE) is a temporary result set.
expression
Deterministic
A deterministic function returns the same value each time it is executed.
function
Metadata is data about data. Metadata can be used to describe objects within
SQL Server such as table information (number of columns, column names,
Metadata
datatypes of the columns, etc.) or it can be used to describe the content of
the objects such as the information within the table.
Nondeterministic A nondeterministic function may return a different value each time it is
function executed.
A recursive common table expression is a CTE that is executed multiple
Recursive common
times. The result of each execution of the CTE is a subset of data used in
table expression
another CTE until the final result is obtained.
Recursive query A recursive query is a query that references a recursive CTE.
Scalar refers to a single value as opposed to an array which consists of
Scalar
multiple values.
A subquery is a query expressed in a SELECT statement that returns a single
Subquery value and is nested inside a SELECT, INSERT, UPDATE, or DELETE
statement or another subquery.

65 Taught by: Aiman Mobarak Elkhalifa

You might also like