SQL Server 2005 Concepts

Published on March 2017 | Categories: Documents | Downloads: 44 | Comments: 0 | Views: 313
of 65
Download PDF   Embed   Report

Comments

Content

 

Microsoft SQL Server - Concepts   2 005

1

Taught aught by by: Aiman Aiman Mobarak Mobarak Elkhali Elkhalifa fa

 

Microsoft SQL Server - Concepts   2 005

SQL Serv Ser ver Over Overview view

SQL Server 2005 Overview 2

Taught aught by by: Aiman Aiman Mobarak Mobarak Elkhali Elkhalifa fa

 

Microsoft SQL Server - Concepts   2 005

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

SQL Server Database Engine

Description The SQL Server Database Engine 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: server



Controlled access Replication Full-text search Relational data management tools XML data management tools Rapid transaction processing for data-consuming data-consuming applications



Outstanding support to sustain availability

• • • • •

SQL Server Analysis Services (SSAS) provides Online Analy Analytical tical Processing (OLAP) and data mining functionality for business intelligence solutions. You can use SSAS to design, create, maintain, and visualize: SQL Server Analysis Services





OLAP multi-dimensional multi-dimensional structures that contain aggregated data from relational databases or additional sources. Data mining models that are constructed from data sources by using industrystandard 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 o Matrix reports o Graphical reports o Free-form reports Publish reports in a variety of formats Develop report applications applications



Manage security and subscriptions centrally



SQL Server Reporting Services •

SQL Server  Notification  Notificatio n Services 3

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

Taught aught by by: Aiman Aiman Mobarak Mobarak Elkhali Elkhalifa fa

 

Microsoft SQL Server - Concepts   2 005



Generate and send timely, 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) (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 An Integrations service Ta Tasks sks for performing workflow functions such as: o FTP operations o Executing SQL statements o Sending e-mail messages Application programming 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



SQL Server Integration Services

• • •



4

Taught aught by by: Aiman Aiman Mobarak Mobarak Elkhali Elkhalifa fa

 

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 Edition includes  includes the complete set of enterprise data management and business intelligence features. SQL Server Enterprise offers offers the highest levels of scalability and availability. Enterprise Edition supports:

SQL Server 2005 Enterprise Edition

• • •

Data warehousing systems 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.

SQL Server 2005 Standard Edition

Standard Edition is an affordable option for small- and medium-sized organizat organizations. ions. It includes the core functionality needed for non-critical e-commerce, data warehousing, and line-of business solutions. solutions. Standard Edition is optimized to run on win32, x64, and Itanium-based servers.

SQL Server 2005 Workgroup Edition

Workgroup Edition is Edition is the data management solution for small organizations or workgroups within larger entities. It includes all the core database features needed for data management. Workgroup Edition is available only on a 32-bit platform.

SQL Server 2005 Express Edition

 Express Edition Edition is  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 a basic server database. Express Edition is available only on a 32-bit platform.  Developer Edition Edition is  is designed for application developers. It includes all the functionality of

SQL Server 2005 Developer Edition

Enterprise Edition. License restrictions limit the use of this version to application development and testing only. It is not for use as a production server. Developer Edition runs on win32, x64, and Itanium-based servers.

SQL Server 2005 Mobile Edition

 Mobile Edition Edition allows  allows organizations to extend enterprise data management and business intelligence capabilities to mobile devices. Mobile Edition can replicate to a SQL 2005 Enterprise or Standard Edition environment. Mobile Edition is only available on a 32-bit platform.

5

Taught aught by by: Aiman Aiman Mobarak Mobarak Elkhali Elkhalifa fa

 

Microsoft SQL Server - Concepts   2 005

Ma na gem ent T oo ooll s

SQL Tool Facts

6

Taught aught by by: Aiman Aiman Mobarak Mobarak Elkhali Elkhalifa fa

 

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. computer 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. implementation. Using its graphical gr aphical interface and script editors, you can use SQL Server Management Studio to perform such tasks as: • • • •

SQL Server Management Studio

• •

Create databases, tables, indexes, views, etc. Perform database maintenance maintenance Perform server maintenance on servers Manage security Register multiple servers 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 solut solutions. ions. It integrates into into Microsoft Visual V isual Studiocomponents with project types types specifically designed for business intelligence. The primary componen ts of SQL SQL Server Business Server Business Intelligence Development Studio are: Intelligence Development Studio Analysis Services Integration Services • •



SQL Server Configuration Manager

7

Reporting Services

SQL Server Configuration Manager  enables you to manage SQL Server services. SQL Server Configuration Manager is a Microsoft Management Management 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:

Taught aught by by: Aiman Aiman Mobarak Mobarak Elkhali Elkhalifa fa

 

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 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  provides a graphical graphical user interface to SQL SQL Trace. 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 Services. Analyzing Analyzin g query patterns.



Capturing event data to a file or table.



SQL Server Profiler 

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





Database Engine Tuning Advisor 

Enable and disable features, services, and network protocols for remote connectionss to help reduce the surface area of your SQL Server connection installations. 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 Configuratio n (SAC) utility to export settings.

The Database Engine Tuning Advisor analyzes the performance effects of 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 Advisor provides two interfaces: •

8

A standalone standalone graphical user interface tool for f or tuning databases and for

Taught aught by by: Aiman Aiman Mobarak Mobarak Elkhali Elkhalifa fa

 

Microsoft SQL Server - Concepts   2 005

viewing tuning recommendations and reports. •

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

Advisor functionality functionality in software sof tware 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: • •

Report Manager 









9

View, search, and subscribe to reports. Configure site properties and defaults. Configure role-based security that determines access to items and operations. Configure report execution properties, report history, history, and report  parameters. Create report models. Create linked reports to reuse and repurpose an existing report in different ways.

Taught aught by by: Aiman Aiman Mobarak Mobarak Elkhali Elkhalifa fa

 

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 information is stored in tables, which are made up of rows and columns. The following graphic shows several components of a database.

10

Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

Microsoft SQL Server - Concepts   2 005

The following table describes common relational r elational database components. Comp Co mpon onen entt

Desc Descri ript ptio ion n A table is a collection or set of related r elated 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: •



Table





The table itself defines an object class 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 identifies a distinct employee. Columns represent 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, EmployeeID, LastName, FirstName, and Extension. Values  for each row and column identify the exact characte Values for characteristics ristics of each record. For example, the LastName of the second employee in the table is King.

A primary key is key is a column guaranteed to have a unique value for each row in a table. A  primary key can be multiple columns columns which together together have a unique unique value. In the tab table le 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 foreig  foreign n key defines key defines the relationship and correspondence 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 would be a foreign key for the table in the example. Database Objects

The database organizes logical entities into database objects such objects such as tables, indexes, views, and other objects. •

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

11

Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

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, 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 query is  is a statement containing one or more commands for a database. The commands typically typically are a request to view or modify data. Queries are: •

Queries



Written in a structured language that is understood by the DBMS. For example, SQL server uses Transact-SQL as the query language. Submitted by client applications applications to the DBMS. For example, database management tools are client applications that connect to and submit queries to management the DBMS.



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

A search  search is  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  is used to coordinate changes in data management management systems that support multiple user access to a single database. At any time, the host system can have multiple clients connected, connected, all accessing different portions of the same database. Locking: •

Locking





Transactions

Is released after the changes are made, at which time other clients can lock the data for modification. modification.

A transaction transaction is  is a group of actions that are treated as a single unit. Transactions ensure data integrity. 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: • •

12

Prevents multiple users from changing the same piece of data at the same time. 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.

The application of of theactions transaction. The application signals submitsthe submits thestart series that are part of the transaction.

Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

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  and the changes  become permanent. permanent. If there is an error during the transaction, the DBMS rolls back  the  the changes,  putting the database database in its original original (unchanged) (unchanged) state.

Transactions are particularly useful in processing changes that are made across Transactions databases or across servers. For example, if you were transferring money from one  bank account account to another account, account, the transaction might involve involve servers at two different different  banks. The transaction transaction would would not be completed completed unless the withdrawal 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 System databases operation of a server instance. User  databases  databases are the databases created by users for storing their unique data.

The following table identifies specific databases used by SQL Server. 13

Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

Microsoft SQL Server - Concepts   2 005

Database Database Type  Name

master

Description The master database records all system-level information for the SQL Server system, The  including the existence of all other databases and the location of their files, login account information, and system configuration settings. A backup of this database should always be available.

System

model

The model database is used as the template for all new databases. A backup of this database The  should always be available.

msdb

The  msdb database is used by SQL Server Agent for recording operators and scheduling The  jobs and alerts. This database al also so contains backup aand nd restore hist history ory tables. A backup backup of this database should always be available.

resource (RDB)

The  resource  database contains all objects that ship with SQL Server. You must use a fileThe  based or disk-based backup for this database and you cannot restore the fi file le using SQL Server restore.

tempdb

The tempdb database is a temporary database that is used as a holding area for all The  temporary tables, stored procedures, and temporary worktables used by the relational database engine. This database is recreated each time SQL Server is started–no data is saved from one session to another.

The distribution 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 dat database abase should alw always ays be available. User databases are created for use in your organization and hold data that you supply. supply. A sample user database,  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. company. These databases and their tables are frequently used as examples in SQL Server Books Online.

User 

Database Objects

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

Description

Tables

Database tables typically consist of columns and rows of data. The rows represent unique records in the database, while the columns represent fields within the record.

Views

Views identify Views  identify the specific data that is displayed at any given time. Views can: 14

Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

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 index is  is a structured list of the values in the table or view and the row location of the value. •

Indexes





Indexes can be clustered , where the data is sorted and stored based on the index key. A nonclustered  index  index is separate from from the data rows. Row locators in the index  point to the location location of the data data in either a clustered clustered index key or in a heap. heap. A table that is created with no index is called a heap heap,, and the data rows are stored in no particular order.

Stored  procedures

A stored procedure procedure is  is a group of Transact-SQL statements compiled into a single execution plan. Stored procedures are typically used to achieve consistent implementation, implement ation, improved performance, and a single point of control for commonly  performed tasks.

Constraints

Constraints allow you to define the rules for the values allowed in columns. Whil Constraints allow Whilee there are other methods of enforcing data integrity (i.e., triggers, rules, and defaults), using constraints is the standard method for enforcing data integrity. integrity.

Defaults

 Defaults specify the values to be used in a column when no value is specified when a  Defaults specify row is inserted.

Roles

A role role is  is a profile that defines the security access controls and permissions. Assigning a user to a role, gives that user the security privileges for the role. An assembly assembly is  is a .dll file created using .NET Framework common language language runtime

Assemblies

(CLR). Assemblies Assemblies are used in an instance of o f SQL Server to deploy functions, stored  procedures, triggers, triggers, user-defined aggre aggregates, gates, and user-defin user-defined ed types.

Triggers

Triggers are a special class of stored procedures defined to execute autom Triggers are automatically atically whenever an UPDATE, INSERT, or DELETE statement is issued against a table or view. Tables can have multiple triggers. Triggers can be used to enforce business rules and automate processing for a company.

User-defined data types

User-defined data types are types are based on pre-defined SQL Server 2005 data types. Userdefined data types are typically used when columns holding similar classes of data must have the same base data type, length, and nullability. User-defined data types are not supported in table variables.

User-defined functions

User-defined  functions  functions are uniquely-named subroutines made up of one or more Transact-SQL statements customized by the user for a specific purpose.

Additionall objects are used by Analysis Additiona Analysis Services. The following table lists these objects. 15

Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

Microsoft SQL Server - Concepts   2 005

Object

Description

A data source is source is used by Analysi Analysiss Services to identify the connection string that defines Data Sources how Analysis Analysis Services connects to a physical data store using a managed Microsoft .NET Framework or native OLE DB provider. Data Source Views

A data source view is view is a metadata definition of the schema objects used by Analysis Services. These schema elements are used by Unified Dimensiona Dimensionall Model (UDM) and  by the mining mining structures.

Cubes

A cube cube is  is an arrangement of data in an array that allows for fast analysis. The arrangement of data into cubes avoids a limitation limitation of relational databases which are not well suited for analysis of large amounts of data almost instantaneously.

Dimensions

A database dimension is dimension is a collection of attributes. These attributes provide information 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 Structures

A mining structure defines structure defines the data domain from which mining models are built. A single mining structure can contain multiple mining models that share the same domain.

Roles

A role role is  is a profile that defines the security access controls and permissions. Assignin Assigning ga user to a role, gives that user the security privileges for the role.

Assemblies

An assembly assembly is  is a .dll file created using .NET Framework common language runtime (CLR). Assemblies Assemblies are used in an instance of SQL Serve Serverr to deploy functions, stored  procedures, triggers, triggers, user-defined agg aggregates, regates, and user-defined user-defined types.

Measures

A measure measure represents  represents a column of data (usually numeric) that can be aggregated - processed as a set of values values rather than as ind individual ividual data values. values. A measure group contains group contains multiple measures that associate dimensions with measures.

Measure groups

Y ou can alsobehavior. use measure for measures that have distinctby count as their aggregation Yougroups can optimize aggregation processing putting each distinct count measure into its own measure group.

Hierarchies

16

A hierarchy hierarchy establishes  establishes the priority of entities used. Hierarchies can be established for attributes, data types, dimensions, cubes, etc.

Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

Microsoft SQL Server - Concepts   2 005

Data Type Facts

As you define tables and other database objects and as you construct Transac Transactt 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

Integer 

17

Keyword

Description

 bigint

Integer (whole number) data from -263 (-9,223,372,036,854,775,808) (-9,223,372,036 ,854,775,808) through 263-1 (9,223,372,036,854,775,807).

int

Integer (whole number) data from -231 (-2,147,483,648) through 231-1 (2,147,483,647). (2,147,483,647).

smallint

Integer data from -215 (-32,768) through 215-1 (32,767).

tinyint

Integer data from 0 through 255.

Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

Microsoft SQL Server - Concepts   2 005

 bit

Integer data with with either a 1 or 0 value. value.

decimal

Fixed precision and scale numeric data from -1038+1 through 1038-1. 38

Bit, Decimal,  Numeric, and Approximate  Numerics

numeric

Fixed 1038-1.precision and scale numeric data from -10 +1 through

float

Floating precision number data with the following valid values: -1.79E + 308 through -2.23E - 308, 0 and 2.23E + 308 through 1.79E + 308.

real

Floating precision number data with the following valid values: -3.40E + 38 through -1.18E - 38, 0 and 1.18E - 38 through 3.40E + 38.

money

Monetary data values from -263 (-922,337,203,685,477.5808) (-922,337,203,685,477.5808) 63 through 2 -1 (+922,337,203,685,477.5807), (+922,337,203,685,477.5807), with accuracy to a ten-thousandth ten-thousand th of a monetary unit.

Money

Monetary data values from -214,748.3648 -214,748.3648 through smallmoney

+214,748.36 +214,748.3647, 47, with accuracy to a ten-thousandth of a monetary unit.

datetime

Date and time data from January 1, 1753, through December 31, 9999, with an accuracy of three-hundredths of a second, or 3.33 milliseconds.

smalldatetime

Date and time data from January 1, 1900, through June 6, 2079, with an accuracy of one minute.

char 

Fixed-length non-Unicode character data with a maximum Fixed-length length of 8,000 characters.

varchar 

Variable-length non-Unicode data with a maximum of 8,000 characters.

Date/Time

text Character Strings and Characters

18

nchar 

Variable-length non-Unicode data with a maximum length of 2311 (2,147,483,647) (2,147,483,647) Fixed-length Fixed-lengt h Unicode data with a maximum length of 4,000 characters.

nvarchar 

Variable-length Unicode data with a maximum length of 4,000 characters. sysname is a system-supplied system-supplied user-defined data type that is functionally equivalent to nvarchar(128) and is used to reference database object names.

ntext

Variable-length Unicode data with a maximum length of 2 30-1 (1,073,741,823) (1,073,741,82 3) characters.

Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

Microsoft SQL Server - Concepts   2 005

Binary Strings

 binary

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

varbinary

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

Other Data Types

image

Variable-length (2,147,483,64 (2,147,483,647) 7)binary bytes. data with a maximum length of 2 -1

cursor

A reference to a cursor.

sql_variant

A data type that stores values of various SQL Server-supported data types, except text, ntext, timestamp, and sql_variant.

table

A special data type used to store a result set for for later processing.

timestamp

A database-wide unique number that gets updated every time a row gets updated.

uniqueidentifier uniqueiden tifier A globally unique identifier identifier (GUID). (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 precisi using  precision on and  and scale  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 aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

Microsoft SQL Server - Concepts   2 005

Query Facts

A query query is  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 applicationss submit queries to SQL Server using one of the following formats: application Format

Description

Transact-SQL

The primary database query and programming language used by SQL Server.

Extensible Markup Language (XML)

A hypertext programming language used to return data from queries and stored procedures using URLs or templates over HTTP. Also used to insert, delete, and update database values. The results from these queries are returned as XML documents.

Multidimensional Multidim ensional Expressions

Syntax used to define multidimensional multidimensional objects and queries and

20

Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

Microsoft SQL Server - Concepts   2 005

(MDX)

manipulate this data in an OLAP database.

OLE DB and ODBC APIs

Programming interfaces used to send Transact-SQL commands to a database.

ADOtowraps OLE for usedatabases. in other programming languages; used access dataDB in OLTP ActiveX Data Objects (ADO) and ActiveX Data Objects ADO MD is a language-independent language-independent set of object-based 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 Application language questions instead of more complex queries to access database information.

English Query

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 Transact-SQL -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: Comp Co mpone onent nt Descr Descript iption ion Commands perform functions on the server or the database. Each statement begins with a Commands perform command. Four common commands are: Commands

Keywords 21



SELECT retrieves rows from a table. UPDATE changes data in a table. INSERT adds a row to a table or a view.



DELETE removes rows from a table.

• •

 Keywords are  Keywords  are commands commands or command parameters used by SQL. In the example shown above, the FROM and WHERE are keywords. Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

Microsoft SQL Server - Concepts   2 005

Note: Withi  Within n 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 are 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  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: • • • •

Functions



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. INDEX_COL returns an index column name.

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



The SELECT SUSER_NAME() statement returns the currently logged on user. The SELECT DB_ID('AdventureWorks') DB_ID('AdventureWorks') statement returns the ID of the AdventureWorks database.

An expression expression is  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

Operators perform actions on data. For example, you can use arithmetic operators to Operators perform  perform mathematical mathematical operations operations on the data.  Datatypes define  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 o f any variables used within the statement.

Comments

Comments  are nonexecuting remarks in a statement. Comments Comments are 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 part of the statement. statement. Text Text on a new line line that is not preceded preceded by the double hyphens is not commented. Forward slash-asterisk pairs (  /* ... */ ). Any text inside the character pair will not be executed, even if i f it spans multiple lines.

For example, the following statement: --get the list of names SELECT Firstname /*, Lastname */   FROM Customers

22

Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

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 documentati documentation: on: • • • • •

• • • •



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

1. The batch statements are compiled into a single executable unit called an execution plan. plan. During compilation, 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 order f ollowing actions actions may be taken: o Most run-time statements stop the current statement and the statements that follow it. violations, s, stop the statement with the runo Some run-time errors, such as constraint violation 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 provides statement-level statement-level recompilation--the recompilation--the statement triggering a recompilation recompilati on is recompiled r ecompiled and not the whole batch. You can save groups of SQL statements for later use by using one of the following methods: 23

Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

Microsoft SQL Server - Concepts   2 005

Method

Description

Scripts

A script  is  is a series of Transact-SQL Transact-SQL statements statements stored in a file. The file can be used as 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 procedu procedure re 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. application. Key facts about stored procedures are: •

Stored Procedures

• •

• •



SQL server comes with many pre-defined stored procedures (called system stored procedures) for common tasks. System stored procedures begin with sp_  with sp_ . Common system stored procedures include: o sp_helpdb returns information about databases on the server. o f objects for the current database. o sp_help returns a list of 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 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 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.

Triggers

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 functions are stored in the database as reusable code. User-defined A table valued function is 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 transaction whereas stored  procedures cannot. cannot. Also, Also, you can use table-valued table-valued user-defined user-defined functions to perform 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 in clude CREA CRE ATE DEF DE FAULT AULT, CREA CRE ATE PROCEDURE, PROCE DURE, CREA C REATE TE RULE, RULE , 24

Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

Microsoft SQL Server - Concepts   2 005

• •



CREATE TRIGGER, and CREATE VIEW. All other statements that follow in that batch will  be interpreted as part part of the definition of the the first CREATE 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  Parameters are values passed to the program. Parameters can bebe identified value (such  are as @loginame = 'login'), or the parameter name can omitted.by a name and If you omit the parameter name, you must enter parameters in the order shown.

QL

25

er ver Installa tio n

Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

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 summarizes the operating system requirements for a 32-bit installation of SQL Server. Windows Version(s)

Supported SQL Version(s)

Windows 2003 Web Edition SP1

Express Edition and Express with Advanced Services

Windows XP Home Edition SP2

Developer Edition Express Edition and Express with Advanced Services

Windows 2000 Professional Edition SP4 Windows XP Professional Edition SP2 Windows XP Media Edition SP2 Windows XP Tablet Edition SP2

Developer Edition Standard Edition Workgroup Edition Express Edition and Express with Advanced Services Evaluation Edition

Windows 2000 Server SP4 Windows 2000 Advanced Server SP4 Windows 2000 Datacenter Edition SP4 Windows 2003 Server SP1 Windows 2003 R2 Windows 2003 Datacenter Edition SP1

Enterprise Edition Developer Edition Standard Edition Workgroup Edition Express Edition and Express with Advanced Services

Windows Windows Small Small Business Business Server Server 2003 2003 Standard Premium Edition Edition SP1 SP1

Evaluation Edition

26

Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

Microsoft SQL Server - Concepts   2 005

Windows 2003 64-Bit X64 Standard Edition SP11 Windows 2003 64-Bit X64 Datacenter Edition SP1 1 Windows 2003 64-Bit X64 Enterprise Edition SP1 1 1

Windows XP x64 Professional 2003   1

You can install SQL Server on Windows on Windows (WOW64) 32-bit subsystem of a 64-bit server.

Developer Edition Standard Edition Workgroup Edition Express Edition and Express with 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 SP1 Windows 2003 64-Bit Itanium Enterprise Edition SP1

Enterprise Edition (IA64) Developer Edition (IA64) Standard Edition (IA64) 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 SP1 5 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: •

Client Software •

Installation Software

SQL Server 2005 64-bit client components can be installed on Windows 2003 (64-bit).

SQL Server Setup requires: •





27

SQL Server 2005 32-bit client components can be installed on Windows 2000 Professional SP4 or later.

Microsoft Windows Windows Installer 3.1 or later and Microsoft Data Access Components (MDAC) 2.8 SP1 or later. Microsoft Windows Windows .NET Framework 2.0. (Automati ( Automatically cally installed by SQL Server 2005). Microsoft SQL Server Native Client. (Automatically installed by SQL

Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

Microsoft SQL Server - Concepts   2 005

Server 2005). •

Microsoft SQL Server Setup support files. (Automatically installed by SQL Server 2005).

Clustering

Failover clusters require Microsoft Cluster Server (MSCS) on at least one node of the server cluster. MSCS must be installed on a hardware configuration that has  been tested for compatibility compatibility with with the MSCS software. software.

Programming

Integration Services (SSIS) programming, Analysis Management Objects (AMO), and ADOMD.NET require Windows XP, Windows 2000, or Windows 2003.

 Native Web Web Service Windows 2003 is required for Native Web Service (SOAP/HTTP). (SOAP/HTTP) SQL Server (32-Bit and 64-Bit) requires the following f ollowing hardware: •







Hardware

• •

• •



Intern Int ernet et Softw Software are

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. Processor (32-bit) - Pentium III-compatible processor or higher. 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. recommended. Hard disk space - 1.6 GB.

The fol follow lowing ing Inter Internet net soft softwar waree is requir required: ed: •





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 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 aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

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 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 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 required for installation installation based on the installation installation type. Type ype of in insta stallat llatio ion n

Perm ermissi ssions ons

Installing on the local Administ Administrator rator 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 cluster 

Local administrator administrator with permission to logon as a service and act as part of the 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 installation allows you to select between a typical and a custom installation, and make selections during the installation regarding specific componentss to be installed. component 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 aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

Microsoft SQL Server - Concepts   2 005

During the installation process, you will need to be prepared to make the following choices: Instal Ins tallat lation ion Step Step Descri Descripti ption on 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: • • • •

Components

• • • • •

SQL Server Database Services Analysis Services Reporting Services  Notification  Notificatio n Services Integration Services Client components Management tools SQL Server Books Online Sample databases, code, and application applicationss

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 instances (occurrences  (occurrences or installation i nstallations) s) of SQL Server 2005 on the same computer. Each instance will operate independently, with its own  program and data files. All All instances on a computer computer also share a set of common files. Each instance is identified as either the default or a named instance. Instance





The default  instance  instance is called MSSQLServer. MSSQLServer. Only one default instance per server is allowed. A named  instance  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 r unning 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 account–the two types of built-in system accounts are: o

30

Local Service account has the same level of access to resources and

Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

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. Service account–Microsoft account–Microsoft recommends recommends that you do not o  Network Service 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 whowill havebebeen authenticated by the Windows operating system ablepreviously to connect to SQL Server 2005. This is the recommended mode.

Authentication Mode •

Mixed Mode–Users connecting through a Microsoft Windows account will  be authenticated authenticated by the Windows Windows operating operating system; other other users will use SQL Server Authentication Authentication which will require them to enter a username and  password to login 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, case-sensitivity, accent marks, kana character types, etc. It also determines the rules for comparing Unicode and non-Unicode data. •

Collation Setting







The collation setting you choose during installation becomes the default collation type for all databases and tables. 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 aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

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 databases on computer computer connected directly directly to the Intern Internet. et. 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 aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

Microsoft SQL Server - Concepts   2 005

Databases

33

Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

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: Compone Com ponent nt Descri Descripti ption on Database File

A database  is a logical collection of related data, organized into one or more tab tables. les. database is Databases also include additional objects that are used u sed by SQL server for defining the database structure, improving performance, and performing locking and transactions. A file  file is  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. •

34

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

Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

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. A secondary data file is 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 ac cess contention by storing all data and objects in secondary files. 





o







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

 Log files contain files contain the transaction log for recovering recov ering the database's transactions. o You must have at least one log file for each database. o o

You can create multiple log files per p er database to facilitate faster recovery. 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  filegroup is  is collection of data files that are managed manage d as a single unit. Y You ou can increase performance by assigning different database objects (tables, indexes, etc.) across several filegroups on different d ifferent disk subsystems. Multiple filegroups allow for selective back up and restore. Y You ou can also a lso assign data files within the same filegroup to different disks. The types of filegroups are: •

Filegroup





A primary filegroup filegroup contains  contains the primary data file and secondary data files not stored in another filegroup. All system tables are allocated to the primary filegroup. A secondary filegroup contains filegroup contains secondary data files and database objects. A database can contain up to 32,767 user-defined filegroups. The default filegroup contains filegroup contains objects that were created without an a n assigned filegroup. The primary filegroup is the default filegroup unless another filegroup is specified. You You can specify the default filegroup by b y 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 aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

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 aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

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',   = 10,   SIZE MAXSIZE = 100,   FILEGROWTH = 10 ) LOG ON ( NAME = 'LogFile1',   FILENAME = 'e:\logfiles\MyLogFile.ldf',   SIZE = 512KB,   MAXSIZE = 2MB,   FILEGROWTH = 512KB )

The following table tab le describes each option in the CREATE CREATE DAT DATABASE statement for creating data and log files. Other options, such as specifying collation type, can be entered in the CREATE CREA TE DA D ATABASE statement. stateme nt. Transact-SQL Keyword

Description The ON keyword is followed by b y blocks (surrounded by parenthesis) that define the datafile(s) for the database. •

ON •

The ON portion is optional. If not specified, the database will be created with a single data file in the default location. Use the PRIMARY keyword after the ON keyword ke yword to identify the  primary data file. If PRIMARY PRIMARY is not used, the first file listed will be the primary.

 NAME

Identifies the logical name for the file.

FILE FILENA NAME ME

Ident dentif ifiies the pat path and and filen ilenam amee for for th thee dat datab abas asee or or llog og fi file le..

37

Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

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: • •

SIZE

 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. grow. •

FILEGROWTH







LOG ON

In addition to unit suffixes (KB, MB, etc.), you can also specify a  percentage (%). If a suffix is not included, the default is MB. MB. 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 specified, a single log file will be created in the default location.

Create Database Facts 38

Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

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 tab le describes each option in the CREATE CREATE DAT DATABASE statement for creating data and log files. Other options, such as specifying collation type, can be entered in the CREATE CREA TE DA D ATABASE statement. stateme nt. Transact-SQL Keyword

Description The ON keyword is followed by b y blocks (surrounded by parenthesis) that define the datafile(s) for the database. •

ON •

The ON portion is optional. If not specified, the database will be created with a single data file in the default location. Use the PRIMARY keyword after the ON keyword ke yword to identify the  primary data file. If PRIMARY PRIMARY is not used, the first file listed will be the primary.

 NAME

Identifies the logical name for the file.

FILE FILENA NAME ME

Ident dentif ifiies the pat path and and filen ilenam amee for for th thee dat datab abas asee or or llog og fi file le..

SIZE

Configures the size of the data or log file.

39

Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

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. grow. •

FILEGROWTH

• •

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



LOG ON

40

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 specified, a single log file will be created in the default location.

Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

Microsoft SQL Server - Concepts   2 005

Database Objects

Table Facts

41

Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

Microsoft SQL Server - Concepts   2 005

After the database has been designed, you can then add the tables that will hold the data. Tables Tables can be created c reated using SQL Server Management Manage ment Studio, Transact-SQL scripti scripting, ng, or Table Objects (SQL-SMO). When you create a table, tab le, you define the columns on o n 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

 Name

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 for each owner in the database, different owners can have tables of the same name. Column names must follow SQL Server 2005 naming rules.

Data type

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 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.

Data length

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 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. co lumn. NULL is not the same thing as a zero (0) or blank data. Instead, NULL represents a value that is as yet undefined. • •

 NULL/NOT  NULL



You can allow a llow or disallow NULL values for columns. co lumns. When NOT NULL is defined, users must enter a value when a new row is added. If NULL is allowed, SQL Server automatically supplies NULL when 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 DEFAULT property defines a value that is automatically added to the column when a new row is defined.

DEFAULT IDENTITY

42

Use the IDENTITY prop opeerty to de define an an identifier  column.  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:

Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

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. •

ROWGUIDCOL

• •



You can only on ly have one ROWGUIDCOL column. The data type must be set to uniqueidentifier. The setting does not automatically generate values. You You must use a DEFAUL DEF AULT T with a NEWID function to generate automatic values if desired. ROWGUIDCOL does guarantee uniqueness. You You must use a UNIQUE constraint to not 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 aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

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 aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

Microsoft SQL Server - Concepts   2 005

Note: Rules are  Rules are objects used u sed 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, DEFAUL DEFAULT T, UNIQUE, and a nd CHECK.

The table below describes the classes of constraints: Constraint Class

Description

A NOT NULL constraint restricts 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 b y 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 co nstraints 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 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 PRIMARY KEY constraints are: •

PRIMARY KEY







45

PRIMARY KEY constraints do not support NULL values. PRIMARY The PRIMARY KEY setting setting defines the identity column. Because the values are guaranteed to be unique, the PRIMARY KEY KEY can be used for row identifiers. Each table can have ha ve only a single PRIMARY KEY (although the key may use multiple columns as long as the combination co mbination of column values is unique for each row). The PRIMARY KEY is used when defining inter-table relationships.

Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

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. 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.



UNIQUE

• • •

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 Relationship to  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 You can use a FOREIGN KEY to specify that a column allows only the values contained in the referenced table column. A self-ref  self-referencing  erencing  table  table is a table with a foreign key that references columns in other tables in the same database da tabase 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 aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

Microsoft SQL Server - Concepts   2 005

DEFAULT

o

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

o

Set Default the value totable the default value for the column all foreign key  sets columns for the have defined defaults (SQL if Server 2005 only).

The DEFAULT DEFAULT keyword defines a value that is used if the user doesn't do esn't specify a value for the column. The default value va lue 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 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 con straints later with ALTER ALTER TABLE TABLE statements and name the constraints. It is easier to modify or drop constraints if they were added using ALTER ALTER TABLE. TABLE. This example uses the ADD CONSTRAINT keyword to create a PRIMARY 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 co nstraint to more than one column. A column cannot be deleted if it is referenced by b y a FOREIGN KEY constraint. Drop the FOREIGN KEY constraint in order to delete columns (including columns with a PRIMARY KEY by athe FOREIGN If you change the constraint) data type inreferenced one column, data typeKEY. in the other column will be changed as well.

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





 Entity integrity ensures integrity ensures that all a ll 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 integrity ensures that values within a column are a re valid (for example, data type, format, and value range). Use CHECK constraints to enforce the format or the range of  possible values. You You can also use FOREIGN KEY and NOT NULL constraints to restrict the range of possible values.  Referential integrity 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 aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

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 a s dropping a foreign key table while the FOREIGN KEY constraint exists. User-defined integrity ensures 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. automatically. You You can create constraints using: • •

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

Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

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,   camera char(25), constraint   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 a UNIQUE constraint

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,   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 c onstraint 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 aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

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 ar aree 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 constraint

  camera char(25),   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 aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

Microsoft SQL Server - Concepts   2 005

DML Trigger Facts

A DML trigger  is  is a type of stored procedure procedu re 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 ap plication 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 aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

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 t ypes of DML triggers you can execute. Trigg rigger er Typ Typee

Desc Descri ript ptio ion n An AFTER trigger executes after the statement that triggered it completes. •



AFTER trigger 





Multiple AFTER triggers can be specified for each INSERT, INSERT, UPDATE, UPDATE, or DELETE triggering action. AFTER triggers can be specified for tables but not for views. When creating a trigger, the trigger is created as an AFTER trigger unless you specify INSTEAD OF. An AFTER trigger executes after the successful execution of a TransactSQL 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. •

INSTEAD OF trigger 





Only one INSTEAD OF trigger can be specified for each INSERT INSERT, UPDATE, UPDA TE, or DELETE triggering action. When the action takes place, the trigger executes instead of the normal 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 so me 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 constraint can accept or reject updates up dates 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 aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

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 ALTER TRIGGER to modify a trigger. Use ENABLE and DISABLE TRIGGER to control whether a trigger fires without dropping the trigger. trigger. For DML triggers, you can also use AL ALTER TER TABLE TABLE to enable or disable a trigger. trigger. Use DROP TRIGGER to delete a trigger. 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   @escwamt = b.EscrowAmt, AS @workorder = w.WorkOrders   SELECT FROM BldgComplete.Tbl_Complete b, BldgProgress.Tbl_Workord BldgProgress.Tbl_Workorders ers 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 aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

Microsoft SQL Server - Concepts   2 005

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 INSERT, UPDATE, UPDATE, and DELETE operation is allowed. Triggers not specified as first or last are randomly executed. Using ALTER ALTER TRIGGER eliminates first and last trigger designations. The UPDATE( UPDATE( ) function allows you to define a trigger based on an u update pdate or insertion into a column. The COLUMNS_UPDA COLUMNS_UPDATED TED 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. execu ted. A DELETE trigger will not catch a TRUNCATE TABLE statement. o



• • •





• •

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

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

In SQL Server 2005, you cannot  use  use the following Transact-SQL statements inside the body bod y 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 AL TER TABLE TABLE when used to do the following: o Add, modify, or drop columns o Switch partitions PRIMARY KEY or UNIQUE constraints o Add or drop PRIMARY

54

Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

Microsoft SQL Server - Concepts   2 005

View Facts

A view view is  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 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 aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

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 b y 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. databa se. 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: BY, COMPUTE, or COMPUTE BY clauses. o Views cannot use ORDER BY, 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. 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 chang es affect columns referenced in the view. You 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 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: view • •



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. 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 aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

Microsoft SQL Server - Concepts   2 005

• • • •

Use indexes for views that include many man y 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, BY, HA HAVING, VING, 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 procedure is  is precompiled code that can be reused. It is precompiled, stored 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 aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

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. 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. databa se. 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 p rocedures available in Microsoft SQL Server 2005.  Type

Description Descrip tion System stored procedures are procedures are stored procedures supplied by SQL Server. 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. databa se. In SQL Server Se rver 2005, GRANT, GRANT, DENY, 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 Stored Procedures

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

58

Using traditional Transact-SQL statements. statements. This method is preferred when the stored procedure accesses data using little or no procedural logic.

Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

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 stored procedure CPU-intensive calculations, andthe complex logic. CLRperforms is also the choice when functions, accessing objects such as the network or file system, or o r to run processor-intensive code on the client computers.

Extended Stored Procedures

Temporary Stored Procedures

 Extended system stored procedures procedures (  (xp_  prefix)  prefix) are stored procedures that interface between SQL Server and external programs for maintenance activities. a ctivities. Extended stored procedures can be written using a programming language like C. Note: Extended stored procedures will be dropped in a future release. Use userdefined, 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. server. These may occasionally be useful whenthat working applications that build dynamic Transact-SQL statements need towith be executed multiple times, or for working with earlier versions of SQL Server. Server. CLR stored procedures cannot be created as temporary stored procedures.

The following guidelines apply to both CLR managed code aand nd Transact-SQL stored procedures. • • • •





You can create a stored procedure only in the current c urrent database. Validate all user input before you use it. Use the EXEC keyword to call a stored procedure. CREATE CREA TE PROCEDURE statements cannot canno t 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 CREATE RULE CREATE DEFAULT CREATE SCHEMA CREATE or ALTER FUNCTION CREATE CREA TE or o r ALTER ALTER TRIGGER  TR IGGER  CREATE or ALTER PROCEDURE CREATE CREA TE or ALTER VIEW SET SET PARSEONLY SHOWPLAN_ALL 59

Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

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 aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

Microsoft SQL Server - Concepts   2 005   WHERE SaleDate = @ReportDate END GO

Note: Y  You ou can use the WITH ENCRYPTION 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. code. You can create managed code using a .NET Framework language such as Visual Basic .NET or Vis Visual ual 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 do es 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 Code

Decision Criteria Use managed code when:

Managed Code

• •



You want to access the functionality of the .NET Framework. The code performs complex logic that is CPU-intensive. You want the code to run on the client side to leverage the processing power of the client computer rather than tax the server.

TransactUse Transact-SQL when: SQL 61

Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

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 Safe code restrictions and cannot call unmanaged code.  External  code  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 Unsafe  code does not have h ave 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 aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

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, INSERT, UPDATE, UPDATE, and DELETE. You 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 63

Example Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

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      

  GO

INSERT VALUES INSERT VALUES INSERT VALUES

INTO CrewList (CrewName , CrewForeman , CrewSize) 'CrewD' , 'Samuel Smith', 22 INTO CrewList (CrewName , CrewForeman , CrewSize) 'CrewE' , 'Miguel Gomez', 43 INTO CrewList (CrewName , CrewForeman , CrewSize) 'CrewF' , 'Jacob Ouahib', 37

In the following example, the data inserted in the previous example is updated. You You will change ch ange the CrewSize for CrewD to be 31. Update data in a table

USE MyConstruction 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 table

USE MyConstruction GO   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 operator to return only table. USE MyConstruction unique values. GO      

SELECT DISTINCT BldgTyp FROM Building.CrewReport INTO CrewBldgTyp AS BldgTypsInProg

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

Definition

Ad hoc names

 Ad hoc names 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: •

64

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

Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

 

Microsoft SQL Server - Concepts   2 005





access the OLE DB database source. This type of access should be used u sed infrequently, infrequently, if at all. These types of queries use OPENROWSET and OPENDATASOURCE functions.

Aggregate function

An aggregate aggregate  function performs  function performs a calculation on several rows or cells of data and returns a single result. Examples of aaggregate ggregate functions are A AVG VG (returns the average of the group), COUNT (returns the number in the group), MAX (returns the highest value in the group). g roup).

Common table expression

A common table expression (CTE) expression (CTE) is a temporary result set.

Deterministic function

A deterministic function returns function returns the same value each time it is executed.

Metadata

 Metadata is data about data. Metadata can be used to describe objects within  Metadata is SQL Server such as table information (number of columns, column names, datatypes of the columns, etc.) or it can c an be used to describe the content of the objects such as the information within the table.

 Nondeterministic function

A nondeterministic function may function may return a different value each time it is executed.

Recursive common table expression

A recursive common table expressi exp ression on is  is a CTE that is executed multiple times. The result of each execution of the CTE is a subset of data used in another CTE until the final result is obtained.

Recursive query

A recursive query is query is a query that references a recursive CTE.

Scalar

Scalar refers to a single value as opposed to an array which consists of multiple values.

Subquery

A subquery  subquery is  is a query expressed in a SELECT statement that returns a single value and is nested inside a SELECT, INSERT, UPDATE, or DELETE statement or another subquery. subquery.

65

Taught aught by by: Aiman Aiman Moba Mobarak rak Elkhali Elkhalifa fa

Sponsor Documents

Or use your account on DocShare.tips

Hide

Forgot your password?

Or register your new account on DocShare.tips

Hide

Lost your password? Please enter your email address. You will receive a link to create a new password.

Back to log-in

Close