SQL Server 2005 Concepts
SQL Server 2005 Concepts
SQL Server 2005 Concepts
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:
• 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:
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:
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.
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:
• 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:
• 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:
• 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:
• 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.
• A standalone graphical user interface tool for tuning databases and for
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.
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.
• 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:
• 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:
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
• 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.
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:
• 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.
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.
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.
Note: The primary and foreign keys of a table must be the same data type.
Transact-SQL Overview
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
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.
Component Description
Commands perform functions on the server or the database. Each statement begins with a
command. Four common commands are:
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:
When calling functions, follow the function name with parenthesis ( ). Inside include any
parameters that must be passed to the function. For example:
• 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.
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.
• 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,
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:
• 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.
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.
The following table summarizes the operating system requirements for a 64-bit installation of SQL
Server.
Other requirements for a SQL Server 2005 installation are identified in the following table.
Server 2005).
• 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.
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.
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:
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.
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.
• 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.
Databases
The following diagram shows the logical and physical components that make up a SQL database.
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.
• 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.
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:
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.
Note: The SIZE, MAXSIZE, and FILEGROWTH values have the following
common characteristics:
• 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.
• 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.
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:
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.
Note: The SIZE, MAXSIZE, and FILEGROWTH values have the following
common characteristics:
• 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.
• 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.
Database Objects
Table Facts
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.
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:
• 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.
The following example creates a table called Tbl_BldgStarts with five columns. Note the data
type and length specified for each.
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.
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:
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:
When configuring a FOREIGN KEY constraint, you can use the following settings to
customize how referential integrity is enforced:
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).
• 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)
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.
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.
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
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 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.
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.
• 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.
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
• 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.
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.
• 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
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.
• 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).
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:
• 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.
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.
• 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).
• 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:
• 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.
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
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.
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
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
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:
• The code primarily accesses data and has little or no procedural logic.
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
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