When considering the scalability and performance of an MS-SQL Server running in a Windows NT environment, it is important to understand the differences among the impacts of multi-tasking, multi-threading, and multi-processing on MS-SQL Server performance.
Multi-tasking refers to the operating system's ability to run multiple programs at the same time. Although only one application can have control of the central processing unit (CPU) at a time, the operating system creates the illusion that several programs are executing simultaneously, by letting each of them use the CPU for a period of time. At the end of the program's CPU time slice, the system notes where the program left off so that it can restart the program at the same point the next time it gives the application control of the CPU. Then the system switches to another application and lets that program control use the CPU for a time, and so on. It takes the operating system only a few hundred milliseconds to switch from one application to another. However, each of the programs will appear to run more slowly when the time between CPU time slices allotted to the program increases as the server shares the CPU among an increasing number of programs.
Each program running on an NT Server is called a process. Figure 501.1 shows statistics on several of the 35 processes (including 2 instances of MS-SQL Server) running on a Windows NT Server.
Figure 501.1: The Windows NT Task Manager showing statistics on processes running on an NT Server
The operating system assigns each process a priority from 1 to 31 (which increases the longer the process waits for its CPU time slice) and grants use of the CPU to the process with the highest priority. Each instance of MS-SQL Server, for example, defaults to an initial (base) priority of 7. (Processes that run at a base priority of 7 are said to run at normal priority because the majority of applications start themselves at a base priority of 7.) In Tip 502, "Using the MS-SQL Server PRIORITY BOOST Configuration Option to Increase Server Thread Priority from 7 to 13," you will learn how to use the PRIORITY BOOST configuration option to increase the MS-SQL Server's base priority to 13, which will cause the MS-SQL Server process to run at high priority.
Multi-threading relates to multi-processing in that each program running on an NT Server may be written in sections so that each section or thread in an application can operate on the CPU independently. Thus, when the NT operating system gives a CPU time slice to a multithreaded process, the system actually starts (or restarts) the highest-priority thread (or section of code within the process) at the point at which the thread halted the last time it had to give up the CPU to another process or thread. One of the instances of MS-SQL Server (shown in Figure 501), for example, has 30 threads, while the other has 31. Therefore, when Windows NT gives control of the CPU to one of the two instances of MS-SQL Server, it is actually giving the CPU time slice to the MS-SQL Server thread with the highest priority that is waiting to execute.
Each instance of the MS-SQL Server always runs several threads: one for each network protocol used to communicate with workstations and other servers, one to handle login requests, another to communicate with the server's service control manager, and several others to execute the individual SQL and Transact-SQL statements and statement batches users send to the MS-SQL Server for execution. Multi-tasking with multiple threads is most advantageous when the NT Server has multiple processors because a single CPU (or processor) can execute only one thread at a time.
Multi-processing refers to the Windows NT operating system's ability to spread processes and threads across multiple CPUs located in a single server. Thus, a Windows NT Server with five CPUs can execute five threads or processes simultaneously. A multi-CPU NT Server is particularly advantageous when used to host an MS-SQL Server because the MS-SQL Server can use one of the CPUs to execute database I/O requests while at the same time using another CPU to execute a login thread to allow another user to open a connection to the SQL server and executing a query for another user on a third CPU, and so on.
As you learned in Tip 501, "Understanding MS-SQL Server Multi-tasking and Multi-threading on a Multi-processor Windows NT System," Windows NT assigns a priority from 1 to 31 to each process and thread waiting to execute on one of the server's CPUs. If more than one process or thread is waiting to execute, the operating system will give the available CPU time slice to the thread with the highest priority. Each MS-SQL Server thread defaults to the normal priority of 7. However, you can use the PRIORITY BOOST option to increase the thread base priority to 13. Since doing so will give MS-SQL Server threads a higher priority than other processes and threads waiting to execute on the server, MS-SQL Server will tend to execute queries and other DBMS commands more quickly. In fact, at a (high) base priority of 13, the NT Server will tend to execute its threads whenever they are ready to run (since they will tend to have a higher priority than other threads and processes). Moreover, the high-priority MS-SQL Server threads will not be preempted by threads from other processes—again because they will tend to have a higher priority than other processes and threads waiting to use the CPU. (A thread is preempted when it is forced to relinquish control of the CPU to another waiting thread with a higher priority.)
To boost the base priority of MS-SQL Server threads from 7 (normal) to 13 (high), perform the following steps:
After you complete Step 7, you must stop and restart the MS-SQL Server in order for the priority boost to take effect.
Note |
Running the MS-SQL Server with PRIORITY BOOST can greatly improve the SQL server's performance. However, if MS-SQL Server is executing a memory-intensive operation (such as a sort) that takes a long time to complete, other applications are unlikely to have a high enough priority to preempt the MS-SQL Server thread. As a result, the performance of other applications or other instances of the MS-SQL Server running at normal priority (priority 7) will be adversely affected because these threads and processes are forced to wait for the priority-boosted thread to finish executing before they get a CPU time slice. |
Windows NT Server includes a Performance Monitor that you can use to check the performance of one or more computers (both workstations and servers) on a network. Items that the Performance Monitor can monitor (referred to as objects by the application) include processors (CPUs), executing programs (processes), threads, hard drives, network resources, Internet services, and memory. To start the Windows NT Performance Monitor and generate a graphical display of MS-SQL Server statistics, perform the following steps:
Figure 503.1: The Windows NT Performance Monitor Chart View
Figure 503.2: The Windows NT Performance Monitor Add to Chart dialog box
Note |
The name of the MS-SQL Server may be something other than SQLServer on your system. For example, MS-SQL Server 2000 will be labeled as MSSQL$. Therefore, if you installed MS-SQL Server 2000 into the MSSQL2000 folder, you would select MSSQL$MSSQL2000:Buffer Manager in Step 5. |
If you decide that you want to add additional items to the chart, you can repeat the preceding procedure from Step 3. Conversely, to remove an Object/Counter, click your mouse pointer on the item you no longer want displayed in the list of Object/Counter items at the bottom of the Performance Monitor application window, and then select the Edit menu's Delete from Chart option, or click your mouse pointer on the Delete Selected Counter button (labeled with an X) on the Standard toolbar.
To clear all Object/Counter items, select the File menu's New Chart option.
In Tip 503, "Understanding the NT Server Performance Monitor Chart View," you learned how to use Performance Monitor to display Object/Counter information in graphical form. Charts work well when you want to view the change in an Object/Counter item's value over time and when you want to compare the values of two or more Object/Counter items. However, there are times when you want to see the Performance Monitor statistics in tabular (vs. graphical) form. The Performance Monitor's Report View will display the numeric values for the Object/Counter items you select. In Chart View, you must interpret the values of the items by the position of the line(s) on the graphic relative to the data point's height on the chart's vertical axis.
To display Performance Monitor Object/Counter items in Report View, perform the following steps:
Note |
Performance Monitor will display items in the Instance list box whenever you select a counter that pertains to more than one object (or "instance"). Conversely, if you select an Object/Counter item such as the Cache Size (pages) counter of the SQLServer:Buffer Manager object, the Performance Monitor does give you a choice of Instance selections, since the Object/Counter can pertain to only a single item—the MS-SQL Server. |
Figure 504.1: The Windows NT Performance Monitor Report View
If you decide you want to add additional items to the tabular report, you can repeat the preceding procedure from Step 4. Conversely, to remove an Object/Counter/Instance item, click your mouse pointer on the item (in the body of the report) that you want to remove, and then select the Edit menu's Delete from Report option, or click your mouse pointer on the Delete Selected Counter button (labeled with an X) on the Standard toolbar.
To clear all Object/Counter/Instance items, select the File menu's New Report Settings option.
Tip 503, "Understanding the NT Server Performance Monitor Chart View," and Tip 504, "Understanding the NT Server Performance Monitor Report View," showed you how to use Performance Monitor to display MS-SQL Server data on an ongoing basis. However, there are certain conditions you hope will never or rarely occur. Rather than watch a graphical or tabular display for a spike or dip in a counter value that corresponds to one or more of these events, you can tell Performance Monitor to display an alert only when a specific event occurs.
To have Performance Monitor display an alert whenever an Object/Counter item value or Object/Counter/Instance item value falls below or exceeds a specific threshold, perform the following steps:
Figure 505.1: The Windows NT Performance Monitor Add to Alert dialog box
The Performance Monitor Alert View display will remain empty until one of the Object/Counter/Instance values satisfies the alert criteria. Thereafter, Performance Monitor will add each alert raised to the display similar to that shown in Figure 505.2.
Figure 505.2: The Windows NT Performance Monitor Alert View
If you decide that you want to add additional alerts, repeat the preceding procedure from Step 4. Conversely, to remove an alert, click your mouse pointer on the alert that you no longer want in the list of alerts at the bottom of the Performance Monitor application window, and then select the Edit menu's Delete Alert option, or click your mouse pointer on the Delete Selected Counter button (labeled with an X) on the Standard toolbar.
To clear all alerts, select the File menu's New Alert Settings option.
The SQL-89 standard made a strong distinction between the SQL data manipulation language (DML) statements and data definition language (DDL) statements. While the standard required that the DBMS be able to execute DML statements during its normal operation, it made no such demand with regard to the ability to execute DML statements. In fact, the SQL-89 standard permits an SQL database to have a static structure like that used by the older hierarchical and network database models (which you learned about in Tip 3, "Understanding the Hierarchical Database Model," and Tip 4, "Understanding the Network Database Model").
If an SQL-89-compliant DBMS were implemented using a static database structure, the database administrator (DBA) would use DDL statements to create a database schema-a map of the database that shows its structure including tables, views, users, and access privileges. The DBA would then submit the database schema to a "builder" utility that creates the database according to the specifications in the schema. Once created (by the "builder" utility), the database objects and security scheme could not be changed. DML statements could add, change, remove, and retrieve data. However, to add a new table or user to the database-which requires the execution of DDL statements-the DBA would have to stop all access to the database, unload all of its data, use the DDL to create a revised schema, submit the new schema to the "builder" utility, and then reload the database data.
Although allowed by the SQL-89 standard, no database product actually used a static database structure. In fact, the later SQL-92 standard includes DROP (TABLE, VIEW, USER, and so on) and ALTER (TABLE, VIEW, USER, and so on) statements that effectively require an SQL-92-compliant database to support dynamic database object definition and modification. However, the concept of using a database schema to create a set of tables, views, and permissions (in effect, a database) is still supported by many DBMS products-despite their ability to create, drop, and alter individual database objects on the fly.
The CREATE SCHEMA statement lets you create a conceptual database object that contains the definitions of tables and views and to grant access privileges on those tables and views to DBMS users and roles. The syntax of the CREATE SCHEMA statement is:
CREATE SCHEMA AUTHORIZATION [|| ]
Note |
Although the AUTHORIZATION is required, it is not actually used when the DBMS assigns ownership of the tables and views it creates. All tables and views created by executing the CREATE SCHEMA statement are owned by the user ID executing the statement. |
|||
To create a set of tables and views, you can execute a CREATE SCHEMA statement such as:
CREATE SCHEMA AUTHORIZATION frank CREATE VIEW vw_offices AS SELECT offices.office_ID, manager_ID, f_name + l_name manager_name FROM offices, employees WHERE manager_ID = emp_ID CREATE TABLE employees (emp_ID INTEGER, f_name VARCHAR(15), l_name VARCHAR(15), total_sales MONEY, office_ID SMALLINT) CREATE TABLE offices (office_ID SMALLINT, street_address VARCHAR(30), manager_ID INTEGER) GRANT SELECT ON vw_offices TO PUBLIC GRANT ALL PRIVILEGES ON offices TO sally GRANT ALL PRIVILEGES ON employees TO sally
In short, the CREATE SCHEMA does not add any real functionality to the DDL. However, the CREATE SCHEMA statement does give you a single SQL statement that you can use to create one or more tables and views and to grant access permissions to those tables and views.
With the exception of views that are dependant on other views, the objects created in the CREATE SCHEMA statement need not appear in any specific order. As such, you can grant permissions or create a view based on a table created later in the CREATE SCHEMA statement. Moreover, view definitions and foreign keys created in one part of the statement can refer to columns in tables created later in the CREATE SCHEMA statement. However, if a view definition references columns in another view (vs. columns in a table), the view whose columns are being referenced must be created before the view that references its columns.
As is the case with any single SQL statement, the DBMS will roll back (undo) the CREATE SCHEMA statement's work if any part of the statement fails to execute successfully. Therefore, if any one of the CREATE SCHEMA statement's CREATE or GRANT statements fails, the DBMS will not create any of schema's tables or views, nor will the DBMS grant any of the privileges specified in the schema.
Tip 503, "Understanding the NT Server Performance Monitor Chart View," and Tip 504, "Understanding the NT Server Performance Monitor Report View," showed you how to use Performance Monitor to display real-time object/counter values in chart and tabular form, respectively. If you want to store the values of the counters for one or more Performance Monitor objects so that you can display the counter values and analyze them later, use the Performance Monitor Log View. The Performance Monitor's Log View will write counter values to a disk file at set intervals. As you will learn in Tip 508, "Using the NT Performance Monitor to View a Performance Log File," you can tell the Performance Monitor to retrieve object/counter values from its log files and display them in chart or graphical form.
To have Performance Monitor log the values of the counters for one or more objects for later review, perform the following steps:
Figure 507.1: The Windows NT Performance Monitor Add to Log dialog box
Figure 507.2: The Windows NT Performance Monitor Log Options dialog box
When you complete Step 12, Performance Monitor will close the Log Options dialog box and begin writing the object/counter values (which you selected in Steps 6-8) into the log file (which you specified in Step 10), at the interval you entered in Step 11. Click your mouse pointer on the dash (-) (third button from the right in the upper-right corner of the Performance Monitor application window), and shrink the application to an icon on the task bar at the bottom of your computer screen.
After Performance Monitor (running as a background task on your computer) has collected data for a desired time period, click you mouse pointer on its icon on the task bar at the bottom of your screen to display its application window. Next, select the Options menu's Log option to again display the Log Options dialog box. To stop the application from logging counter values, click your mouse pointer on the Stop Log button (in the lower-right corner of the dialog box).
You will learn how to use Performance Monitor to display the contents of its log files in Tip 508.
After you create Performance Monitor log files (by performing the steps in the procedure in Tip 507, "Setting Up the NT Server Performance Monitor Log to Help in Optimizing the MS-SQL Server"), you can use Performance Monitor to display the contents of the log files in chart (graphical) or tabular form. The process is very simple. Instead of having Performance Monitor retrieve the counter values it is to display directly from the NT Server hosting the MS-SQL Server, you tell the program to use the counter values in the log file (as if they were coming directly from the server).
For example, to use Performance Monitor to display previously logged counter values in chart form, perform the following steps:
Figure 508.1: The Windows NT Performance Monitor Data From dialog box
After you complete Step 13, Performance Monitor will display the entire contents of the log file on a single chart. To view, "zoom in" on the values logged during a specific period of time, select the Edit menu's Time Window, and specify the time period of interest on the Input Log File Timeframe dialog box.
In Tip 505, "Understanding the NT Server Performance Monitor Alert View," you learned how to use Performance Monitor to alert you to potential problems with the MS-SQL Server's operation by displaying a message in Alert View whenever object/counter values either exceeded or fell below certain limits. The Performance Monitor, however, is not the only tool you can use to monitor the health of your MS-SQL Server. Windows NT includes an integrated logging tool that maintains a log of application, security, and system operations called events. By reviewing the application log events generated by your MS-SQL Server, you can learn how often the SQL Server/Agent was stopped and started, see how often it encounters file (table, log, and index) errors, and review warnings and error messages generated by various other database operations such as transaction rollbacks and roll-forwards executed when the SQL server is restarted after an abnormal shutdown.
Windows NT enables the event-logging service automatically when you start the server. To avoid losing event notifications due to a full event log, you should use the Event Viewer to configure the event logs after you install the MS-SQL Server on the server. To use the Event Viewer to set the maximum log file size in kilobytes, the length of time events remain in the log, and whether or not the event logging service will overwrite events if the log file is full, perform the following steps:
Figure 509.1: The Windows NT Event Viewer Event Log settings
While you are still in the Event View, you should go ahead and set the configuration settings for the system and security logs as well. To do so, start at Step 3 of the preceding procedure and select System in Step 4. Then, after completing Steps 5 and 6, repeat the procedure again, starting at Step 3, and select Security at Step 4 the third time through.
The Event Viewer lets you view application (system and security) log information recorded by the Windows NT server's event-logging service. As shown in Figure 510.1, each line in an event log shows the date and time the event occurred, the source of the event, and the event's category, ID number, and username (if applicable) of the user that launched the transaction.
Figure 510.1: A Windows NT Event Viewer application event log
To display more detailed information on an event, double-click your mouse pointer on the event (or click your mouse pointer on the event, and then select the View menu's Detail option). The Event Viewer will display an Event Detail message box similar to that shown in Figure 510.2.
Figure 510.2: The Windows NT Event Viewer Event Detail message box
After you invoke the Event Detail dialog box to display the detail for one event, you can click your mouse pointer on its Next button to display the next event (toward the bottom of the event list) or on the Previous button to display event detail for the next event toward the top of the list. When you are finished viewing event detail, click your mouse pointer on the Close button to close the Event Detail dialog box and return to the Event View application window.
If you noticed a trend in the application log's event messages, made a correction to the application's settings or hardware, and now want to monitor the server for the reoccurrence of the trend, you will want start with an empty event log. To clear all events from a log, select the Log menu's Clear All Events option. The Event Monitor will display a Clear Event Log confirmation textbox. Click your mouse pointer on the Yes button if you want to write the event log to a disk file before clearing it, click on the No button to clear the event log before saving its contents to another file on disk, or click on the Cancel button to leave the event log unchanged.
There are several ways you can start the MS-SQL Server on a Windows NT Server. When you install the MS-SQL Server (as you will learn to do in Tip 527, "Installing the MS-SQL Server"), you can select an option on one of the setup screens to have Windows NT start the MS-SQL Server as a service automatically whenever you boot the operating system. Conversely, you can choose to start the MS-SQL Server manually with the MS-SQL Server Service Manager or by entering a command at the command prompt in the MS-SQL Server's BINN directory.
To start the MS-SQL Server using the MS-SQL Server Service Manager, perform the following steps:
Figure 511.1: The MS-SQL Server Service Manager dialog box
Note |
If you want the Windows NT Server to start the MS-SQL Server (service) automatically each time you boot the operating system, click your mouse pointer on the check box to the left of Auto-start Service When OS Starts until a check mark appears. |
In addition to starting the MS-SQL Server, you can use the MS-SQL Server Service Manager to start four other SQL related services:
To start any of these MS-SQL Server support services, select the service you want to start instead of SQL Server in Step 4 of the preceding procedure.
As mentioned in Tip 511, "Using the MS-SQL Server Service Manager to Start the MS-SQL Server," you can start the MS-SQL Server from the command prompt. To start the MS-SQL Server from a command prompt, perform the following steps:
sqlservr - :\master.mdf
For example, if you are starting MS-SQL Server Version 7 installed to the default directories, with database files in the C:MSSQL7DATA directory, enter sqlserver -master c:mssql7datamaster.mdf at the command prompt and then press the Enter key.
If you used something other than MASTER for the name of the master database when you installed the MS-SQL Server, substitute that name for and for the "master" in master.mdf in Step 4.
In Tip 527, "Installing the MS-SQL Server," you will learn how to install the MS-SQL Server on a Windows NT server. As mentioned in Tip 511, "Using the MS-SQL Server Service Manager to Start the MS-SQL Server," the installation process gives you the option of having the operating system (OS) start the MS-SQL Server automatically during the OS boot process. If you select the installation option to force a manual restart of the MS-SQL Server each time you restart the Windows NT server, you can change the "manual" MS-SQL Server startup election later.
As you learned from Tip 511, you can make the election to automatically start the server in the future by clicking a check mark into the Auto-start Services When OS Starts check box on the MS-SQL Server Service Manager dialog box. Alternatively, to tell Windows NT to start the MS-SQL Server automatically as part of the boot process (vs. manually after the Windows NT server is running), through the Windows NT server's Control Panel, perform the following steps:
Figure 513.1: The Windows NT Control Panel Services window's Service (startup) dialog box
In addition to enabling (or disabling) automatic startup of the MS-SQL Server, you can manually start (or stop) the MS-SQL Server on the Control Panel's Services dialog box. If the MS-SQL Server is not running at Step 4 (or after Step 7), you will see nothing in the MS-SQL Server's Status column. To start the MS-SQL Server, click your mouse pointer on the Start button in Step 5 (vs. the Startup button). Windows NT will start the MS-SQL Server and display Started in the Status column of the line for the MS-SQL Server that you selected in Step 4. Conversely, if you want to shut down a running MS-SQL Server, at Step 4 (or after Step 7), click your mouse pointer on the Stop button. Windows NT will stop the MS-SQL Server and remove Started from the Status column of the affected MS-SQL Server's line in the Service list box of the Services dialog box.
When you run the MS-SQL Server installation program, the application will install both the MS-SQL Server and the tools you need to manage it and to modify and query its data. As such, if the computer on which you installed the MS-SQL Server is also the workstation you are using to work with the SQL server, you need not install any additional client software. However, as is most likely the case, when you are using one computer to manage or work with data on the MS-SQL Server installed on another computer, you need to install some (if not all) of the MS-SQL Server client software shown in Table 514.1 on your workstation.
Component |
Space |
Subcomponent |
Space |
---|---|---|---|
Management Tools |
28,672K |
Enterprise Manager |
25,024K |
Profiler |
640K |
||
Query Analyzer |
1,696K |
||
DTC Client Support |
OK |
||
Conflict Viewer |
1,024K |
||
Client Connectivity |
288K |
||
Books Online |
32,512K |
||
Development Tools |
16,800K |
Headers and Libraries |
6,400K |
MDAC SDKs |
9,600K |
||
Backup/Restore API |
512K |
||
Debugger Interface |
288K |
||
Code Samples |
6,944 |
Active-X Data Objects (ADO) |
192K |
DB-Library (DBLIB) |
160K |
||
Desktop |
3,424K |
||
Data Transformation Services (DTS) |
576K |
||
Embedded SQL for C (ESQLC) |
160K |
||
Miscellaneous |
224K |
||
Microsoft Distributed Transaction Coordinator (MSDTC) |
160K |
||
Open Database Connectivity (ODBC) |
160K |
||
Open Data Services (ODS) |
160K |
||
Object Linking and Embedding (OLE) Automation |
160K |
||
Replication |
160K |
||
SQL Distributed Management Objects (SQLDMO) |
192K |
||
SQL Namespace (SQLNS) |
160K |
||
Utils |
288K |
||
XML |
288K |
If you want to install all of the client software, books online (documentation), development tools, and code samples, you will need approximately 180MB of free space on your computer. At a minimum, you will need to install the management tools (which let you manage the MS-SQL Server and work with its data) and the client connectivity tools (which allow the clients to communicate with the server through DBLIB, ODBC, and OLEDB drivers). If you plan to write applications, you will also need the headers and libraries, MDAC SDK's subcomponents of the development tools component, and the subcomponents of the code samples component relevant to your planned development environment.
In Tip 515, "Installing MS-SQL Server Client Software," you will learn how to install the MS-SQL Server client software. For now, the important thing to understand is that the MS-SQL Server client software lets you use any workstation on the network to manage the MS-SQL Server and work with its data—as long as the DBA and the network administrator have given your user ID the required access rights. Although there are still some 16-bit clients available, the latest clients (released with MS-SQL Server 7.0 and above) require that you install and run them on a 32-bit operating system (such as Windows 95, 98, ME, NT, 2000, UNIX, Apple Macintosh, OS/2, and so on).
As mentioned in Tip 514, "Understanding MS-SQL Server Client Software," you will need to install MS-SQL Server client software on a workstation when you want to work with the data or manage the MS-SQL Server installed on another computer on the network. You will find the MS-SQL Server client software on the MS-SQL Server installation CD. Please refer to table 514 in Tip 514 for a complete list of the client applications, documentation, and code samples available for installation.
Before starting the installation process, close all applications running on your workstation (be sure to save any unsaved work first) because you will be prompted to reboot your computer to finish the setup process. Then, to install the MS-SQL Server client software, documentation, or code samples on your workstation, perform the following steps:
After you complete Step 12, the MS-SQL Server installation program will begin copying the documentation and code sample files, and will install the client software applications that you selected in Step 10. Once it has finished the installation process, the setup program will display the Setup Complete screen. When you see it, click your mouse pointer on the Finish button to restart your computer.
To use an MS-SQL Server client, select the client from those listed in the MS-SQL Server group under Programs on the Windows start menu. If you installed code samples as well, you can find them in folders subordinate to the C:PROGRAM FILESMICROSOFT SQL SERVER folder.
MS-SQL Server uses tables to store both data and metadata. (Metadata consists of the fields and the value of the fields that describe the overall structure of the database and the objects such as tables, views, constraints, indexes, and keys, in it.) While users create and maintain the data tables that model real-world objects or events, the server's installation program creates the tables in the System Catalog and the SQL server maintains the metadata stored in the tables. Thus, the System Catalog consists of a set of tables whose data values describe everything about the database itself. By querying the System Catalogs, then, you can retrieve information such as:
Tables 516.1-516.4 provide the name, database location, and a brief description for each of tables in the MS-SQL Server system catalog. Although you can query the tables in the System Catalog directly, Microsoft recommends against this practice because the structure of the tables in the System Catalog changes from one version of the MS-SQL Server to another. Therefore, issue SELECT statements against System Catalog tables only if you cannot retrieve the information you need by using an information schema view (discussed in Tips 472-493), metadata function, or system stored procedure (discussed in Tips 606-640).
The following System Catalog tables are stored only in the MS-SQL Server's MASTER database.
Table Name |
Description |
---|---|
sysaltfiles |
Contains information about the physical files in which the database and its transaction log are stored on the hard drive(s). The logical name and physical pathname of each file, along with its initial size, maximum size, and growth rate, are stored in this table. (These are the parameters you entered on tabs in the Properties dialog box in Tips 495-497.) |
syscacheobjects |
Contains information about MS-SQL Server's system cached usage. |
syscharsets |
Contains one row of information about each of the character sets and sort orders available on MS-SQL Server. The character set and sort order marked as the default sort order in the SYSCONFIGURES table is the only one the server is actually using. |
sysconfigures |
Contains the saved values of MS-SQL Server's user settable configuration options. These are the configurations settings currently in effect when you first start MS-SQL Server. |
syscurconfigs |
Contains the system configuration settings currently in effect for any configuration options you change while the MS-SQL Server is running. The SYSCURCONFIGS table is empty each time you start the MS-SQL Server because it contains only the configuration settings you change during the server's operation. |
sysdatabases |
Contains the logical name, physical filename, creator, creation date, status, and other information on each of the databases managed by MS-SQL Server. |
sysdevices |
Contains one row of information on each disk-based backup file, tape-based backup file, and physical database file for the databases managed by MS-SQL Server. (Provided for backward compatibility with versions of MS-SQL Server prior to version 7.0.) |
syslanguages |
Contains one row of information about the date and numeric data format for each language available to the MS-SQL Server. Although not listed in SYSLANGUAGES, U.S. English is always available to the MS-SQL Server. |
syslockinfo |
Contains information about each lock request currently active on the system. The information includes the ID of user requesting the lock, its current status, the type of lock requested, and the object that is (or is to be) locked. |
syslogins |
Contains one row of information for each login to MS-SQL Server. The information includes the login name, whether the login ID is an individual or group name, and indicators that show whether the user is a member of an administration group or a DBCREATOR. |
sysmessages |
Contains one row with the error number, message group ID, severity, and description for each system error, alert, or warning message MS-SQL Server can issue. |
sysoledbusers |
Contains one row of information for each username/password pair that can be used to log in to and use a remote server (whose ID is also specified in the same row) as an OLE DB data source. |
sysperfinfo |
The MS-SQL Server's performance counters that can be displayed using the Windows NT Performance Monitor. |
sysprocesses |
Built dynamically when you query the table. Contains one row of information on each of the processes (both client and system) running on the MS-SQL Server at the time of the query. |
sysremotelogins |
Contains one row of information for each user allowed to run stored procedures on the current MS-SQL Server while logged in on a remote MS-SQL Server. |
sysservers |
Contains one row of information on each remote server that a user logged into the current server can access as an OLE DB data source. |
The following System Catalog tables are stored in each of the databases managed by MS-SQL Server.
Table Name |
Description |
---|---|
syscolumns |
Contains one row with the name, data type, scale, precision, and length for each column in every table and view, and a row with the same information plus the behavior of each parameter in a stored procedure. |
syscomments |
Contains one or more rows of information about each view, rule, default, trigger, CHECK constraint, DEFAULT constraint, and stored procedure. The number of rows used to define an object depends on the length of the SQL statements that define it. Each row's TEXT column (which holds the object's SQL statements) can hold a maximum of 4,000 characters. |
sysconstraints |
Contains a row with the mapping of each constraint to the table and column (where applicable) whose values it limits. |
sysdepends |
Contains rows that define the dependencies between database objects such as views, stored procedures, and triggers, and the database objects (tables, views, and stored procedures) used in the definition of each object. |
sysfilegroups |
Contains one row for each filegroup in the database. Each row contains a filegroup's ID, name, and status. |
sysfiles |
Contains one row for each physical disk file used to store database data. The row's columns hold the file's ID, the ID of the filegroup to which it belongs, and the physical pathname, logical (database) name, status, size, maximum size, and growth rate. |
sysforeignkeys |
Contains one row for each FOREIGN KEY constraint on table definitions. |
sysfulltextcatalogs |
Lists information about each full-text index created in the database. |
sysindexes |
Contains one row of information for each index and table in the database. |
sysindexkeys |
Contains one row of mapping information for each column used in an index. |
sysmembers |
Contains one row with the user ID and group (role) ID for each member of a database role. |
sysobjects |
Contains one row with the name, ID, object type, and owner ID for each object in the database. |
syspermissions |
Contains one row for each permission granted or denied to users, groups, and roles for each object in the database. |
sysprotects |
Contains one row with the user ID, object ID, and permission granted or denied using a GRANT or DENY statement. |
sysreferences |
Contains one row listing the referenced columns for each FOREIGN KEY constraint. |
systypes |
Contains one row of information about each system-supplied and user-defined data type. |
sysusers |
Contains one row of information on each user, group, and role allowed to access the database. |
The following System Catalog tables are stored in the MSDB database for use by the SQL Server Agent.
Table Name |
Description |
---|---|
sysalerts |
Contains one row describing the alert event that causes it, users to be alerted, and the delivery method for each alert defined to the MS-SQL Server. |
syscategories |
List of categories used by the MS-SQL Server Enterprise Manager to organize jobs, alerts, and operators. |
sysdownloadlist |
Contains the list of queued download instructions for all target servers. |
sysjobhistory |
Contains one row with the execution results for each job executed by the MS-SQL Server Agent. |
sysjobs |
Contains one row with the description of each job in the MS-SQL Server Agent's job queue. |
sysjobschedules |
Contains one row with the scheduling information for each job to be executed by the MS-SQL Server Agent. |
sysjobservers |
Contains one row that defines the target server on which to run the job for each job in the MS-SQL Server Agent's job queue. |
sysjobsteps |
Contains one row of description information for each step in each job to be executed by the MS-SQL Server Agent. |
sysnotifications |
Contains one row with the alert ID, user ID to receive the alert, and delivery method for each job status notification defined on MS-SQL Server. |
sysoperators |
Contains one row of information about each database operator. |
systargetserver-groupmembers |
Contains one row with the server ID and server group ID for each target server in a multi-server group. |
systargetservergroups |
Contains one row with the server ID and server group ID for each target server in a multi-server group. |
systargetservers |
Contains one row with the name, status, and lasting poll date, time, and status for each of the target servers in each multi-server group. |
systaskids |
Contains one row with information that maps each task created in an earlier version of MS-SQL Server to MS-SQL Server Enterprise Manager jobs in the current version. |
The following System Catalog tables are stored in the MSDB database for use by backup and restore operations.
Table Name |
Description |
---|---|
backupfile |
Contains one row of information for each file in the database and transaction log file that is backed up. |
backupmediafamily |
Contains one row of information about each media family used to back up data and log files. Each media family is a part of a backup set. |
backupmediaset |
Contains one row of information about each media set. |
backupset |
Contains one row of information about each backup set. Backup sets contain one or more media families. |
restorefile |
Contains one row for each file restored from backup, including the individual files restored when restoring all of the files in a file-group. |
restorefilegroup |
Contains one row for each filegroup restored from backup. |
restorehistory |
Contains one row of information about each restore operation executed on the MS-SQL Server. |
If you have not backed up your computer in a while, the last question you want to hear when you call the support department for an application you are running is, "When was your last backup?" While painful when it happens to you at home on your personal computer, being caught without a recent backup for a database used by multiple departments in a company can cause severe repercussions. Having to reenter a huge amount of data can be costly in terms of employee time and salaries, and it also could cost the company business as customers unable to place orders or access accurate account information take their business elsewhere.
Fortunately, all commercially available SQL servers provide several different methods you can use to protect against (or at least minimize) data loss and downtime due to equipment failure or user/application program error. These techniques range from "hot backups" that duplicate the information in the database on mirrored disks, to manual or scheduled backups that copy both database data files and transaction log files to a named backup device (either a tape drive or a disk drive file) at specific intervals during the day.
When implementing an SQL server backup scheme, keep in mind that you need to back up two different (and equally important) components of the database. First, you need to back up the database data and its objects-that is, you need to back up the physical disk file(s) in which the SQL server stores its tables, views, stored procedures, indexes, defaults, constraints, and so on. Second, you need to back up the transaction log file(s) that contains the "before" and "after" pictures of the database, stored by the SQL server as it executes transactions that change the structure of database objects or the data stored in them.
The most important things to understand when designing a backup strategy are that a backup is a snapshot of the database taken at a specific point in time, and the database's transaction log contains all of the changes made after the snapshot was taken since the last backup. Therefore, if the physical database file (the file with all of the database objects) is that large and you cannot back it up on a daily basis, then, at a minimum, back up the database file once per week and back up the transaction logs daily. In doing so, you can restore the database exactly as it was as on a specific date and time, and then restore and apply the transaction logs from the backup device, one at a time, for each day between the last backup and the day of the system failure that required you to restore the database.
One other consideration to keep in mind is that not all restore operations follow a catastrophic hardware failure. Sometimes a new program or stored procedure installed on the system causes data loss or stores invalid data values. In such instances, the problem may go unnoticed for several days (or weeks). As a result, you may want to restore the database to the way it was just before a user executed the erroneous program or stored procedure for the first time, instead of as it was when the data loss was detected. Therefore, a good backup system keeps a month (or at least two weeks) of backup sets available for restoration. By selecting the appropriate full backup and associated transaction log backups, you can then restore the database as it was at any point during the month (or the past two weeks).
When you back up a database file or its transaction log file, you copy its contents to a dump device. The dump device can be either a disk file on the local system, a disk file in a folder on a network drive, or a tape device. If you use a disk file as the dump device for the backup operation, you then set up the system-wide non-SQL server backup program to copy the database dump file to tape, to another hard drive, or to whatever location you use to store and manage your system backups.
When creating a backup file for SQL server data, the most important thing to understand is that you must let the SQL server create the backup file if you want the SQL server to be able to restore the data from the backup file later. If you simply rely on your system-wide backup program to back up the SQL server files (along with the other files it backs up), you must shut down the SQL server while the backup is running. (If you run an external backup program without shutting down the SQL server, the database and transaction log files will remain "in use" and the backup file will not be able to save them to the backup device. Moreover, if you use a non-SQL server backup program to create a backup, you cannot restore the backup and apply changes from the transaction log-you will have to use the snapshot of the database as is.)
To set up an MS-SQL Server backup (dump) device, perform the following steps:
Figure 518.1: The MS-SQL Server Enterprise Manager Backup Device Properties-New Device dialog box
Note |
If any of the folders listed in the backup file's path name do not exist, Enterprise Manager will display a warning message box similar to that shown in Figure 518.2 when you click the mouse pointer on the OK button in Step 8.
|
Note |
If you receive this error message, verify the path name that you entered. If the path name is correct, click the mouse pointer on the Yes button near the bottom center of the message box. Enterprise Manager will then go ahead and create the backup device. However, before you back up the database to the device (as you will learn to do in the next tip), you must create the folder path that you entered in Step 7. If you do not, the backup will fail and MS-SQL Server will display an error message similar to that shown in Figure 518.3.
|
Note |
If you receive this error message during the backup process, click the mouse pointer on the OK button at the bottom of the message box, use the Windows Explorer (or DOS command prompt) to create the folder structure you need, and then repeat the backup procedure (in the next tip). |
The important thing to understand now is that you must perform the steps in the preceding procedure to create a named backup (dump) device. To perform the actual SQL server backup operation, you will select the dump device that you learned to create in this tip while performing a manual SQL server backup (as you will learn in the next tip) or scheduling an automated backup (as you will learn to do in Tip 520, "Scheduling Automatic Backups of an MS-SQL Server"). As such, if you plan to make weekly full backups and daily transaction log backups, repeat the preceding procedure and then create a separate backup device for each backup that you plan to perform. For example, you would create the transaction log backup devices SQLTIPS-LOG-TUESDAY, SQLTIPS-LOG-WEDNESDAY, SQLTIPS-LOG-THURSDAY, SQLTIPS-LOG-FRIDAY, SQLTIPS-LOG-SATURDAY, and SQLTIPS-LOG-SUNDAY to be used in conjunction with the SQLTIPS-MONDAY full backup. You would then be able to back up to a different device (backup file) each day of the week.
After you create the backup (dump) devices needed to support your backups (as you learned to do in Tip 518, "Creating an MS-SQL Server Backup [Dump] Device"), you can use the devices to perform either manual or automatic/scheduled backups. However, because business emergencies, unexpected meetings, and the demands of life in general have a way of making even the most conscientious worker forget to perform a manual backup now and again, use the manual backup process as a "backup on demand." For example, prior to installing a new application or upgrade to an existing one, perform a manual backup so that you can restore the database to the state it was in immediately before problems caused by the new software. To protect database data against accidental loss on an ongoing basis, implement an automated backup scheme (which you will learn about in Tip 520, "Scheduling Automatic Backups of an MS-SQL Server").
To execute a manual backup, perform the following steps:
Figure 519.1: The MS-SQL Server Enterprise Manager SQL Server Backup dialog box
Figure 519.2: The MS-SQL Server Enterprise Manager Select Backup Destination dialog box
Either click the mouse pointer on the File Name radio button and enter that pathname of the disk file to which you want the Enterprise Manager to back up the database, or click your mouse pointer on the Backup Device radio button and select a backup (dump) device that you defined previously.
Then, click your mouse pointer on the OK button near the bottom-right corner of the Select Backup Destination dialog box.
Note |
Only use the "Append to media" option if you are performing a multiple database backup during a single backup session. For example, if you start the backup session with a backup of the SQLTips database, select the "Overwrite existing media" option. If you then decide to backup the MASTER database and the MSDB database to the same backup device, select the "Append to media" option when you perform the manual backup procedure for the second and third time. |
After you complete Step 11, the Enterprise Manager will display a Backup Progress message box with a status bar that shows you how close the backup process is to completion. When the Enterprise Manager completes the backup process, it will display a "Backup operation completed successfully" message box. Click the mouse pointer on the OK button at the bottom center of the message box to return to the Enterprise Manager application window.
A manual backup provides a convenient way to see how the MS-SQL Server backup process works, how long it takes to back up a particular database (or transaction log), and the impact on performance of executing a backup while users are logged in and using the database. For a greater degree of protection from accidental data loss (because someone forgot to run the backup the day before you need it for a database restore), set up a schedule of automatic backups, as you will learn to do in the next tip.
As mentioned in Tip 519, "Executing a Manual Backup of an MS-SQL Server Database," scheduled/automatic backups are your strongest defense against data loss due to equipment failure or the actions of errant applications or stored procedures. While the manual backup process is simple to execute, it is too often forgotten or put off "until tomorrow" because hardware has become so reliable. However, you need only experience the loss of several months worth of data one time to understand the importance of implementing a comprehensive and reliable database backup plan.
Fortunately, MS-SQL Server provides an easy way to make database backups occur automatically. After you schedule the backup jobs that you want done on a daily basis, you can rely on the server not to forget to execute a backup due to an upheaval in its "normal" workday.
Before you create the schedule of automatic backups, perform the procedure that you learned in Tip 518, "Creating an MS-SQL Server Backup [Dump] Device," as many times as necessary to create a different backup (dump) device for each of the backups that you want to schedule. If you plan to perform backups to tape, you need only a single backup device, since all backups will use to the same tape drive. (You can have the backup program vary the backup set's name to indicate the day of the week on which the MS-SQL Server Agent started it.) If you plan to perform backups to disk, however, you will want to use a different disk file for each backup session. As such, create at least seven backup (dump) devices similar to those shown in the right pane of the Enterprise Manager application window in Figure 520.1.
Figure 520.1: The MS-SQL Server Enterprise Manager application window with seven (daily) backup devices shown in its right pane
To create a queue of scheduled/automatic backups, perform the following steps:
Figure 520.2: The MS-SQL Server Enterprise Manager Edit Schedule dialog box
Figure 520.3: The MS-SQL Server Enterprise Manager Edit Recurring Job Schedule dialog box
Repeat Steps 1-9 six additional times to create weekly backup jobs for each of the remaining days of the week. Each time you perform the steps in the procedure, select a different day's backup (dump) device (in Step 9 of the procedure in Tip 519) and enter an appropriate description of the backup performed into the Name field in Step 3. Be sure to click the mouse pointer on the check box next to the correct day of the week in Step 6.
Note |
If your scheduled backups use a tape device, either you or another very trustworthy person on your staff must change the backup tape in the tape drive on a daily basis. Since each day's backup will overwrite the tape's contents, the backup scheme will fail if, for example, you leave Monday's backup tape in the drive and Tuesday's transaction log backup overwrites Monday's full database backup. If you are using a disk file as the backup device, your backup scheme will work as long as you do not run out of space on the hard drive on which you told MS-SQL Server to store the backup data. |
No one looks forward to a hardware or software failure. However, failures are bound to occur. Fortunately, having designed and implemented a comprehensive backup plan, you will be able to restore your SQL data and get the database back online in the shortest time possible.
Typically, restoring an MS-SQL Server to full functionality involves the following steps:
Prior to starting a database restore operation, you must have a functional MS-SQL Server installed and running on your fileserver. Therefore, execute the MS-SQL Server installation procedure (detailed in Tip 527, "Installing the MS-SQL Server"), if necessary.
Note |
If you are restoring database data after a hard drive failure, you have to reinstall MS-SQL Server only if its program files were somehow damaged or deleted. You do not have to reinstall MS-SQL Server in order to restore a damaged or lost database file. Therefore, before reinstalling the MS-SQL Server software, check the fileserver's task list to see if MS-SQL Server is already installed and running. If MS-SQL Server is not shown in the fileserver's task list, or if its status is not Running, check with the network administrator to make sure that the MS-SQL Server that you want to use was not moved to another fileserver or taken offline for some other reason. If the MS-SQL Server is simply Stopped, you can use the MS-SQL Server Service Manager to restart it (as you learned to do in Tip 511, "Using the MS-SQL Server Service Manager to Start the MS-SQL Server"). |
Next, make sure that the most recent complete (full) database backup file and any subsequent transaction log backup files are available. If you used a disk-based backup scheme to back up the MS-SQL Server to disk, restore the server's backup files from the network-wide backup system's disks as necessary. Conversely, if you used a tape-based backup scheme for MS-SQL Server backups, make sure that the tape device is available, and retrieve the MS-SQL Server backup tapes you need from storage.
After MS-SQL Server is up and running and you have the full database backup file and transaction log backup file(s) that you want to restore either on disk or on tape, perform the following steps to restore a database from a complete (full) backup file:
Figure 521.1: The MS-SQL Server Enterprise Manager Restore Database dialog box's General tab
Note |
If you are restoring all of the databases on an MS-SQL Server, make sure that you restore the MASTER database first. Next, repeat the steps in the current full backup restore procedure to restore the MSDB database. Then install any user-created databases. Be careful that you do not restore a user-created database such as SQLTips or COMPANY_DB as the MASTER database by accepting the default database name in the Restore to Database field. |
Figure 521.2: The MS-SQL Server Enterprise Manager Restore Database dialog box's General tab, with Restore from Device options displayed
Figure 521.3: The MS-SQL Server Enterprise Manager Choose Restore Devices dialog box
Figure 521.4: The MS-SQL Server Enterprise Manager Choose Restore Destination dialog box
Figure 521.5: The MS-SQL Server Enterprise Manager Restore Database dialog box's Options tab
Figure 521.6: The MS-SQL Server Enterprise Manager Restore Progress message box
When the Enterprise manager is finished restoring the database from the backup file, the program will display a "Restore Completed Successfully" message box. When you see the message box, click the mouse pointer on its OK button.
After you restore the database from the complete (full) backup file, you need to apply the changes to the database stored in the transaction log backup files created subsequent to the full database backup file. To restore and apply changes from a transaction log backup file, perform the following steps:
After the Enterprise Manager has finished restoring the transaction log from the backup file, it will display a "Restore completed successfully" message box. When you see the message box, click the mouse pointer on its OK button.
In addition to restoring the physical transaction log file, the restore process updates the database by executing the transactions stored in the transaction log file. As such, when you finish the transaction log backup file-restoration process, the database will look as it did when MS-SQL Server performed the transaction log backup.
Repeat the transaction log restore procedure as often as necessary in order to restore all of the transaction log backup files created subsequent to the full database backup. When you perform the steps in the procedure to restore the final transaction log backup file, be sure to select the Leave Database Operational, No Additional Transaction Logs Can Be Restored radio button in Step 14.
When you submit an SQL statement to the MS-SQL Server for execution, the database management system (DBMS) sends the statement to its query optimizer. The query optimizer analyzes the statement and generates the execution plan (i.e., the sequence of steps) the DBMS will perform in order to execute the statement. By adding one or more optimizer hints to an SQL statement, you can change the data retrieval methods and locking mechanisms the query optimizer will include in the statement's execution plan. In short, when you add optimizer hints to a statement, you are doing a portion of the query optimizer's job by deciding the most efficient way to retrieve data from the database or to issue locks in order to prevent deletion and modification anomalies.
For example, without optimizer hints, the query optimizer might decide against using an index when executing a SELECT statement, because the query only returns a small number of rows. It would be faster to retrieve the data only from the table (vs. the table and the index). Similarly, if a table has more than one index and the query optimizer decides it should use one of them when retrieving data from the table, the optimizer will select the index that it thinks will result in the fastest retrieval of data to satisfy the query. In both cases, you could add an optimizer hint to the query to force the query optimizer to use a particular index in its execution plan, thereby return a set of rows sorted in ascending order by the columns in the index you select.
You can also use optimizer hints to control the system's lock behavior when executing a DELETE, INSERT, SELECT, or UPDATE statement. For example, adding the WITH NOLOCK hint to a SELECT statement tells the DBMS to read data currently locked by other users (including inserted or updated and yet uncommitted data). Similarly, adding the WITH HOLDLOCK optimizer hint tells the DBMS to prevent others from modifying data in rows returned by your SELECT statement until the end of the current transaction.
Table 522.1 lists the optimizer hints available on an MS-SQL Server and a description of each hint.
Optimizer Hint |
Description |
---|---|
FAST x |
Optimize the query for fast retrieval of "x" rows. After returning the first "x" rows, query execution will continue to produce a full-results set. |
HOLDLOCK |
Hold a shared lock until the end of a transaction instead of releasing the lock on the row, table, or data page after reading its data. Using HOLDLOCK is similar to setting the transaction isolation level to SERIALIZABLE (Tip 357). |
INDEX = x |
Use INDEX "x" when selecting rows. |
INDEX () |
Use the indexes in the order specified when selecting rows. |
NOLOCK |
Do not issue shared locks and do not honor exclusive locks. NOLOCK is only applicable to the SELECT statement, and makes it possible for the query to read data from uncommitted UPDATE and DELETE statements that might be rolled back before the end of the query. |
PAGLOCK |
Use page-level locks to lock data in a table a page at a time instead of using a row-level lock or a table-level lock. |
READCOMMITTED |
Scan the rows in a table using the semantics of the READ COMMITTED transaction isolation level (Tip 360). |
READPAST |
Skip rows locked by other transactions instead of waiting for those transactions to release their locks before completing the query. READPAST is only applicable to a SELECT statement operating at the READ COMMITTED transaction isolation level (Tip 359), and will only skip over row level locks. |
READUNCOMITTED |
Equivalent to executing a SELECT statement with the NOLOCK optimizer hint or at the READ UNCOMMITTED transaction isolation level (Tip 360). |
REPEATABLEREAD |
Scan the rows in a table using the semantics of the REPEATABLE READ transaction isolation level (Tip 358). |
ROWLOCK |
Use row-level locks to lock data in a table a row at a time instead of using a page-level lock or a table-level lock. |
SERIALIZABLE |
Equivalent to executing a statement at the SERIALIZABLE transaction isolation level (Tip 357). |
TABLOCK |
Issue a table-level lock that locks the entire table instead of using a row-level lock or a page-level lock. |
TABLOCKX |
Issue an exclusive (vs. the default, shared) table-level lock, that locks the entire table instead of using a row-level lock or a page-level lock. Executing a statement with the TABLOCKX optimizer hint prevents other transactions from reading or updating the data in an entire table. |
UPDLOCK |
Use update locks instead of shared locks when reading the data in a table. An update lock lets others read data read by your transaction, but prevents them from updating the data until your transaction ends and releases its update locks. |
XLOCK |
Issue-exclusive (vs. shared or update) locks. Exclusive locks prevent others from accessing data read by your transaction until your transaction ends and releases the exclusive locks it issued. |
Use a WITH or OPTION clause to introduce one or more optimizer hints into SQL statements as follows:
DELETE [FROM] WITH () ... or DELETE [FROM]
[] OPTION () INSERT [INTO]
WITH () ... SELECT [] [] [] OPTION () UPDATE
WITH () ... or UPDATE
[] OPTION ()
When choosing optimizer hints in an effort to increase the efficiency of a query, you will find it helpful to review the list of instructions in the execution plan that the query optimizer generates. If you find a costly step such as full table scans, you can create new INDEXES or perhaps use an optimizer hint that directs the optimizer to use an existing index to eliminate the step.
If you execute a query after turning on the MS-SQL Server's SHOWPLAN_TEXT option (which you will learn about in Tip 523), the DBMS will display the steps that the query optimizer generated for the SELECT statement's execution plan. After you look through the plan, you can try executing the same query with different sets of optimizer hints until the query optimizer generates an execution plan more to your liking.
As mentioned in Tip 522 "Understanding MS-SQL Server Optimizer Hints," when you submit an SQL statement to the MS-SQL Server for execution, the DBMS sends the statement to the query optimizer, which, in turn, generates the statement's execution plan. (An execution plan is the sequence of steps the query optimizer tells the DBMS is to perform in order to execute a statement.)
When you tell the MS-SQL Server to execute a statement, you are normally interested only in the statement's results and not in how the DBMS produced them. For example, when you submit the query
SELECT a.au_lname, a.au_fname, t.title, t.ytd_sales FROM authors a, titles t, titleauthor ta WHERE a.au_id = t.au_ID AND t.title_ID = ta.title_ID
to the DBMS, you want the SQL server to return a list of author names, book titles, and sales figures. However, you really do not care how the DBMS retrieves the information from its tables. As such, the DBMS hides the execution plan from view.
However, if you are trying to improve a statement's performance, you will want to see the steps the DBMS must perform in order to execute it. When optimizing a SELECT statement, for example, you definitely want to know if the DBMS must perform a full-table scan when executing the query. Because reading every row in a large table usually makes executing a query take an unacceptably long time, the DBMS only performs a full-table scan if it cannot use any existing indexes to retrieve the data in the manner requested. Therefore, seeing a full-table scan in the query's execution plan would tell you that it might be possible to create an INDEX that will reduce the query's execution time.
You can use the MS-SQL Server's SHOWPLAN_TEXT option (and the SHOWPLAN_ALL option discussed in Tip 524), to tell the DBMS to show you what it plans to do "behind the scenes" when executing the SQL statements in a statement batch. One important thing to understand is that after you turn on the SHOWPLAN_TEXT option by submitting the SET statement
SET SHOWPLAN_TEXT ON
to the MS-SQL Server for execution, the DBMS will display the execution plan for each of the statements you submit to the DBMS. However, the DBMS will not actually execute any of the statements you submit until you turn off the SHOWPLAN_TEXT option by executing the SET statement
SET SHOWPLAN_TEXT OFF
For example, if you execute the SET statement
SET SHOWPLAN_TEXT ON
and then submit the statement batch shown in the upper pane in Figure 523.1, the DBMS will return a results set with the text of the statements in the batch, followed by the results set shown in the results (lower) pane in Figure 523.1.
Figure 523.1: The MS-SQL Server SQL Query Analyzer results after submitting a query with SHOWPLAN_TEXT set on
When you are finished reviewing execution plans for SQL statements you are trying to optimize, execute the SET statement
SET SHOWPLAN_TEXT OFF
to tell the DBMS to stop displaying execution plans and resume the normal execution of statements you submit to the server.
To construct a statement's execution plan, the MS-SQL Server's query optimizer uses statistical information that the server stores with database tables and indexes to evaluate alternative ways in which to execute the statement. For example, when you submit a SELECT statement with an ORDER BY clause, the query optimizer will check to see if the database has an index it can use to satisfy the sort requirements of the clause, or if it must add the step of physically sorting the rows it retrieves them from the table(s) involved in the query. In short, the query optimizer attempts to create a "least cost" (i.e., most efficient) execution plan for each SQL statement you submit to the MS-SQL Server for execution.
In Tip 523 "Using the MS-SQL Server SHOWPLAN_TEXT Option to Display a Statement's Execution Plan," you learned how to set the SHOWPLAN_TEXT option to "on" so that the DBMS would show you the execution plan for statements you told it to execute. Setting the MS-SQL Server's SHOWPLAN_ALL option to "on" also tells the DBMS to display statement execution plans rather than actually executing the statements. However, in addition to displaying the steps in an execution plan, the SHOWPLAN_ALL option also provides the data shown in Table 524.1 (as applicable) for each step.
Column Name |
Description |
---|---|
StmtText |
Contains the text of the Transact-SQL statement for rows that are not of type PLAN_ROW. For rows of type PLAN_ROW, this contains a description of the operation involved that includes a physical operator (such as "Index Seek" or "Clustered Index Scan"), and perhaps a logical operator, such as "Compute Scalar" or "Stream Aggregate." |
StmtID |
The number of the statement in the current connection. For example, if you are using the SQL Query Analyzer to execute SQL statements and this is the fifteenth statement you have submitted to the server, StmtID will have a value of 15. |
NodeID |
ID of the node in the current step. (A single step may consist of multiple physical database operations or nodes.) |
ParentID |
Node ID of the current step's parent step. |
PhysicalOp |
Physical database operation performed in the node. |
LogicalOp |
The logical and relational algebraic operation represented by the physical operation performed in the node. |
Argument |
Additional information about the physical database operation performed in the node. |
DefinedValues |
Contains a comma-separated list of values introduced by the operation that is performed in this node. The values may be computed expressions or internal values the query operator needs to process the query. Once introduced, defined values may be referenced elsewhere within the statement. |
EstimateRows |
An estimate of the number of rows of output the current operator will generate. |
EstimateIO |
Estimated input/output cost of the current operation. |
EstimateCPU |
Estimated CPU cost of the current operation. |
AvgRowSize |
Estimated average number of bytes of data in each row passed through the current operator. |
TotalSubtreeCost |
Estimated total cost of the current operation and all of its child operations. |
OutputList |
Contains a comma-separated list of columns projected by the current operation. |
Warnings |
Contains a comma-separated list of warning messages relating to the current operation. The query optimizer issues a warning message each time it has to make a decision based on a column for which it has no data. |
Type |
Contains the Transact-SQL statement type for a parent node and PLAN_ROW for nodes in the execution plan. |
Parallel |
Zero (0) if the operator is not running in parallel or one (1) if it is. |
Estimated Executions |
Estimated number of times this operation will be executed in the current statement. |
As was the case with the SHOWPLAN_TEXT option, you must execute the SET statement:
SET SHOWPLAN_TEXT OFF
when you are finished reviewing execution plans for SQL statements and want the DBMS to stop displaying execution plans and resume the normal execution of SQL statements you submit.
In addition to generating a text-based results sets with execution-plan information, the MS-SQL Server SQL Query Analyzer also lets you display execution plans graphically. In Tips 523 and 524, you learned how to use the statements SET SHOWPLAN_TEXT ON and SET SHOWPLAN_ALL ON. These statements are used so the DBMS returns the query optimizer-generated execution plans for SQL statements instead of executing the statements and returning their results sets.
When you submit an SQL statement with SHOWPLAN_TEXT ON or SHOWPLAN_ALL ON to the MS-SQL Server for execution, the DBMS returns an execution plan which lists the steps it would perform if it were to execute the statement. The DBMS returns the execution plan as rows of column values in a table—just like it would return the results set generated by a statement executed by the server. As such, with SHOWPLAN_TEXT or SHOWPLAN_ALL set to on, you can type an SQL statement batch in the SQL Query Analyzer's query (top) pane, select the Query menu Execute option, and review the statement's execution plan in the SQL Query Analyzer's results (bottom) pane.
You can also use the MS-SQL Server's SQL Query Analyzer to display a statement's execution plan graphically by performing the following steps:
Note |
If you type more than one statement into the query pane, you can generate an execution plan for all of the statements as a "statement batch." Conversely, if you only want to generate the execution plan for one of several statements in the query pane, use the mouse pointer to select the statement whose execution plan you want to see before you perform Step 6. |
Figure 525.1: The SQL Query Analyzer's graphical display of a statement execution plan
Note |
If you want the SQL Query Analyzer to submit both the statement (or statement batch) in the query pane to the DBMS for execution and display the execution plan, select the Query menu Show Execution Plan option. Unfortunately, the SQL Query Analyzer will not open a second results pane so you can see query results as well as the execution plan. Therefore, if you enter a SELECT statement into the query pane and select the Query menu Show Execution Plan option, the SQL Query Analyzer will ask the DBMS to execute the query. Keep in mind, however, that you will only see an execution plan (and not the query's results set) onscreen. |
Each of the icons displayed in the graphics-execution plan in the results pane represents a step in the plan. When you move your mouse pointer over an icon, the SQL Query Analyzer will display the values for several of the SHOWPLAN_ALL columns (explained in Table 524.1) for that step in the plan, similar to that shown in Figure 525.2.
Figure 525.2: The SQL Query Analyzer's graphical execution plan detail
Similarly, if you move the mouse pointer over an arrow between icons, the SQL Query Analyzer will display the estimated number or rows passed from one step to the next along with the estimated average byte length of each row passed.
Before you install the MS-SQL Server 2000 on your computer, make sure your system meets the minimum hardware requirements for the edition of the MS-SQL Server you are about to install.
At a minimum, to install and run the MS-SQL Server 2000, you need:
Note |
The MS-SQL is available in several editions: Enterprise Edition, Standard Edition, Evaluation Edition, Developer Edition, Personal Edition, and Desktop Engine. Please visit the MS-SQL Server 2000 area on the Microsoft Web site (www.microsoft.com/sql) for detailed product information about each edition. Then you can select the one that best satisfies your needs. |
As is the case with almost all Microsoft products, the MS-SQL Server 2000 has an installation wizard that will guide you through the process of installing the core (required) DBMS software and its optional components (such as the Microsoft English Query and Data Analysis Services) on your computer. Before installing the MS-SQL Server, make sure you computer meets the minimum requirements (detailed in Tip 526).
To install the MS-SQL Server, perform the following steps:
Figure 527.1: The MS-SQL Server Installation Welcome screen
Figure 527.2: The MS-SQL Server 2000 installation wizard Computer Name dialog box
Figure 527.3: The MS-SQL Server 2000 installation wizard Installation Selection dialog box
Figure 527.4: The MS-SQL Server 2000 installation wizard Installation Definition dialog box
Figure 527.5: The MS-SQL Server 2000 installation wizard Instance Name dialog box
Figure 527.6: The MS-SQL Server 2000 installation wizard Setup Type dialog box
Conversely, if you previously installed the SQL tools and code samples on this computer (and therefore do not want to install them again), click the mouse pointer on either the Typical or on the Minimum radio button—depending on the type of installation you want to perform. Then, click the mouse pointer on the Next button near the lower right corner of the dialog box. The installation wizard will display the Services Accounts screen of Step 14.
Figure 527.7: The MS-SQL Server 2000 installation wizard Services Accounts dialog box
Figure 527.8: The MS-SQL Server 2000 installation wizard Authentication Mode dialog box
Note |
Rather than using the system administrator's username and password, set up a separate username such as "SQLEXEC" (with a password, of course) and assign the user-name to the system administrators group. This will allow for administrator access to the DBMS if the system administrator changes. |
Note |
To explore the other DBMS startup options, click the mouse pointer on the Help button near the bottom center of the dialog box. The dialog box help screen gives examples of several different startup options for the MS-SQL Server. Moreover, the help screen lists the restrictions the operating system imposes on the MS-SQL Server's access rights. Keep in mind that if you choose to have the MS-SQL Server login to the local system account on startup, the MS-SQL Server will be unable to start if the system administrator later changes the password on the account. |
Note |
The security mechanism is the same whether you select Windows Authentication Mode or Mixed Mode. However, only Mixed Mode lets you set the sa account's password. Given the importance of not leaving the sa account's password blank, now is as good of a time as any to select a password to protect the account that has all access privileges to all objects in the DBMS. |
Figure 527.9: The MS-SQL Server 2000 installation wizard Network Libraries dialog box
Note |
The installation program will install all of the network libraries onto the server. Therefore, if you do not see the network library you need, or if the network administrator is not available to help you with the library setup right now, you can always configure the libraries any time after you install the MS-SQL Server. See MS-SQL Server 2000's Books Online help system for additional details. |
After you complete Step 18, the MS-SQL Server 2000 installation wizard will start copying the MS-SQL Server 2000's files onto your computer and setup the MS-SQL Server DBMS software as you specified through the installation wizard's dialog boxes. Once the installation wizard starts copying files, the MS-SQL Server 2000 installation will run to completion without further intervention on your part. The installation program will display a message box and a series of status bars that tell you the name of the file it is copying and how close the program is to completing its work.
When the installation program has finished installing the MS-SQL Server 2000 on your computer, the program will display a Setup Complete dialog box. Click the mouse pointer on the Finish button at bottom of the dialog box to reboot the computer so you can start using the MS-SQL Server. Unless you specified otherwise on the Services Account screen in Step 14, the MS-SQL Server 2000 will login as a system service and startup automatically during the computer's boot process.
When you implement database security, you will give some users access privileges on certain database objects and not on others. To test a user's access rights, you can login to the user's account, or if you are the system administrator (sa) or the database owner (DBO), you can use the SETUSER statement to impersonate any database user.
The syntax of the SETUSER STATEMENT is:
SETUSER [WITH NORESET]
Therefore, while logged in to the sa account you could execute the statement:
SETUSER MARY
for example, and test user MARY's access privileges on various database objects. Moreover, username MARY will own any database objects you create while the DBMS "thinks" you are MARY. As such, the SETUSER statement gives you an easy way to create new database objects and give a specific user all access privileges (as the database object owner (DBOO)) on those objects.
When you want to revert back to being the sa or DBO, execute the SETUSER statement without a username, or execute a USE statement.
If you include the WITH NORESET clause in the SETUSER statement, such as
SETUSER MARY NORESET
to impersonate another user, the DBMS will not change your identity back to the account you originally logged in on (either sa or DBO). If you include the NORESET option when you execute a SETUSER statement, the only way to get your original identity back is to logoff and then login as sa or DBO.
The MS-SQL Server uses the MODEL database as a template whenever you tell it to create a new database. Any new database the MS-SQL Server creates will have option settings identical to the database options of the MODEL database. Moreover, the new database will contain a copy of all objects that exist in the MODEL database when you execute the CREATE DATABASE statement. Therefore, the MODEL database provides the ideal starting place to create such things as rules, constraints, defaults, and tables that you want to exist in every database you create.
For example, if you want the rule created by
CREATE RULE valid_empnum AS @employee_number BETWEEN 1000 AND 1999
to be available in all databases created in the future, login to the MODEL database using the system administrator (sa) account and create the VALID_EMPNUM rule. MS-SQL Server will create the VALID_EMPNUM rule in each database you create subsequent to adding the rule as an object in the MODEL database. MS-SQL Server will, of course, stop creating the VALID_EMPNUM rule in new databases if you later drop the VALID_EMPNUM object from the MODEL database.
Note |
Because the MS-SQL Server creates the TMPDB database each time the operating system starts the DBMS, make sure you never delete the MODEL database. If you remove the MODEL database from the MS-SQL Server, the DBMS will not run because it will be unable to create the TMPDB database at startup. |
SQL Tips and Techniques