home *** CD-ROM | disk | FTP | other *** search
Text File | 2013-11-08 | 445.9 KB | 13,319 lines |
- Microsoft SQL Server - System Administrator's Guide
-
-
-
-
-
-
-
-
- ────────────────────────────────────────────────────────────────────────────
- Microsoft(R) SQL Server - System Administrator's Guide
-
- The SYBASE(R) SQL Server database for PC networks
- VERSION 1.1
- ────────────────────────────────────────────────────────────────────────────
-
-
- for the MS(R) OS/2 Operating System
-
-
-
-
-
-
-
-
- Microsoft Corporation
-
- Information in this document is subject to change without notice and does
- not represent a commitment on the part of Microsoft Corporation. The
- software described in this document is furnished under a license agreement
- or nondisclosure agreement. The software may be used or copied only in
- accordance with the terms of the agreement. It is against the law to copy
- the software on any medium except as specifically allowed in the license or
- nondisclosure agreement. No part of this manual may be reproduced or
- transmitted in any form or by any means, electronic or mechanical, including
- photocopying and recording, for any purpose without the express written
- permission of Microsoft Corporation.
- (C) 1990 Microsoft Corporation and SYBASE, Inc. All rights reserved.
-
-
- Printed in the USA.
-
-
- 1 = Microsoft, MS-DOS, MS, and the Microsoft logo are registered trademarks
- of Microsoft Corporation. IBM is a registered trademark of International
- Business
- Machines Corporation.
-
-
- SYBASE is a registered trademark of SYBASE, Inc.
- TRANSACT-SQL and DB-LIBRARY are trademarks of SYBASE, Inc.
-
- Document Number: SY10229-0290
- OEM-D/0788-1Z
-
-
-
-
-
-
- Table of Contents
- ────────────────────────────────────────────────────────────────────────────
-
-
-
- Before You Begin
- Manual Overview
- How to Use This Guide
- Notational Conventions
- Finding Further Information
-
- Chapter 1 Overview of System Administration
-
- Introduction
- Special Users of SQL Server
- System Administrator
- Database Owner
- Database Object Owner
- SQL Server Administration Tools
- SQL Server Administration Facility
- TRANSACT-SQL Statements
- System Procedures
- Help on TRANSACT-SQL Statements and System Procedures
- Utility Programs
- Batch Files and the isql Utility Program
- System Tables
- Permissions on System Tables
- Querying System Tables
- Keys in System Tables
- System Databases
- The master Database
- The model Database
- The tempdb Database
- The pubs Sample Database
-
- Chapter 2 Using the SAF
-
- Introduction
- Starting the SAF
- Responding to Messages
- Menus and Dialog Boxes
- Menus and Menu Items
- Dialog Boxes
- Text Boxes
- List Boxes
- Option Buttons
- Command Buttons
- Display Fields
- Getting Help
- Exiting the SAF
-
- Chapter 3 Making Queries with the SAF
-
- Introduction
- About the Examples
- Queries and Results
- Queries
- Results
- The Window Menu
- Creating Queries
- Entering Queries
- Scrolling
- Selecting and Deleting Text
- Executing Queries
- Viewing the Results of Queries
- Viewing the Query and Results on Separate Screens
- Scrolling the Results Window
- Alternating between Different Windows
- Modifying Previous Queries and Results
- Making a New Query
- Saving Queries and Results
- Filenames for Query and Results Files
- Saving Queries or Results to a File
- Working with Saved Queries and Results
- Printing Queries and Results
- Logging Queries and Results to a File
- Logging In to Another Server
-
- Chapter 4 Starting and Shutting Down SQL Server
-
- Introduction
- Starting SQL Server
- Starting SQL Server Using the SAF (MS OS/2 Only)
- Starting SQL Server Using the net Command
- Shutting Down SQL Server
- Shutting Down SQL Server Using the Config Menu
- Shutting Down SQL Server Using the SHUTDOWN Statement
- Shutting Down SQL Server Using the net Command
-
- Chapter 5 Managing Storage
-
- Introduction
- Dumping the master Database
- Adding Database Devices and Dump Devices
- Database Devices and Dump Devices
- Adding Database Devices
- Setting Up Default Database Devices
- Adding Dump Devices
- Displaying Information on Database Devices and Dump Devices
- Creating Databases and Transaction Logs
- Creating a Database
- Putting the Transaction Log into a Different Database Device
- Expanding the Transaction Log Space
- Altering Database Size
- Displaying Information on Database Storage
- How SQL Server Allocates Space for a Database
- Dropping Databases
- Dropping Database Devices and Dump Devices
-
- Chapter 6 Managing User Accounts
-
- Introduction
- Managing Login IDs
- Login IDs and Passwords
- Special Login IDs
- Default Databases
- Visitor Login IDs
- Managing Login IDs Using the Admin Menu
- Managing Login IDs Using System Procedures
- Displaying Information on Login IDs
- Managing Database Usernames
- Usernames
- Guest User
- Managing Usernames Using the Admin Menu
- Managing Usernames Using System Procedures
- Displaying Information on Usernames
- Managing Database Groups
- Groups
- Public Group
- Managing Database Groups Using the Admin Menu
- Managing Groups Using System Procedures
- Displaying Information on Groups
- Managing Aliases
- Aliases
- Managing Aliases Using the Admin Menu
- Managing Aliases Using System Procedures
- Displaying Information on Aliases
- Changing a Database Owner
- Changing a Database Owner Using the Admin Menu
- Changing a Database Owner Using System Procedures
- Displaying Information on Database Owners
- Displaying Information on Current Users
-
- Chapter 7 Managing User Permissions
-
- Introduction
- Permissions Summary
- Object and Statement Permissions
- The Permission Hierarchy
- Permissions of the SA
- Permissions of Database Owners
- Permissions of Database Object Owners
- Permissions on System Tables
- Permissions on System Procedures
- The SETUSER Statement
- Granting and Revoking Permissions
- GRANT and REVOKE Statements
- Combining GRANT and REVOKE Statements
- Conflicting GRANT and REVOKE Statements
- Displaying Information on Permissions
- Permissions on Views and Stored Procedures
- Views as Security Mechanisms
- Stored Procedures as Security Mechanisms
- Ownership Chains
- Triggers
-
- Chapter 8 Backup and Recovery
-
- Introduction
- Automatic Recovery
- Transaction Logs
- Checkpoints
- Dumping a Database or Transaction Log
- When to Dump Databases
- Dump Devices
- Dumping a Database
- Dumping a Transaction Log
- Truncating a Transaction Log
- Interactions between Backing Up a Database and Its Log
- Loading a Database
- Loading a Database Using the Admin Menu
- Loading a Database Using System Procedures
- Loading a Transaction Log
- Loading a Transaction Log Using the Admin Menu
- Loading a Transaction Log Using System Procedures
- Keeping Transaction Logs Small
- If You Run Out of Space in a Database
- Moving a Database
- Restoring the master Database
- Building the master Database
- Starting SQL Server in Single-User Mode
- Adding a Dump Device
- Reloading the master Database
- Applying Changes
- Recovering from Media Failure
- Re-creating Lost Devices and Reloading Lost Databases
- Finding Information on Lost Devices and Databases
- Examples of Recovery from Media Failure
-
- Chapter 9 Fine-tuning Performance and Operations
-
- Introduction
- Setting Query Options
- Setting and Changing Database Options
- Displaying Information on Database Options
- Monitoring SQL Server Activity
- Updating Statistics
- Locking and the HOLDLOCK Keyword
- Displaying Information on Locking
- HOLDLOCK Keyword
- Deadlocks and Livelocks
- Setting Configuration Options
- Configuration Options
- Changing Configuration Options Using the Config Menu
- Changing Configuration Options Using System Procedures
- Displaying Information on Configuration Options
-
- Chapter 10 Transferring Data to and from SQL Server
-
- Introduction
- Permissions Needed to Copy Data
- Transferring Data with the Bulk Copy Utility
- Native and Character Options
- Changing the Defaults: Interactive bcp
- File Storage Type
- Prefix Length
- Length
- Field Terminator
- Indexes
- Data Integrity: Defaults, Rules, and Triggers
- Example of Copying a Database Table to a File
- Copying Data for Use with Other Programs
- Example of Copying a File to a Database Table
- Error Files
-
- Chapter 11 Diagnosing System Problems
-
- Introduction
- Error Log
- Error Messages
- Message Numbers
- Severity Levels
- Reporting Errors
- Stopping Processes
- Database Consistency Checker
- The CHECKTABLE Option
- The CHECKDB Option
- The CHECKALLOC Option
- The CHECKCATALOG Option
- The DBREPAIR Option
-
- Appendix A The pubs Sample Database
-
- A.1.1
- Rules
- Trigger
- Stored Procedure
- View
- Defaults
-
- Appendix B System Tables
-
- sysalternates (all databases)
- syscolumns (all databases)
- syscomments (all databases)
- sysconfigures (master database only)
- syscurconfigs (master database only)
- sysdatabases (master database only)
- sysdepends (all databases)
- sysdevices (master database only)
- sysindexes (all databases)
- syskeys (all databases)
- syslocks (master database only)
- syslogins (master database only)
- syslogs (all databases)
- sysmessages (master database only)
- sysobjects (all databases)
- sysprocedures (all databases)
- sysprocesses (master database only)
- sysprotects (all databases)
- syssegments (all databases)
- systypes (all databases)
- sysusages (master database only)
- sysusers (all databases)
-
- Appendix C Special Keys
-
- Editing Keys (Dialog Boxes)
- Editing Keys (SQL Windows)
- Menu Keys
- Query Keys
-
- Index
-
-
-
-
- Before You Begin
- ────────────────────────────────────────────────────────────────────────────
-
-
- Manual Overview
-
- This manual explains the various tools and techniques used to manage SQL
- server databases. It is written for System Administrators who are
- responsible for maintaining systems running SQL Server.
-
- Before using this manual, you should be familiar with TRANSACT-SQL(tm),
- which is described in SQL Server Learning TRANSACT-SQL and in the SQL Server
- Language Reference. You should also be familiar with MS-DOS(R) and Microsoft
- Operating System/2 (MS(R) OS/2) system management.
-
-
- How to Use This Guide
-
- The following topics are covered in this manual:
-
- ────────────────────────────────────────────────────────────────────────────
- Chapter 1
- An overview of system and database administration
-
- Chapter 2
- Instructions for using the System Administration Facility (SAF)
-
- Chapter 3
- Information on creating queries with the SAF
-
- Chapter 4
- Instructions for starting and stopping SQL Server
-
- Chapter 5
- Information on managing storage
-
- Chapter 6
- Information on managing user accounts
-
- Chapter 7
- Information on managing user permissions
-
- Chapter 8
- Instructions for database backup and recovery
-
- Chapter 9
- Information on performance tuning
-
- Chapter 10
- Information on transferring data to and from SQL Server
-
- Chapter 11
- Help with diagnosing system problems
-
- Appendix A
- A description of the structure of the pubs sample database
-
- Appendix B
- A description of the various system tables
-
- Appendix C
- Special keys recognized by SAF
-
- ────────────────────────────────────────────────────────────────────────────
- Notational Conventions
-
- Throughout this manual, the following conventions are used to distinguish
- elements of text:
-
- ╓┌─────────────────────────────────┌─────────────────────────────────────────╖
- Convention Purpose
- ────────────────────────────────────────────────────────────────────────────
- UPPERCASE Represents statement and clause names,
- functions, macros, and any other
- portions of syntax that must appear
- exactly as shown.
-
- SMALL CAPS Represent key names such as CTRL.
-
- bold Represents stored procedures, system
- procedures, triggers, defaults, rules,
- utility programs, and commands.
-
- italic Represents database names, table names,
- Convention Purpose
- ────────────────────────────────────────────────────────────────────────────
- italic Represents database names, table names,
- view names, column names, datatypes,
- index names, pathnames, filenames, and
- variables that appear in text.
-
- monospace Represents examples, screen output,
- program code, and error messages.
-
- [brackets] Enclose optional items. Type only the
- information within the brackets, not the
- brackets themselves.
-
- {braces} Enclose required items. Type only the
- information within the braces, not the
- braces themselves.
-
- | (vertical bar) Separates items inside a set of braces
- or brackets. The vertical bar means you
- must choose one and only one item.
- Convention Purpose
- ────────────────────────────────────────────────────────────────────────────
- must choose one and only one item.
-
- ... (ellipsis) Means that you can repeat the previous
- item as many times as you like.
-
- <execute> Executes one or more SQL statements. (In
- the SQL Server Administration facility,
- SQL statements are executed by pressing
- the CONTROL+E keys. In the isql program,
- SQL statements are executed with the go
- command.)
-
- ────────────────────────────────────────────────────────────────────────────
-
-
-
-
- Finding Further Information
-
- The following manuals describe SQL Server and are included in the standard
- documentation set:
-
- ────────────────────────────────────────────────────────────────────────────
- SQL Server Installation Guide
- A guide to installing and setting up SQL Server
-
- SQL Server Learning TRANSACT-SQL
- A guide to learning and using TRANSACT-SQL
-
- SQL Server Language Reference
- A reference to the syntax of all TRANSACT-SQL statements, commands,
- procedures, and utilities
-
- SQL Server Programmer's Reference
- A reference to DB-LIBRARY(tm), which is a set of C routines and macros
- that allow your application to interact with SQL server
-
- SQL Server Quick Reference
- A quick reference guide to TRANSACT-SQL
-
- ────────────────────────────────────────────────────────────────────────────
-
-
-
-
- Chapter 1 Overview of System Administration
- ────────────────────────────────────────────────────────────────────────────
-
-
- Introduction
-
- This chapter describes
-
-
- ■ The special users who are responsible for managing SQL Server
- databases
-
- ■ The tools used to manage SQL Server databases
-
- ■ SQL Server system tables
-
- ■ SQL Server system databases
-
-
- Many of the procedures discussed in this document require you to be logged
- in as the System Administrator (SA). To identify yourself to SQL Server as
- the SA, use the login ID sa and the password that is assigned to the SA.
-
-
- Special Users of SQL Server
-
- Three types of special users manage and control SQL Server:
-
-
- ■ The System Administrator
-
- ■ Database Owners
-
- ■ Database Object Owners
-
-
-
- System Administrator
-
- The SA is not necessarily an individual; rather, system administration is a
- role. Anyone who knows the SA's password can log in and act as the SA. In a
- large organization, the SA's role can be carried out by several people or
- groups.
-
- The SA is responsible for administrative tasks unrelated to specific
- applications. Typically, the SA does the following:
-
-
- ■ Installs SQL Server
-
- ■ Manages storage
-
- ■ Creates user databases and grants ownership of them
-
- ■ Sets up user accounts on SQL Server
-
- ■ Grants permissions to SQL Server users
-
- ■ Backs up system data and restores it in case of failure
-
- ■ Transfers bulk data between SQL Server and other software programs
-
- ■ Diagnoses system problems
-
- ■ Fine-tunes SQL Server by changing the configuration options
-
-
- For information on installing SQL Server, see the SQL Server Installation
- Guide. The other system administration tasks listed above are described in
- this guide.
-
- When SQL Server is installed, the SA is the Database Owner of the master
- database. The SA is also treated as the Database Owner of any databases he
- or she uses.
-
-
- Login ID and Password
-
- The SA's login ID is sa. Immediately after installation, the SA has no
- password: that is, the password is the null value. As long as the SA has no
- password, anyone can log in as sa.
-
- ────────────────────────────────────────────────────────────────────────────
- NOTE
-
- After SQL Server has been installed, be sure to change the SA's password and
- to control knowledge of it. See Chapter 6, "Managing User Accounts," for
- instructions on changing passwords.
- ────────────────────────────────────────────────────────────────────────────
-
- More than one person in an organization can be authorized to log in as sa.
- However, it is important that the SA's administrative functions be
- centralized or well coordinated.
-
-
- Permissions
-
- Unlike other users, the SA has permission to use all TRANSACT-SQL
- statements, system procedures, and menus in the SQL Server Administration
- Facility (SAF). For detailed information on SA permissions, see Chapter 7,
- "Managing User Permissions."
-
-
- Database Owner
-
- A Database Owner creates a database and is then responsible for
- administrative tasks related to that database. These tasks include
-
-
- ■ Adding users to the database
-
- ■ Assigning users to groups
-
- ■ Granting permissions within the database
-
- ■ Creating tables
-
- ■ Creating procedures, rules, defaults, triggers, and views
-
- ■ Backing up and restoring the database
-
-
- The Database Owner owns the database and all its system tables.
-
-
- Login ID and Password
-
- A Database Owner logs in to SQL Server using his or her normal login ID and
- password. The Database Owner's username within the database is always dbo.
- This name is automatically assigned when the database is created.
-
-
- Permissions
-
- The Database Owner has full permissions inside the database he or she owns
- and must grant permissions to other users before they can access the
- database. For example, the Database Owner can give particular SQL Server
- users specified levels of access to the database and add a guest account to
- give all SQL Server users limited access to it. The Database Owner is
- responsible for granting other users permission to create tables, views,
- rules, defaults, and stored procedures.
-
- The Database Owner can also set up groups, which are used for convenience in
- granting and revoking permissions.
-
-
- Database Object Owner
-
- A user who creates a database object is its owner. Before creating a
- database object, permission to create that object must be granted by the
- Database Owner.
-
-
- Database Objects
-
- Each SQL Server database is a set of database objects. These database
- objects include the following:
-
- ╓┌─────────────────────────────────┌─────────────────────────────────────────╖
- Database Object Description
- ────────────────────────────────────────────────────────────────────────────
- Default A value that SQL Server inserts into a
- column if the user does not enter a
- Database Object Description
- ────────────────────────────────────────────────────────────────────────────
- column if the user does not enter a
- value
-
- Index An ordered set of pointers to the data
- in a table
-
- Rule A specification controlling what data
- can be entered in a column
-
- Stored procedure A precompiled collection of SQL
- statements
-
- Table A collection of rows and columns
-
- Trigger A special form of stored procedure that
- goes into effect automatically when a
- user modifies data in a table
-
- View An alternate way of looking at data in
- Database Object Description
- ────────────────────────────────────────────────────────────────────────────
- View An alternate way of looking at data in
- one or more tables
-
- ────────────────────────────────────────────────────────────────────────────
-
-
-
- For complete information on database objects, see SQL Server Learning
- TRANSACT-SQL.
-
-
- Login ID and Password
-
- A database object owner logs in to SQL Server using his or her normal login
- ID. There is no special login ID or password for database object owners.
-
-
- Permissions
-
- A database object owner must grant permissions to other users before they
- can access the database object.
-
-
- SQL Server Administration Tools
-
- To manage an SQL Server database, you use a combination of SAF menus,
- TRANSACT-SQL statements, and system procedures. You can also develop batch
- files made up of a series of SQL statements.
-
-
- SQL Server Administration Facility
-
- The SAF provides easy-to-use menus, which help you perform many system
- administration tasks, and the SQL Query Window, which you use to execute
- TRANSACT-SQL statements and system procedures.
-
- In many cases, you have a choice: you can perform a task by using a menu or
- by executing SQL statements and system procedures. In some cases, there is
- no menu to perform a task, so you must use SQL statements or system
- procedures.
-
-
- Menus
-
- You can use SAF menus to perform common administrative tasks, such as
-
-
- ■ Adding user accounts
-
- ■ Saving queries and their results to files
-
- ■ Setting configuration options
-
- ■ Shutting down SQL Server
-
-
- See Chapter 2, "Using the SAF," and Chapter 3, "Making Queries with the
- SAF," for details on how to use SAF menus.
-
-
- SQL Query Window
-
- The SQL Query Window allows you to enter, edit, and execute SQL statements
- or system procedures. After you execute the statement or system procedure,
- the results appear at the bottom of the screen. An example of a system
- procedure and its results is shown in Figure 1.1:
-
- (This figure may be found in the printed book.)
-
- See Chapter 2, "Using the SAF," and Chapter 3, "Making Queries with the
- SAF," for details on how to execute SQL statements and system procedures
- from the SQL Query Window.
-
-
- SAF Help
-
- From the SAF Help menu, you can get information on some of the most common
- system administration tasks. Many administrative tasks can be performed by
- using SAF menus; however, some more complex tasks cannot be performed
- through these menus. The SAF Help screens include step-by-step procedures
- that show how to perform these more complex tasks.
-
- See Chapter 2, "Using the SAF," and Chapter 3, "Making Queries with the
- SAF," for details on how to use SAF Help.
-
-
- TRANSACT-SQL Statements
-
- TRANSACT-SQL, the enhanced SQL language, contains many statements used by
- SAs. You execute these statements from the SQL Query Window. TRANSACT-SQL
- statements are described throughout this manual and also in SQL Server
- Learning TRANSACT-SQL and the SQL Server Language Reference.
-
-
- System Procedures
-
- A system procedure is a precompiled collection of SQL statements. Many
- system procedures are available for managing SQL Server and for displaying
- information on databases and users.
-
- System procedures are located in the master database and are owned by the
- SA, but many of them can be executed from any database.
-
- You can write your own system procedures that can be executed from any
- database. See SQL Server Learning TRANSACT-SQL for more information on
- creating your own system procedures.
-
- If a system procedure is executed in a database other than master, it
- operates on the system tables in the database from which it was executed.
-
- System procedures are described throughout this manual and also in SQL
- Server Learning TRANSACT-SQL and the SQL Server Language Reference.
-
-
- Help on TRANSACT-SQL Statements and System Procedures
-
- The sp_helpsql system procedure displays the syntax of TRANSACT-SQL
- statements, system procedures, and other topics. You can use the sp_helpsql
- system procedure as you develop queries. The sp_helpsql system procedure has
- the following syntax:
-
- sp_helpsql ["topic"]
-
- For example, to get help on the DISK INIT statement, execute
-
- sp_helpsql "disk init"
-
-
- Utility Programs
-
- Utility programs are executed from the operating system prompt, not from the
- SAF. SQL Server includes these utility programs:
-
- ╓┌─────────────────────────────────┌─────────────────────────────────────────╖
- Utility Program Function
- ────────────────────────────────────────────────────────────────────────────
- bcp Copies a database table to or from an
- operating system file.
-
- bldmastr Builds the master database.
-
- console Prompts the operator while a database is
- being backed up or restored to or from
- diskettes. When you use the SAF to back
- up or restore a database, you do not
- Utility Program Function
- ────────────────────────────────────────────────────────────────────────────
- up or restore a database, you do not
- need to start the console program.
-
- defncopy Copies definitions of database objects
- to a file.
-
- isql Executes batch files.
-
- ────────────────────────────────────────────────────────────────────────────
-
-
-
-
- Batch Files and the isql Utility Program
-
- The isql utility program executes a batch file which contains one or more
- SQL statements.
-
- You can use the SAF or a text editor to create and save a batch file. Be
- sure to add the go command on a separate line to execute previous SQL
- statements or system procedures.
-
- To execute the batch file, use the isql command at the operating system
- prompt. (See the SQL Server Language Reference for details on isql.)
-
- For example, the following isql command executes a batch file, authors.qry,
- and places the results in the authors.res file:
-
- isql /U sa /P mypassword /S myserver /i authors.qry /o authors.res
-
-
- System Tables
-
- SQL Server system tables keep track of information about SQL Server as a
- whole and about each user database.
-
- All of the SQL-Server-supplied tables in the master database (SQL Server's
- controlling database) are considered system tables. In addition, each user
- database is created with a subset of these system tables.
-
- A master database and its tables are created when SQL Server is installed.
- The system tables in a user database are automatically created when the
- CREATE DATABASE statement is executed.
-
- See Appendix B, "System Tables," for detailed information on each system
- table.
-
-
- Permissions on System Tables
-
- The Database Owner controls permissions for use of the system tables, just
- like permissions on any other tables.
-
- The SQL Server setup program sets up permissions so that all users can read
- necessary information in the system tables.
-
- Direct updates to system tables are not allowed, even for the Database
- Owner. In almost all cases, updates to the system tables should be performed
- using system procedures or SAF menus. To set a configuration option that
- allows direct updates to the system tables, see Chapter 9, "Fine-tuning
- Performance and Operations."
-
-
- Querying System Tables
-
- The system tables can be queried just like any other table. For example,
- here's a statement that returns the names of all triggers in the current
- database:
-
- select name
- from sysobjects
- where type = "TR"
-
- The system procedures provide shortcuts for querying the system tables.
-
-
- Keys in System Tables
-
- Primary, foreign, and common keys for the system tables have been defined in
- the master and model databases. A report on defined keys is available by
- executing the sp_helpkey system procedure. For a report on columns in two
- system tables that are likely join candidates, execute sp_helpjoins.
-
-
-
- System Databases
-
- When SQL Server is installed, it has three databases: the master database,
- model database, and tempdb temporary database. The SA can optionally install
- the pubs sample database.
-
-
- The master Database
-
- The master database controls the user databases and the operation of SQL
- Server as a whole. It keeps track of user accounts, ongoing processes,
- system error messages, the databases on SQL Server, the storage allocated to
- each database, the available database devices and dump devices, and the
- active locks. In addition, the system procedures are stored in master.
-
- You must be in the master database to execute the CREATE DATABASE, DISK
- INIT, DISK REFIT, and DISK REINIT statements.
-
- It is possible to add user objects to the master database, but it's not a
- good idea. Any objects created in master should be used for the
- administration of the system as a whole, so permissions in master should be
- set so that most users cannot create objects there.
-
- Another way to discourage users from creating objects in master is to change
- users' default databases (the database to which the user is connected after
- login). Default databases are discussed in Chapter 6, "Managing User
- Accounts."
-
- ────────────────────────────────────────────────────────────────────────────
- WARNING
-
- You should back up the master database after you change it─each time you
- create a database, alter a database, allocate physical storage, and so on.
- If the master database is damaged, it is recovered with a procedure
- different from that for user databases. (See Chapter 8, "Backup and
- Recovery.")
- ────────────────────────────────────────────────────────────────────────────
-
-
- The model Database
-
- The model database provides a template or prototype for new user databases.
- Each time the CREATE DATABASE statement is executed, SQL Server makes a copy
- of the model database and then extends it to the size requested in the
- CREATE DATABASE statement.
-
- The model database contains the system tables required for each user
- database. It can be modified to customize the structure of newly created
- databases─everything you do to model is reflected in each new database. Here
- are some of the changes that are commonly made to model:
-
-
- ■ Adding user datatypes, rules, or defaults.
-
- ■ Adding to model..sysusers users who are to be given access to all
- databases on SQL Server.
-
- ■ Establishing default permissions, particularly for guest accounts.
-
- ■ Setting database options. The setting of options is then reflected in
- all new databases. The original value of database options in model is
- OFF. Database options are described in Chapter 9, "Fine-tuning
- Performance and Operations."
-
-
- Typically, most users are not granted permission to modify the model
- database. There is no need to grant permission to read it either, since its
- entire contents are copied into each new user database.
-
-
- The tempdb Database
-
- The tempdb temporary database provides storage for temporary tables and
- other temporary storage needs (for example, intermediate results of GROUP BY
- and ORDER BY).
-
- All temporary tables are stored in the temporary database, no matter what
- database the user who creates them is using. However, you can query a
- temporary table from inside the database in which it was created or from
- tempdb. If you query tempdb..sysobjects, you will notice that a suffix is
- attached to the names of temporary tables. System procedures (for example,
- sp_help) do not work on temporary tables.
-
- The temporary database is a shared work space used by all the databases on
- SQL Server. Its contents are destroyed every time the current user leaves
- SQL Server or when the system stops. Temporary objects can also be deleted
- before a session ends.
-
- The default size of the temporary database can be changed by the SA with the
- ALTER DATABASE statement.
-
- No special permissions are required to use the temporary database─that is,
- to create temporary objects or to execute statements (such as ORDER BY) that
- may require storage space in the temporary database.
-
-
- The pubs Sample Database
-
- Installing the pubs sample database is optional. It is provided as a
- learning tool and is used as the basis of most of the examples in the SQL
- Server manual set. The pubs database is illustrated in Appendix A of this
- guide.
-
- The pubs database consists of eight tables: publishers, authors, titles,
- titleauthor, roysched, sales, stores, and discounts. These tables have the
- following description:
-
- ╓┌─────────────────────────────────┌─────────────────────────────────────────╖
- Table Description
- ────────────────────────────────────────────────────────────────────────────
- publishers Contains the identification numbers,
- names, cities, and states of three
- publishing companies.
-
- authors Contains an identification number, first
- and last name, address, and contract
- status for each author.
-
- titles Contains the identification number, name,
- type, publisher identification number,
- price, advance, royalty, year-to-date
- sales, comments, and publication date
- for each book that has been or is about
- Table Description
- ────────────────────────────────────────────────────────────────────────────
- for each book that has been or is about
- to be published.
-
- titleauthor Links the titles and authors tables
- together. For each book, it contains the
- title ID, the author ID, the author
- order, and the royalty split among the
- authors of a book.
-
- roysched Lists the unit sales ranges and the
- royalty connected with each range. The
- royalty is some percentage of the net
- receipts from sales.
-
- sales Records bookstore sales of titles in the
- titles table.
-
- stores Lists bookstores by store ID.
-
- Table Description
- ────────────────────────────────────────────────────────────────────────────
- discounts Lists three types of discounts for
- bookstores.
-
- ────────────────────────────────────────────────────────────────────────────
-
-
-
- The pubs database contains a guest user mechanism that allows any authorized
- SQL Server user to access it. The guest user has been given a fairly wide
- range of permissions in pubs, including permission to select, insert,
- update, and delete all the user tables. For more on the guest user mechanism
- and a list of the guest permissions in pubs, see Chapter 6, "Managing User
- Accounts."
-
-
-
-
-
-
- Chapter 2 Using the SAF
- ────────────────────────────────────────────────────────────────────────────
-
-
- Introduction
-
- This chapter explains how to use the SQL Server Administration Facility
- (SAF). The SAF is a system of menus and dialog boxes that allows you to
- query an SQL database, view the results of your query, and manage your query
- and results files.
-
-
- Starting the SAF
-
- Before you can start the SAF, you need the following information (if
- necessary, see your SA):
-
-
- ■ The name of the server to which you will log in
-
- ■ Your login ID
-
- ■ Your password
-
-
- Before you start SAF, you must start your network workstation, if it is not
- already started.
-
- When you start SAF, you can include the server name, username, and password
- on the command line. You can also omit one or more of the parameters and let
- SAF prompt you for their values. The following examples show all of the
- correct ways to start the SAF:
-
- saf servername username password
-
- saf servername username
-
- saf servername
-
- saf
-
- SAF passes the username and password to the server exactly as you have typed
- them. If the requested server is case-sensitive, your parameters must match
- exactly.
-
- If you type in parameters, remember that they are position dependent; you
- must specify them in order. For example, you cannot leave out the server
- name and type the username and password. This example is incorrect:
-
- saf username password
-
- Follow these steps in order to start the SAF:
-
-
- 1. Start your network workstation, if it is not already started.
-
- 2. Type one of the correct commands as shown above.
-
- An introductory dialog box appears on your screen:
-
- (This figure may be found in the printed book.)
-
- 3. Press the ENTER key.
-
- If you did not specify a server name on the command line, skip down to
- step 9. If you did specify a server name, SAF displays the following
- message on the bottom of the screen:
-
- Attempting to logon...
-
- 4. If the parameters you typed were valid and, if the server is running,
- SAF displays the following message:
-
- Connection complete. Inialization in process...
-
-
- After a few moments, SAF displays the SQL Query Window illustrated in
- Figure 2-5. This finishes the login sequence.
-
- 5. If SAF cannot connect to the server you specified on the command line,
- it displays the following dialog box (under MS OS/2 only because you
- cannot start a server from SAF under MS-DOS):
-
- (This figure may be found in the printed book.)
-
- If you choose Cancel, SAF skips down to step 9 in this login sequence.
-
- 6. If you press the ENTER key, SAF displays the following message on
- your screen:
-
- Attempting to start SQL Server...
-
-
- 7. If it cannot start the server, SAF displays the following dialog box
- on your screen:
-
- (This figure may be found in the printed book.)
-
- 8. Press the ENTER key to clear the dialog box.
-
- 9. If you do not enter a server name on the command line or, if it cannot
- locate or start the server you requested, SAF displays the following
- message on your screen:
-
- Please wait for a list of available SQL Servers...
-
-
- After a brief pause, SAF displays the "Login to SQL Server" dialog box
- on your screen:
-
- (This figure may be found in the printed book.)
-
- In the center of the dialog box is a list of visible servers to which
- you can log in. The default server is highlighted.
-
- 10. To select a server other than the default, use the direction keys to
- highlight a different server, or press the SHIFT+TAB keys to move to
- the text box and type in a server name.
-
- 11. Press the TAB key to move the cursor to the "Login ID" text box.
-
- 12. If you included a login ID on the SAF command line, SAF displays it in
- the highlighted text box. Otherwise, type in your login ID.
-
- 13. Press the TAB key to move to the "Password" text box.
-
- 14. If you included a password on the SAF command line, SAF places it in
- the highlighted text box. Otherwise, type in your password. (In either
- case, your password does not appear on the screen.)
-
- 15. Press the ENTER key.
-
- The SQL Query Window appears on your screen:
-
- (This figure may be found in the printed book.)
-
- If you type the wrong login ID or password, the following dialog box
- appears:
-
- (This figure may be found in the printed book.)
-
- To correct your login ID or password:
-
- 16. Press the ENTER key to clear the message.
-
- The "Login to SQL Server" dialog box reappears.
-
- 17. Select the server to which you want to log in and type your correct
- login ID and password.
-
- 18. Press the ENTER key.
-
-
- If you have problems logging in, see your SA.
-
-
- Responding to Messages
-
- As you use the SAF, you will see messages in dialog boxes. Usually the
- messages ask you a question and then take some action depending on your
- response. For example, the following message appears when you want to change
- servers:
-
- (This figure may be found in the printed book.)
-
- You can log out of the current SQL Server by pressing the ENTER key to
- select the highlighted OK command button. If you do not want to log out,
- press the TAB key so that the Cancel command button is highlighted. Then
- press the ENTER key. The message is cleared from the screen, and you are
- still logged in to the SQL Server.
-
-
- Menus and Dialog Boxes
-
- While using the SAF, you move through a series of displays, making
- selections and entering information. You encounter two types of displays:
- menus and dialog boxes.
-
- This section describes how to identify and use menus and dialog boxes. You
- can work with both a keyboard and a mouse, or with just a keyboard.
-
- You can press the ESC key at any time to cancel the current operation and
- move up one level in the SAF. Pressing the ESC key repeatedly returns you to
- the top level.
-
-
- Menus and Menu Items
-
- The names of all available SAF menus appear at the top of the screen:
-
- ╓┌─────────────────────────────────┌─────────────────────────────────────────╖
- Menu Purpose
- ────────────────────────────────────────────────────────────────────────────
- File Transfers the contents of a file to and
- from the current SAF window and prints
- the contents of the current SAF window
- or the results of a query.
-
- Config Logs you in to a different server.
- Additional items on the Config menu are
- available only to SAs.
-
- Admin Performs system administration
- functions.
-
- Query Executes an SQL query or prepares for
- the next query. It also allows you to
- start a query log.
-
- Menu Purpose
- ────────────────────────────────────────────────────────────────────────────
- Window Selects a query window for typing
- queries or a results window for viewing
- the results of these queries.
-
- Help Provides help for system administration
- tasks.
-
- ────────────────────────────────────────────────────────────────────────────
-
-
-
- When you select a menu, the SAF displays a list of menu items. For example,
- when you select the Query menu, you see the following list of menu items on
- your screen:
-
- (This figure may be found in the printed book.)
-
-
- Permission to Use Menu Items
-
- Some menu items are available only to SAs or Database Owners. If you do not
- have permission to choose a menu item, that menu item appears in gray rather
- than black letters.
-
-
- Choosing a Menu Item with the Keyboard
-
- To see a menu's list of items and to choose a menu item with the keyboard:
-
-
- 1. Clear all dialog boxes from the screen.
-
- If there are dialog boxes on your screen, press the ESC key repeatedly
- until all dialog boxes have disappeared.
-
- 2. Press the ALT key, which highlights the first letter of each menu.
-
- 3. Press the highlighted letter of the menu you want to use.
-
- The menu displays its list of menu items.
-
- 4. Press the highlighted letter of the menu item you want. (You can also
- press the direction keys followed by the ENTER key to select an item
- from the menu.)
-
- A dialog box appears on your screen.
-
-
-
- Example
-
- To open an existing file:
-
-
- 1. Press the ALT key.
-
- 2. Press F to select the File menu, which looks like this:
-
- (This figure may be found in the printed book.)
-
- 3. Press O to choose Open.
-
- The "Open File" dialog box appears:
-
- (This figure may be found in the printed book.)
-
-
-
- Selecting a Menu Item with a Mouse
-
- To select a menu and choose a menu item with a mouse:
-
-
- 1. Move the mouse pointer to the menu you want to use.
-
- 2. Press and release the left mouse button. (This action is called
- clicking.)
-
- The selected menu displays its list of menu items.
-
- 3. Move the mouse pointer to the menu item you want, and then click the
- left mouse button.
-
- A dialog box appears on your screen.
-
-
-
- Accelerator Keys
-
- Some commonly used menu items have accelerator keys, which are listed to the
- right of the menu item. Use these keys to choose a menu item without having
- to select the menu first. The following accelerator keys are available:
-
- ╓┌───────┌──────────────────────────┌────────────────────────────────────────╖
- Menu Menu Item Accelerator Key
- ────────────────────────────────────────────────────────────────────────────
- File Exit F3
- Query Execute Query CTRL+E
- Query Next Query CTRL+N
- Window SQL Query CTRL+Q
- Window SQL Results (half screen) CTRL+R
- Window SQL Results Full CTRL+F
- Menu Menu Item Accelerator Key
- ────────────────────────────────────────────────────────────────────────────
- Window SQL Results Full CTRL+F
- ────────────────────────────────────────────────────────────────────────────
-
-
-
- Dialog Boxes
-
- A dialog box has several different areas where you make selections and enter
- information. It can contain up to five different areas:
-
-
- ■ Text box
-
- ■ List box
-
- ■ Option buttons
-
- ■ Command buttons
-
- ■ Display field
-
-
- For example, the "Open File" dialog box contains four areas: a text box, a
- display field, two list boxes, and two command buttons:
-
- (This figure may be found in the printed book.)
-
- Use the TAB key to move between the different areas within a dialog box. To
- move the cursor to a previous area, use the SHIFT+TAB keys to move backward
- through the fields.
-
-
- Text Boxes
-
- A text box is an area in the dialog box where you enter or change
- information. Sometimes text boxes appear with information already supplied.
- This is the default information for that text box. If you want to use the
- default information, leave the text box as is.
-
-
- Using Text Boxes
-
- To supply or change the contents of a text box:
-
-
- 1. Press the TAB key to move the cursor to the different areas in the
- dialog box. Stop when you reach the text box you want to change.
-
- (You can also use the SHIFT+TAB keys.)
-
- 2. If necessary, delete information already in the text box by pressing
- the DEL or BACKSPACE key.
-
- 3. Type the desired information in the text box.
-
-
- The following keys help you view or change the contents of the text box:
-
- Key Movement
- ────────────────────────────────────────────────────────────────────────────
- HOME Moves the cursor to the left side of any text in the field
- END Moves the cursor to the right side of any text in the field
- DEL Deletes the character under the cursor
- BACKSPACE Deletes the character to the left of the cursor
- ────────────────────────────────────────────────────────────────────────────
-
- A text box can hold more characters than fit in the actual box on the
- screen. As you type characters, the text box scrolls horizontally to show
- what you are typing. The HOME, END, LEFT, and RIGHT keys also cause the text
- box to scroll as necessary.
-
-
- Using Text Boxes with a Mouse
-
- To change the contents of a text box with a mouse:
-
-
- 1. Move the mouse pointer to the text box.
-
- 2. Click the left mouse button.
-
- A text pointer appears inside the text box.
-
- 3. Enter, change, or delete information in the same manner as described
- in "Using Text Boxes," earlier in this chapter.
-
-
-
- List Boxes
-
- A list box presents a list of items to select from, such as a list of
- filenames.
-
-
- Using List Boxes
-
- To select an item in a list box:
-
-
- 1. Press the TAB key to move the cursor into the list box.
-
- 2. To see all entries in the box and select an item, use the following
- keys:
- ╓┌───────────────────┌───────────────────────────────────────────────────────╖
- Key Movement
- ────────────────────────────────────────────────────────────────────────────
- UP Up one line
- DOWN Down one line
- PG UP Up one page
- PG DN Down one page
- HOME To the top of the list
- END To the bottom of the list
- ────────────────────────────────────────────────────────────────────────────
-
-
-
-
-
- The items in the list box are arranged alphabetically. You can move to the
- first item starting with a particular letter by pressing that letter while
- the cursor is in the list box. The item that is highlighted is your selected
- item.
-
-
- 1. Press the TAB key to go to the next area.
-
-
-
- Using List Boxes with a Mouse
-
- To view or select from the contents of a list box with a mouse:
-
-
- 1. Move the mouse pointer to the scroll bar at the right of the list box.
-
- This scroll bar controls what you see in the list box.
-
- 2. Place the mouse pointer over the scroll box in the scroll bar. Press
- and hold down the left mouse button (this action is known as
- dragging), and move the scroll box up or down.
-
- The following list box from the "Open File" dialog box shows the
- scroll box and scroll bar:
-
- (This figure may be found in the printed book.)
-
- 3. Drag the scroll box to a location in the scroll bar that roughly
- corresponds to the location in the list box that you want to bring
- into view.
-
- 4. Release the left mouse button.
-
- The view in the list box changes.
-
- 5. Move the contents of the list box up or down one line by clicking the
- up or down arrows at the ends of the scroll bar.
-
- 6. Move the mouse pointer to your selection in the list box, and click
- the left mouse button.
-
- The contents of the text box is updated to correspond to your list box
- selection.
-
-
-
- Option Buttons
-
- An option button is an option preceded by parentheses in a dialog box.
- Option buttons always appear in sets of at least two; only one option button
- in a set can be selected at a time. The selected option button has a small
- circle inside the parentheses.
-
- When a dialog box appears on your screen, one option button is highlighted.
- This is the default option button.
-
-
- Using Option Buttons
-
- To select among option buttons:
-
-
- 1. Press the TAB key to move the cursor to the set of option buttons.
-
- 2. Use the direction keys to move the cursor between the buttons.
-
- When you select a button, a circle appears inside the parentheses.
-
-
-
- Selecting an Option Button with a Mouse
-
- To select an option button with a mouse:
-
-
- 1. Place the mouse pointer on the option button.
-
- 2. Click the left mouse button.
-
- A circle appears inside the parentheses.
-
-
-
- Command Buttons
-
- Command buttons appear at the bottom of a dialog box as angle brackets with
- commands in them. These buttons perform an action, such as taking you to
- another dialog box.
-
- When a dialog box appears on your screen, it already has one command button
- highlighted. This is the default command button.
-
- ────────────────────────────────────────────────────────────────────────────
- NOTE
- To choose the default command button, press the ENTER key at any time while
- the dialog box is displayed. You do not have to move the cursor to the
- default command button before pressing the ENTER key.
- ────────────────────────────────────────────────────────────────────────────
-
- The OK command button tells SAF that you want the actions specified in the
- dialog box to take effect. This button often appears with the Cancel command
- button. The Cancel command button exits a dialog box without saving any
- changes made or executing any actions specified. You can also press the ESC
- key to exit a dialog box without saving changes or executing actions.
-
-
- Using Command Buttons
-
- To choose a command button:
-
-
- 1. Press the TAB key to move the cursor to a command button.
-
- The angle brackets around the button are highlighted.
-
- 2. Press the ENTER key.
-
- The associated action occurs.
-
-
-
- Using Command Buttons with a Mouse
-
- To choose a command button with a mouse:
-
-
- 1. Move the mouse pointer to the command button.
-
- 2. Click the left mouse button.
-
- The associated action occurs.
-
-
-
- Display Fields
-
- A display field displays information. You cannot modify the contents of a
- display field.
-
- You can distinguish a display field from other areas in the dialog box
- because the cursor will not move to a display field when you press the TAB
- key.
-
-
- Getting Help
-
- Help on keyboard movement and on complicated administrative procedures is
- available in the SAF.
-
- To get help on the keyboard:
-
-
- 1. Press the ALT+H keys to select the Help menu.
-
- 2. Press K to choose Keyboard.
-
- A list of keys with their descriptions appears.
-
- 3. To exit the "Keyboard" screen, choose Done.
-
-
- To get help on system administration tasks:
-
-
- 1. Press the ALT+H keys to select the Help menu.
-
- 2. Press C to choose Contents.
-
- A "Contents" screen appears. This screen lists all the system
- administration topics on which help is available.
-
- 3. Select the topic on which you want information.
-
- 4. Press ENTER to choose the topic.
-
- A screenful of information appears. Use the PG DN key to continue
- reading about the topic.
-
- 5. When you have finished reading about the topic, choose Done.
-
-
-
- Exiting the SAF
-
- To exit the SAF:
-
-
- 1. Clear any dialog boxes on the screen by pressing the ESC key.
-
- 2. Press the F3 key.
-
- The following dialog box appears:
-
- (This figure may be found in the printed book.)
-
- Press ENTER to exit from the SAF.
-
-
- You can also exit the SAF from the File menu:
-
-
- 1. Press the ALT+F keys to select the File menu.
-
- 2. Press X to choose Exit.
-
- The exit dialog box shown in Figure 2.13 is displayed.
-
- 3. Press ENTER to exit from the SAF.
-
- The SAF screen disappears, and you are back at the operating system
- prompt.
-
-
-
-
-
-
-
- Chapter 3 Making Queries with the SAF
- ────────────────────────────────────────────────────────────────────────────
-
-
- Introduction
-
- This chapter teaches you to use the SAF to make SQL queries and to view the
- results of these queries. Use this chapter as preparation for SQL Server
- Learning TRANSACT-SQL, which describes SQL queries in detail and provides
- many examples for you to try. This chapter does not explain the intricacies
- of developing SQL queries; instead, it shows you how to use the SAF menus to
-
-
-
- ■ Create SQL queries
-
- ■ Execute queries
-
- ■ View the results of queries
-
- ■ Modify existing queries
-
- ■ Print queries and results
-
-
- This chapter also teaches you how to use the SAF to
-
-
- ■ Create a query log
-
- ■ Log in to another server
-
-
- This chapter describes only the SAF functions that are available to all
- users.
-
-
- About the Examples
-
- The pubs sample database, used throughout this manual, includes eight
- tables. One of these tables, the publishers table, is used for all examples
- in this chapter. Table 3.1 shows the publishers table.
-
- Table 3.1 Publishers Table
-
- pub_id pub_name city state
- ────────────────────────────────────────────────────────────────────────────
- 1389 Algodata Infosystems Berkeley CA
- 0736 New Age Books Boston MA
- 9877 Binnet & Harley Washington DC
- ────────────────────────────────────────────────────────────────────────────
-
- This table contains four columns:
-
- Column Name Description
- ────────────────────────────────────────────────────────────────────────────
- pub_id Publisher's ID number
- pub_name Publisher's name
- city Publisher's city
- state Publisher's state
- ────────────────────────────────────────────────────────────────────────────
-
-
- Queries and Results
-
- This section contains a brief introduction to SQL queries. Its purpose is to
- get you familiar with the SAF using some very simple examples. As you learn
- more about SQL queries in SQL Server Learning TRANSACT-SQL, you will use the
- SAF extensively.
-
-
- Queries
-
- A query includes one or more SQL statements. These statements identify the
- data to be retrieved from an SQL Server database. After a query is executed,
- this data is retrieved from the database and returned to your workstation.
-
- Use the SELECT statement to make queries. The SELECT statement has the
- following syntax:
-
- SELECT select_list FROM table_list
-
- where
-
-
- ■ select_list includes the names of columns from which data is selected.
- In the publishers table, the column names are pub_id, pub_name, city,
- and state.
-
- ■ table_list includes one or more table names. The examples in this
- chapter select data from only one table─the publishers table.
-
-
- For example, to query the pubs database to find publishers' IDs and names,
- the SELECT statement looks like this:
-
- select pub_id, pub_name
- from publishers
-
- Note that the statement can be typed on one line or broken into multiple
- lines. The examples in this manual use multiple lines for readability.
-
-
- Results
-
- Results include the data you receive after you execute your query. The
- results from your queries are presented in table form. The results from the
- previous query are as follows:
-
- pub_id pub_name
- ------ --------------------------
- 0736 New Age Books
- 0877 Binnet & Hardley
- 1389 Algodata Infosystems
-
-
- The Window Menu
-
- You will use the Window menu frequently as you create queries and look at
- results. The following three windows are available through the Window menu:
-
-
-
- ■ SQL Query
-
- ■ SQL Results
-
- ■ SQL Results Full
-
-
- Only one of these windows is "active" at a time. The active window has a
- cursor in it. You shift back and forth between these windows frequently as
- you develop queries and look at results. While using the SAF, you should
- know which window is active because only the active window can be edited,
- saved to a file, or printed.
-
-
- Creating Queries
-
- This section describes how to create queries using the SQL Query Window.
-
-
- Entering Queries
-
- After you log in to SQL Server through the SAF, the SQL Query Window is the
- first screen to appear. You can then start typing in your query. To correct
- typing mistakes, use these keys:
-
- Key Purpose
- ────────────────────────────────────────────────────────────────────────────
- BACKSPACE Deletes the character to the left of the
- cursor.
-
- DEL Deletes the character above the cursor.
-
- CTRL+O Switches between insert mode, where
- characters are added as they are typed,
- and overtype mode, where new characters
- replace existing characters.
-
- ────────────────────────────────────────────────────────────────────────────
-
-
- As a sample, try typing this query:
-
- (This figure may be found in the printed book.)
-
-
- Scrolling
-
- Scrolling is the process of moving text through the window. To scroll
- through text, use these keys:
-
- ╓┌─────────────────────┌─────────────────────────────────────────────────────╖
- Key Movement
- ────────────────────────────────────────────────────────────────────────────
- PG UP Up one screen
- PG DN Down one screen
- CTRL+HOME To the top of the screen
- CTRL+END To the bottom of the screen
- HOME To the beginning of the line
- END To the end of the line
- ────────────────────────────────────────────────────────────────────────────
-
-
-
- Scrolling with a Mouse
-
- The SQL windows contain vertical and horizontal scroll bars and scroll
- boxes:
-
- (This figure may be found in the printed book.)
-
- To scroll through text with a mouse:
-
-
- 1. Move the mouse pointer to the scroll bar.
-
- This scroll bar controls what you see in the window.
-
- 2. Place the mouse pointer over the scroll box in the scroll bar. The
- scroll box represents your current location in the window. Drag the
- scroll box up or down the vertical scroll bar, or left or right in the
- horizontal scroll bar.
-
- 3. Drag the scroll box to a location in the scroll bar that roughly
- corresponds to the location in the window that you want to bring into
- view.
-
- 4. Release the left mouse button.
-
- The view in the window changes.
-
-
-
- Selecting and Deleting Text
-
- Selecting text is the process of highlighting text for use in editing
- commands. You can select characters, words, or lines.
-
- To select text:
-
-
- 1. Use the direction keys to move to the text you want to select.
-
- 2. Press the appropriate keys to select the amount of text you want:
- ╓┌────────────────────────────────┌──────────────────────────────────────────╖
- Key Selection
- Key Selection
- ────────────────────────────────────────────────────────────────────────────
- SHIFT+LEFT direction key Character to the left of the cursor
- SHIFT+RIGHT direction key Character to the right of the cursor
- SHIFT+CTRL+LEFT direction key Word to the left of the cursor
- SHIFT+CTRL+RIGHT direction key Word to the right of the cursor
- SHIFT+UP direction key Previous line
- SHIFT+DOWN direction key Next line
- ────────────────────────────────────────────────────────────────────────────
-
-
-
-
-
- For example, you selected pub_id, pub_name, and city from the publishers
- table:
-
- select pub_id, pub_name, city
- from publishers
-
- To select only city and delete pub_id and pub_name from this query:
-
-
- 1. Move the cursor to the first letter in pub_id.
-
- 2. Press and hold down the SHIFT key. Press the RIGHT direction key until
- pub_id, pub_name is highlighted as follows:
-
- (This figure may be found in the printed book.)
-
- 3. Press the DEL key.
-
-
- If no text is selected, the DEL key deletes the current character. To delete
- a line of text, move the cursor to the line to be deleted and press CTRL+D.
-
-
-
- Selecting Text with the Mouse
-
- To select text with the mouse, point to the starting place for the selection
- and click the left mouse button. Drag the mouse pointer to the end of the
- text you want to select. Release the left mouse button.
-
-
- Executing Queries
-
- Once you have created a query and made typing corrections, you are ready to
- execute the query. When you execute your query, it is sent to the database,
- and you receive results from the database.
-
- To execute your query, from the Query menu, choose Execute query or press
- CTRL+E.
-
-
- Viewing the Results of Queries
-
- After executing your query, the results are displayed on the bottom half of
- your screen. The query and results look like this:
-
- (This figure may be found in the printed book.)
-
-
- Viewing the Query and Results on Separate Screens
-
- To view a full screen of results, choose SQL results full from the Window
- menu or press CTRL+F. The SQL Results Full Window occupies the full screen
- as follows:
-
- (This figure may be found in the printed book.)
-
-
- Scrolling the Results Window
-
- Both the SQL Results Window and the SQL Results Full Window are scrollable:
- they allow you to see all of the data returned by SQL Server, no matter how
- large that data is. If the results of your query are wider than the screen,
- you can scroll horizontally to view all of the text in the returned columns.
- If the results are longer than your screen, you can scroll vertically to
- view all of the text in the returned rows.
-
- It is possible for the results of your query to contain more rows than will
- fit within the available memory on your workstation. In this case, use the
- DOWN or PG DN keys to move to the last row retrieved. This moves you to the
- end of the data that fits in memory. From this point on, every time you
- press DOWN (or PG DN), the SAF reads another row (or screenful) of results
- from the SQL Server. For each 20 rows you read, SAF discards 20 rows from
- the top of the results. These rows are lost; you must reexecute the query to
- recover them. You can continue scrolling down through the results until you
- have viewed all of the remaining rows. Pressing CTRL+END causes the SAF to
- retrieve all remaining rows, discarding rows from the top as necessary.
-
- If you move the cursor out of the SQL Results Window before you have viewed
- all of the results, the SAF discards all of the unread rows. Again, you must
- reexecute the query to view the discarded rows.
-
-
- Alternating between Different Windows
-
- There are several different ways to switch back and forth among the SQL
- Query, SQL Results, and SQL Results Full windows:
-
-
- ■ Using the Window menu
-
- ■ Using the accelerator keys
-
- ■ Using the F6 key
-
- ■ Using the mouse
-
-
-
- Accelerator Keys
-
- To move from one window to another, use the following accelerator keys:
-
- Key Action
- ────────────────────────────────────────────────────────────────────────────
- CTRL+Q Displays the SQL Query Window
-
- CTRL+R Displays the SQL Results Window (half
- query and half results)
-
- CTRL+F Displays the SQL Results Full Window
-
- CTRL+W Shifts back and forth between the two
- halves of the SQL Results Window
-
- ────────────────────────────────────────────────────────────────────────────
-
-
-
- F6 Function Key
-
- The easiest way to alternate between the SQL Query, SQL Results, and SQL
- Results Full windows is to use the F6 function key. This key moves from one
- window to the next in the following order:
-
- (This figure may be found in the printed book.)
-
-
- Modifying Previous Queries and Results
-
- After making a query, you will often want to make changes to the query or
- results. If you have not cleared the windows, you can modify the query or
- results. To change the query or results:
-
-
- 1. For a query, make the SQL Query Window the active window. For results,
- make the SQL Results Window the active window.
-
- (You can select either the SQL Results Window or the SQL Results Full
- Window.)
-
- 2. Make editing changes.
-
-
-
- Making a New Query
-
- To clear the SQL Query and SQL Results windows and make a new query:
-
-
- 1. From the Query menu, choose Next query or press CTRL+N.
-
- The SQL Query Window appears.
-
- 2. Start typing your new query. (See "Creating Queries," earlier in this
- chapter, for details).
-
-
-
- Saving Queries and Results
-
- You may want to save a query or its results in a file. Once you've saved a
- query to a file, you can rerun it easily using the SAF.
-
-
- Filenames for Query and Results Files
-
- Although not required, it is convenient to use the following filename
- extensions for your query and results files:
-
- Extension Type of File Example
- ────────────────────────────────────────────────────────────────────────────
- QRY Query PUBDATA.QRY
- RES Results ADDRESS.RES
-
- ────────────────────────────────────────────────────────────────────────────
-
-
- Using these extensions is helpful when you retrieve one of the files using
- the "Open Filename" dialog box.
-
-
- Saving Queries or Results to a File
-
- To save a query or results to a file:
-
-
- 1. For a query, make the SQL Query Window the active window. For results,
- make the SQL Results Window the active window.
-
- 2. From the File menu, choose Save as.
-
- A dialog box appears:
-
- (This figure may be found in the printed book.)
-
- 3. Type the filename in the text box.
-
- You can type either a complete pathname or a filename only. (If you
- type a filename only, your file is saved in the current directory.)
- Notice that the complete pathname of the saved query file replaces the
- word "untitled" in the screen header.
-
- (This figure may be found in the printed book.)
-
- ────────────────────────────────────────────────────────────────────────────
- NOTE
-
- The SAF imposes a 511 line limit on input query files. You can save a query
- with more than 511 lines to a file, but you cannot execute it from the
- SAF.─────────────────────────────────────────────────────────────────────────
-
-
-
-
- Working with Saved Queries and Results
-
- To open a saved query or results file:
-
-
- 1. For a query, make the SQL Query Window the active window. For results,
- make the SQL Results Window the active window.
-
- NOTE When you open a file, the SQL Query and the SQL Results windows
- are cleared of all text. If you want to save your latest query or
- results, do so before opening a new file.
-
- 2. From the File menu, choose Open.
-
- A message appears:
-
- OK to clear active window?
-
- 3. Choose OK to clear the active window.
-
- A dialog box appears:
-
- (This figure may be found in the printed book.)
-
- 4. Select the file you want to open from the list box, or type the name
- of the file if it does not appear in the list box.
-
- Filenames in the current directory that have an extension of .QRY or
- .RES are displayed in the "Choose" list box.
-
- If the file you want to open is not in the current directory, type the
- complete pathname or the directory name in the text box. A new list
- box full of filenames appears.
-
- 5. Choose OK.
-
- The file you opened appears in the SQL Query or SQL Results window.
-
-
- You can make changes to this file, execute it (if it is a query file), save
- it, or print it.
-
-
- Printing Queries and Results
-
- To print a query or its results:
-
-
- 1. For a query, make the SQL Query Window the active window. For results,
- make the SQL Results Window the active window.
-
- 2. From the File menu, choose Print.
-
- A dialog box appears and printing starts:
-
- (This figure may be found in the printed book.)
-
- 3. To cancel printing, choose Cancel.
-
-
- Your query or results are automatically printed on LPT1. Or you can change
- the default printer to LPT2, your other option:
-
-
- 1. From the File menu, choose Change printer.
-
- A dialog box appears:
-
- (This figure may be found in the printed book.)
-
- 2. Select "LPT2" from the list box.
-
- 3. Choose OK.
-
-
-
- Logging Queries and Results to a File
-
- A query log is a file that stores all your queries and results in
- chronological order. Each new query or result is added to the end of this
- file until you choose End query log from the Query menu. The query log is a
- standard ASCII file and can be accessed with a text editor.
-
- To start your log:
-
-
- 1. From the Query menu, choose Begin query log.
-
- A dialog box appears:
-
- (This figure may be found in the printed book.)
-
- 2. Select the file you want to open from the list box, or type the name
- of the file if it does not appear in the list box.
-
- Filenames in the current directory that have an extension of .LOG are
- displayed in the list box.
-
- If the log file is located in another directory, type the name of the
- directory in the "Open Filename" text box. Once you have typed the
- name of the directory, the files in the list box will change and you
- can select a file.
-
- (To continue using an existing log file, select the name of the
- existing file and press ENTER. Your queries and results will then be
- added to the end of the existing file.)
-
- 3. Choose OK.
-
-
- From this point until the time you end logging, the Query menu displays End
- query log rather than Begin query log.
-
- To stop logging:
-
-
- ■ Choose End query log from the Query menu.
-
-
-
- Logging In to Another Server
-
- To log in to a different server:
-
-
- 1. From the Config menu, choose Login.
-
- A message appears:
-
- (This figure may be found in the printed book.)
-
- Before you can log in to a different server, you have to log out of
- your current server.
-
- 2. Choose OK.
-
- A dialog box appears:
-
- (This figure may be found in the printed book.)
-
- 3. Select a server from the list box.
-
- 4. Type your login ID and password for this server.
-
- 5. Choose OK.
-
- You are logged in to the server you specified.
-
-
-
-
-
-
-
- Chapter 4 Starting and Shutting Down SQL Server
- ────────────────────────────────────────────────────────────────────────────
-
-
- Introduction
-
- There are several ways to start and to shut down the SQL Server.
-
- To start SQL Server, you can use any of the following:
-
-
- ■ The SAF
-
- ■ The net command
-
- ■ The sqlservr program
-
-
- To shut down SQL Server, you can use any of the following:
-
-
- ■ The SAF Config menu
-
- ■ The net command
-
- ■ The SHUTDOWN statement
-
-
- The method you use depends on the network software you are running.
-
-
- ■ If your network is a Microsoft LAN Manager for MS OS/2 or an IBM(R)
- LAN Server, use the SAF or the net command.
-
- ■ If you are using a network other than LAN Manager for MS OS/2 or IBM
- LAN Server, use the sqlservr program or the SHUTDOWN statement.
-
-
-
- Starting SQL Server
-
- This section describes two of the ways to start SQL Server:
-
-
- ■ Using the SAF (MS OS/2 only)
-
- ■ Using the net command
-
-
-
- Starting SQL Server Using the SAF (MS OS/2 Only)
-
- To start SQL Server using the SAF (under MS OS/2 only):
-
-
- 1. At the C > prompt, type
-
- saf
-
-
- The copyright screen appears.
-
- 2. Choose OK.
-
- The "Login to SQL Server" dialog box appears.
-
- 3. From the "Server names" list box, select the name of the server you
- want to start. If the server is not visible, it will not appear in the
- list box. In that case, type it into the text box.
-
- 4. Press the TAB key to move the cursor to the "Login ID" text box, and
- type your login ID.
-
- 5. Press the TAB key to move to the "Password" text box, and type your
- password.
-
- 6. Press the ENTER key.
-
- The "Start a Server" dialog box appears.
-
- 7. Choose OK to start the server.
-
-
-
- Starting SQL Server Using the net Command
-
- To start SQL Server using the net command provided with your network
- software:
-
-
- 1. At the C > prompt, type
-
- net start sqlserver
-
-
- 2. Press the ENTER key.
-
-
-
- Shutting Down SQL Server
-
- This section describes three ways to shut down SQL Server:
-
-
- ■ Using the SAF Config menu
-
- ■ Using the SHUTDOWN statement
-
- ■ Using the net command.
-
-
-
- Shutting Down SQL Server Using the Config Menu
-
- To shut down SQL Server from the SAF Config menu:
-
-
- 1. Select the Config menu, and choose Shutdown SQL Server.
-
- A dialog box appears.
-
- 2. Choose OK.
-
- SQL Server then waits for currently executing SQL statements or stored
- procedures to finish, performs a checkpoint in every database, and
- then shuts down the server to which you are logged in. (You can shut
- down SQL Server from a workstation.)
-
-
-
- Shutting Down SQL Server Using the SHUTDOWN Statement
-
- To shut down SQL Server with the SHUTDOWN statement:
-
-
- 1. In the SQL Query Window, type
-
- shutdown
-
-
- 2. Execute this statement by pressing CTRL+E.
-
- SQL Server then waits for currently executing SQL statements or stored
- procedures to finish, performs a checkpoint in every database, and
- then shuts down the server to which you are logged in. (You can shut
- down SQL Server from a workstation.)
-
-
- For more information on the SHUTDOWN statement, see the SQL Server Language
- Reference.
-
-
- Shutting Down SQL Server Using the net Command
-
- To shut down SQL Server immediately, use the net command provided with your
- network software.
-
- ────────────────────────────────────────────────────────────────────────────
- WARNING
-
- Use this command only if you want to shut down SQL Server immediately
- without waiting for active statements to complete, and without performing
- checkpoints. Restarting the database will take longer if checkpoints are not
- performed, although full transaction integrity is guaranteed in either case.
- ────────────────────────────────────────────────────────────────────────────
-
- To use the net command:
-
-
- 1. At the C > prompt, type
-
- net stop sqlserver
-
-
- 2. Press the ENTER key.
-
-
-
-
-
-
-
- Chapter 5 Managing Storage
- ────────────────────────────────────────────────────────────────────────────
-
-
- Introduction
-
- In SQL Server, you create files in which databases and database backups will
- be stored. Once these files (called database devices and dump devices) are
- created, you can then create databases, add data to databases, and back up
- databases.
-
- This chapter describes how to
-
-
- ■ Add database devices and dump devices
-
- ■ Create databases and transaction logs
-
- ■ Drop databases
-
- ■ Drop database devices and dump devices
-
-
- In many organizations, the SA retains complete control over these tasks.
-
-
- Dumping the master Database
-
- You should dump the master database at the following times:
-
-
- ■ After you add a database device or a dump device
-
- ■ After you create a database and a transaction log
-
- ■ After you drop a database
-
- ■ After you drop a database device or a dump device
-
-
-
- Adding Database Devices and Dump Devices
-
- Immediately after installation, SQL Server includes one database device and
- three dump devices. As you create databases on SQL Server, you will need to
- add and monitor database devices and dump devices. This section describes
- how to
-
-
- ■ Add database devices
-
- ■ Set up a pool of default database devices
-
- ■ Add dump devices
-
- ■ Display information on database devices and dump devices
-
-
-
- Database Devices and Dump Devices
-
- SQL Server databases and transaction logs are stored in hard disk files
- called database devices. You cannot create a database until you have created
- a database device to store that database.
-
- Many databases can be contained within a single database device. Also, one
- database can be stored in several database devices.
-
- SQL Server database backups (dumps) can be stored in diskette files or hard
- disk files. These backup files are called dump devices.
-
- Each database device and dump device has two names: a physical name and a
- logical name. The physical name is the name of the MS OS/2 file. The
- physical name follows the MS OS/2 rules for filenames and must include a
- complete pathname.
-
- The logical name is a name used by SQL Server for the database device or
- dump device. When using most SQL statements, you refer to the database
- device or dump device by its logical name. The logical name follows the SQL
- Server rules for identifiers. (See the SQL Server Language Reference for
- these rules.)
-
- Examples of physical and logical names are:
-
- Type of File Physical Name Logical Name
- ────────────────────────────────────────────────────────────────────────────
- Database device c:\sql\data\cust.dat customer_list
- Database device d:\sql\data\reserve.dat reservations
- Dump device a:\sqltable.dat diskettedumpa
- Dump device b:\sqltable.dat diskettedumpb
- ────────────────────────────────────────────────────────────────────────────
-
-
- Adding Database Devices
-
- You add new database devices with the DISK INIT statement. The DISK INIT
- statement gives the database device a physical and logical name and prepares
- the database device for database storage.
-
- Before you add a database device with the DISK INIT statement, you must
- obtain a device number for the database device. You do this by executing the
- sp_helpdevice system procedure. After executing sp_helpdevice, locate the
- highest number in the device_number column. Choose the next number as the
- device number for the database device you are about to create.
-
- The DISK INIT statement has the following syntax:
-
- DISK INIT
- NAME = "logical_name" ,
- PHYSNAME = "physical_name" ,
- VDEVNO = virtual_device_number ,
- SIZE = number_of_blocks
- [, VSTART = virtual_address ,
- CNTRLTYPE = controller_number ]
-
- The following list describes each keyword:
-
- ────────────────────────────────────────────────────────────────────────────
- NAME
- The logical name of the database device. It is the name used within SQL
- Server. NAME must follow the rules for identifiers (Although names longer
- than 30 characters are allowed, the name will be truncated to 30
- characters.)
-
- PHYSNAME
- The physical name of the database device. PHYSNAME is an MS OS/2 filename
- that includes a complete path.
-
- VDEVNO
- An identifying number for the database device. It must be unique among
- database devices and dump devices used by SQL Server. The device number 0
- is reserved for the master database device. Legal numbers are between 1
- and 9.
-
- SIZE
- The size of the database device in 2 kilobyte (K) blocks. There are 512 2K
- blocks in a megabyte.
-
- If you are planning to use the new database device for the creation of a
- new database, the minimum size is the size of model, 1024 2K blocks (2
- megabytes).
-
- If you are adding a database device for a transaction log, SIZE can be as
- small as 512 2K blocks (1 megabyte).
-
- VSTART
- The starting virtual address, or the offset in 2K blocks, for SQL Server
- to begin using the database device. The default value (and usually the
- preferred value) of VSTART is zero.
-
- CNTRLTYPE
- The disk controller. Its default value is zero. Reset it only if
- instructed to do so.
-
- ────────────────────────────────────────────────────────────────────────────
- The following example shows the DISK INIT statement used to add a database
- device with a logical name of employees, a physical name of
- c:\sql\data\mp1.dat, a device number of 8, and a size of 10240K (or 5120 2K
- blocks). (To find the correct device number, you would execute sp_helpdevice
- before executing the DISK INIT statement.)
-
- disk init
- name = "employees",
- physname = "c:\sql\data\mp1.dat",
- vdevno = 8,
- size = 5120
-
- The DISK INIT statement prepares devices for use by SQL Server. It divides
- the database devices into allocation units, each of which is 256 2K pages (a
- total of one-half megabyte). The minimum amount of storage space that can be
- assigned to a database is the size of the model database, which is four
- allocation units (2 megabytes).
-
- In each allocation unit, the DISK INIT statement initializes the first of
- the 256 pages as the allocation page, which will contain information about
- the database (if any) that resides on the allocation unit. The DISK INIT
- statement also clears all pages.
-
- ────────────────────────────────────────────────────────────────────────────
- WARNING
-
- You should dump the master database after you add one or more database
- devices.
- ────────────────────────────────────────────────────────────────────────────
-
-
- Setting Up Default Database Devices
-
- The SA often sets up a pool of default database devices, which is then
- available whenever a database is created.
-
- To add a database device to (or remove it from) the pool of default database
- devices, execute the sp_diskdefault system procedure. The sp_diskdefault
- system procedure has the following syntax:
-
- sp_diskdefault "database_device", {defaulton | defaultoff}
-
- ────────────────────────────────────────────────────────────────────────────
- database_device
- The logical name of the database device. Use the sp_helpdevice system
- procedure, if necessary, to find the logical name.
-
- defaulton, defaultoff
- Use defaulton if the specified database device is to be designated a
- default database device. Use defaultoff if the specified database device
- is not to be designated a default database device. The defaulton option
- will most frequently be used after a database device has been added to the
- system with DISK INIT. The defaultoff option will most frequently be used
- to change the default status of the master database device (which is on
- when SQL Server is first installed).
-
- ────────────────────────────────────────────────────────────────────────────
- For example, the following example shows the new database device employees
- added to the pool of default database devices:
-
- sp_diskdefault "employees", defaulton
-
- The following example shows how to remove the newdb database device from the
- pool of default database devices:
-
- sp_diskdefault "newdb", defaultoff
-
- It is a good idea to put a database and its transaction log into separate
- database devices. (See "Putting the Transaction Log into a Different
- Database Device," later in this chapter.)
-
-
- Adding Dump Devices
-
- To add dump devices other than those already supplied with SQL Server, use
- the sp_addumpdevice system procedure. This procedure has the following
- syntax:
-
- sp_addumpdevice {"disk" | "diskette"}, "logical_name",
- "physical_name", cntrltype [, noskip | skip [, media_capacity]]
-
- ────────────────────────────────────────────────────────────────────────────
- "disk","diskette"
- The type of dump device. Use "disk" for adding a hard disk file as a dump
- device. Use "diskette" for adding a 5.25 inch or 3.5 inch diskette file as
- a dump device.
-
- logical_name
- The logical name of the dump device. This name must follow the rules for
- identifiers. (If you specify a name longer than 30 characters, the name is
- truncated to 30 characters.)
-
- physical_name
- The physical name of the dump device. This name must follow the rules for
- MS OS/2 filenames and must include a full pathname.
-
- cntrltype
- The controller number of the new dump device. The same controller number
- can be used for more than one dump device. For hard disk dump devices, the
- controller number must be 2. For diskette dump devices, the controller
- number must be 3 or 4. If there are two diskette dump devices, use
- controller number 3 for one and controller number 4 for the other.
-
- noskip, skip
- Indicates whether ANSI tape labels are read (noskip) or ignored (skip).
- Use noskip for diskette dump devices. (The skip option is reserved for
- future tape support.)
-
- media_capacity
- The storage capacity of the diskette (in megabytes). The default is 1.2
- megabytes. Use this parameter only for adding a diskette dump device. If
- you specify media_capacity, you must also specify the noskip option.
-
- ────────────────────────────────────────────────────────────────────────────
- For example, to add a diskette dump device with a capacity of 360K, execute
- the following statement:
-
- sp_addumpdevice "diskette", "diskettedumpb",
- "b:\sqldump.dat", 4, noskip, .36
-
- There are several special logical names for dump devices. The dump device
- known as diskdump sends dumped data to the null device. Using the name
- diskdump will dump data without putting it anywhere. Some installations use
- the diskdump name as a "bit bucket."
-
- If you add a dump device with a physical name of null and any logical name,
- the dump device will be added. However, its physical name will be changed to
- nul and its logical name will be changed to diskdump.
-
- ────────────────────────────────────────────────────────────────────────────
- WARNING
-
- You should dump the master database after you add a dump device.
- ────────────────────────────────────────────────────────────────────────────
-
-
- Displaying Information on Database Devices and Dump Devices
-
- Use the sp_helpdevice system procedure to display information about database
- devices and dump devices.
-
- The following information is displayed when you execute sp_helpdevice:
-
- sp_helpdevice
-
- device_name physical_name
- description
- status cntrltype device_number low high
- --------------- -----------------------------
- ------------------------------
- ----------- ------------- ------------- ----- ------
- diskdump nul
- disk dump device
- 16 2 0 0 20000
- diskettedumpa a:sqltable.dat
- diskette, 1.2 Mb, dump device
- 16 3 0 0 19
- diskettedumpb b:sqltable.dat
- diskette, 1.2 Mb, dump device
- 16 4 0 0 19
- master c:\sql\data\master.dat
- special, default disk, physical disk, 10 Mb
- 3 0 0 0 5119
-
- (4 rows affected)
-
- The report contains the following fields:
-
- ────────────────────────────────────────────────────────────────────────────
- device_name
- The logical name of a database device or dump device.
-
- physical_name
- The physical name of a database device or dump device.
-
- description
- The type of database device or dump device (disk or diskette).
-
- status
- The type of device:
-
- 2 Database device
-
- 3 Default database device
-
- 16 Dump device (either disk or diskette)
-
- cntrltype
- The controller type:
-
- 0 Database device
-
- 2 Disk dump device
-
- 3-4 Diskette dump device
-
- device_number
- The virtual device number. All database devices and dump devices have a
- unique number.
-
- low
- The first virtual page number for a database device. For a dump device,
- the low value is always 0.
-
- high
- The last virtual page number for a database device. For a dump device, the
- high value equals the media capacity specified when the device was
- created. The high value shows media capacity in 62K blocks; for example, a
- value of 19 equals 1.2 megabytes (62K * 19).
-
- ────────────────────────────────────────────────────────────────────────────
- Advanced users may want to query the sysdevices system table for additional
- information on database devices and dump devices. See Appendix B, "System
- Tables," for a description of this table.
-
-
- Creating Databases and Transaction Logs
-
- After installation, SQL Server includes these databases: master, tempdb, and
- model. You may also choose to load the example database, pubs.
-
- This section describes how to
-
-
- ■ Create a database and transaction log
-
- ■ Put a transaction log into a separate database device
-
- ■ Expand transaction log space
-
- ■ Alter database size
-
- ■ Display information on database storage
-
-
-
- Creating a Database
-
- Databases are allocated storage space when the CREATE DATABASE or ALTER
- DATABASE statement is executed. In most organizations, only the SA executes
- these statements to prevent inadvertent or unauthorized use of storage
- space. However, the SA can grant permission for these statements to other
- users if desired. (The SA can transfer ownership of a database to another
- user after it is created.)
-
- The CREATE DATABASE statement can specify one or more database devices and
- the amount of space in each that is to be allocated to the new database. If
- no database device or size is specified (or if the keyword DEFAULT is used),
- SQL Server puts the database in one or more of the default database devices
- and assigns it the default size of 2 megabytes. To see which database
- devices are available, execute the sp_helpdevice system procedure. You
- should place a database and its transaction log in separate devices. You
- must do this if the database is larger than 4 megabytes.
-
- ────────────────────────────────────────────────────────────────────────────
- NOTE
-
- The allocation decisions that you make when you execute CREATE DATABASE or
- ALTER DATABASE are important because it is difficult to reclaim storage
- space once it's assigned. If the database runs out of space, additional
- space must be allocated.
- ────────────────────────────────────────────────────────────────────────────
-
- The CREATE DATABASE statement can be executed only while using the master
- database. This statement has the following syntax:
-
- CREATE DATABASE database_name
- [ON {DEFAULT [= size] , database_device [= size]
- [, database_device [= size]]...}]
-
- ────────────────────────────────────────────────────────────────────────────
- database_name
- The name of the new database. It must conform to the rules for
- identifiers.
-
- ON
- Specifies a location and (optionally) a size for the database.
-
- DEFAULT
- Puts the new database in any default database device. To specify a size
- for the database without specifying a location, use "ON DEFAULT = size".
-
- database_device
- The logical name of the database device into which you want to put the
- database. A database can occupy different amounts of space in each of
- several database devices. To see a list of existing logical names, execute
- sp_helpdevice.
-
- size
- The amount of space allocated to the database (in megabytes). The
- SQL-Server-supplied default size is 2 megabytes. The SA can change the
- default size. (See Chapter 9, "Fine-tuning and Performance Operations,"
- for information.) The default size is usually the same size as the model
- database and must be at least as large as the model database. The legal
- values for a database size range from 2 to 223.
-
- ────────────────────────────────────────────────────────────────────────────
- For example, if you want to create a database in default database devices
- with the default database size, type
-
- create database pubs
-
- To specify a size (in this example, 4 megabytes) for a database to be stored
- in a default location, use "ON DEFAULT = size" like this:
-
- create database newpubs
- on default = 4
-
- To specify a different location for the database, give the name of the
- database device in which you want it stored. You can request that a database
- be stored in more than one database device, with different amounts of space
- in each. This statement creates the newdb database and allocates to it 3
- megabytes in the default database device and 2 megabytes in newdata:
-
- create database newdb
- on default = 3, newdata = 2
-
- If the ON clause is omitted, the database is created with the default amount
- of space indicated in master..sysconfigures (usually 2 megabytes) on the
- default database device indicated in master..sysdevices. A database can
- range in size from a minimum of 2 megabytes to 223 megabytes.
-
- If the amount of space you request in a specific database device is
- unavailable, SQL Server creates the database with as much space as possible
- on a per-device basis. It then displays a message informing you how much
- space was actually allocated in each database device. (This is not
- considered an error.) If there is less than the minimum space necessary for
- a database (the size of model) in the specified database device (or in the
- default, if you don't give any names), the CREATE DATABASE statement fails.
-
-
- ────────────────────────────────────────────────────────────────────────────
- WARNING
-
- After you execute the CREATE DATABASE statement, you should dump the master
- database. This makes recovery easier and safer in case master is later
- damaged. (See Chapter 8, "Backup and Recovery.")
- ────────────────────────────────────────────────────────────────────────────
-
-
- Putting the Transaction Log into a Different Database Device
-
- SQL Server makes an entry in the transaction log each time a database page
- is modified. The logs of databases in which frequent modifications are made
- can grow to be quite large. You can always allocate more database device
- space for a log, but it is difficult to reclaim space if you allocate too
- much.
-
- You should always assign a database and its transaction log to separate
- database devices. However, for very small databases, the transaction log can
- stay in the same database device that the database itself uses. You cannot
- use the DUMP TRANSACTION statement if the database and the log are on the
- same device. In this situation, all backups must be done with DUMP DATABASE.
-
-
- For databases larger than about 4 megabytes, you should place the
- transaction log in a separate database device for these reasons:
-
-
- ■ To establish a fixed size for the log so that it will not compete with
- other database activity for space
-
- ■ To allow backups to be made with the DUMP TRANSACTION statement,
- saving time and diskettes
-
- ■ To improve performance. The improvement is especially dramatic if the
- database is used heavily
-
-
- You can decide to assign the log to a separate database device when you
- execute the CREATE DATABASE statement, or you can assign it later using
- ALTER DATABASE. Specify at least two database devices in the CREATE DATABASE
- statement, and then use the sp_logdevice system procedure to put the
- database's log into one of them.
-
- The sp_logdevice system procedure has the following syntax:
-
- sp_logdevice dbname, database_device
-
- ────────────────────────────────────────────────────────────────────────────
- dbname
- The name of the database whose transaction log you want to put in a
- specific database device.
-
- database_device
- The logical name of the database device you want to put the transaction
- log into. This database device must be an existing database device.
- Execute sp_helpdevice for a report on existing database devices.
-
- ────────────────────────────────────────────────────────────────────────────
- The first statement in the following example creates a database named
- products and assigns it 10 megabytes in the default database device and
- another 2 megabytes in the database device called logs. The second statement
- executes sp_logdevice and puts the database's transaction log table in the
- logs database device.
-
- create database products on default = 10, logs = 2
- exec sp_logdevice products, logs
-
- Only the Database Owner (in this example, the Database Owner of products)
- can execute the sp_logdevice system procedure.
-
- The size of the device required for the transaction log varies according to
- the amount of update activity and the frequency of transaction log dumps. As
- a rule, allocate to the log 10-25% of the space you allocate to the database
- itself. It is a good idea to start with a small amount of space for the log
- and then increase the size as required. Once you have assigned space to a
- log, you cannot decrease that space.
-
- ────────────────────────────────────────────────────────────────────────────
- WARNING
-
- You should dump the master database after you create a transaction log.
- ────────────────────────────────────────────────────────────────────────────
-
-
- Expanding the Transaction Log Space
-
- It makes sense to increase the amount of space allocated for the transaction
- log only if the log is in a different database device. (If you do not put
- the log into a separate device, the database and the log will compete for
- the same space.)
-
- If the log is in a separate database device, you can increase the amount of
- space allocated to it with the ALTER DATABASE statement. Then reexecute
- sp_logdevice. Here's an example:
-
- create database pubs on default = 10, logs = 2
- sp_logdevice pubs, logs
- alter database pubs on logs = 1
- sp_logdevice pubs, logs
-
- You can also increase the amount of space available to the log by adding a
- new database device. First execute the DISK INIT statement to add the
- device. Use ALTER DATABASE and sp_logdevice as in the preceding example.
-
- The amount of space allocated in the new device becomes part of the space
- available to the log. You can use as many devices per database as you wish,
- within the system limit of the number of database devices that can be added.
-
-
- To increase the amount of storage space available for the rest of the
- database, specify some device other than the log device in the ALTER
- DATABASE statement. You can put the transaction logs of more than one
- database into the same database device.
-
-
- Altering Database Size
-
- If the space allocated for a database is too small, it can be increased with
- the ALTER DATABASE statement. However, you cannot decrease the size of a
- database with the ALTER DATABASE statement. Permission for the ALTER
- DATABASE statement, like the CREATE DATABASE statement, defaults to the SA.
- ALTER DATABASE permission is automatically transferred along with a grant of
- CREATE DATABASE permission by the SA. (For more information on permissions,
- see Chapter 7, "Managing User Permissions.")
-
- The ALTER DATABASE statement is most frequently executed when SQL Server
- returns a message saying that a database has filled all of its allocated
- storage space. The minimum increase is 1 megabyte. The default is a
- 1-megabyte increase in the allocated storage space in a database device. You
- can find names of default devices with sp_helpdevice.
-
- To add 1 megabyte in the default database device for the newpubs database,
- type
-
- alter database newpubs
-
- The full syntax allows you to extend a database by other amounts and to
- specify where storage space is to be added:
-
- ALTER DATABASE database_name
- [ON {DEFAULT | database_device} [= size]
- [, database_device [= size]]...]
-
- ────────────────────────────────────────────────────────────────────────────
- database_name
- The name of the database whose storage size is to be changed.
-
- ON
- A size and/or location for the database extension.
-
- DEFAULT
- Allows ALTER DATABASE to put the database extension into any default
- database device(s). To specify a size for the database extension without
- specifying the location, use "ON DEFAULT = size" (the default size is 1
- megabyte). To change a database device's status to the default, use the
- sp_diskdefault system procedure.
-
- database_device
- The logical name of the database device in which you want to locate the
- database extension. The default size of database_device is 2 megabytes. A
- database can occupy more than one database device with different amounts
- of space on each.
-
- size
- The amount of space allocated to the database extension (in megabytes).
- The minimum extension is 1 megabyte. The default values are 1 megabyte for
- a default database device and 2 megabytes for a nondefault database
- device. Legal values range from 1 to 223.
-
- ────────────────────────────────────────────────────────────────────────────
- To add 3 megabytes to the space allocated for the newpubs database in the
- database device named pubsdata1, type
-
- alter database newpubs
- on pubsdata1 = 3
-
- If SQL Server can't allocate the requested size, it will allocate as much as
- it can in each database device in half-megabyte units, with a minimum
- allocation of 1 megabyte, and report the results.
-
- To add 2 megabytes to the space allocated for newpubs in a default database
- device and 3 megabytes in pubsdata2, type
-
- alter database newpubs
- on default = 2, pubsdata2 = 3
-
- ────────────────────────────────────────────────────────────────────────────
- WARNING
-
- You should dump the master database after you execute the ALTER DATABASE
- statement.
- ────────────────────────────────────────────────────────────────────────────
-
-
- Displaying Information on Database Storage
-
- To find the name of the database device in which a particular database
- resides, use the sp_helpdb system procedure with the database name:
-
- sp_helpdb pubs
-
- name db_size owner dbid created status
- -------- -------- ----- ----- ------------ --------------
- pubs 2 Mb sa 4 Nov 13 1987 no options set
-
- (1 row affected)
-
- device size usage
- ------- ------ ------------------
- master 2 Mb data and log
-
- (1 row affected)
-
- Execute sp_spaceused to get a summary of the storage space used:
-
- sp_spaceused
-
- database_name database_size
- -------------- ---------------
- pubs 2 Mb
-
- (0 rows affected)
-
- reserved data index_size unused
- --------- --------- ---------- -----------
- 832 KB 210 KB 52 KB 570 KB
-
- (0 rows affected)
-
- The sp_spaceused report contains the following fields:
-
- ────────────────────────────────────────────────────────────────────────────
- database_name
- The name of the database whose storage space is being measured.
-
- database_size
- The amount of space allocated to the database by the CREATE DATABASE or
- ALTER DATABASE statement.
-
- reserved
- The amount of space allocated to all the tables and indexes that have been
- created in the database. (Space is allocated to database objects inside a
- database in increments of one extent, or 8 2K pages, at a time.)
-
- data
- The amount of space used by data.
-
- index_size
- The amount of space used by indexes.
-
- unused
- The amount of space that has been allocated but not actually used for data
- by tables and indexes. Adding the values in the unused, index_size, and
- data columns should give you the figure in the reserved column.
-
- ────────────────────────────────────────────────────────────────────────────
- You can also use sp_spaceused with a database object name as its parameter
- and get a report on the space used by that object. For example:
-
- sp_spaceused titles
-
- name rows reserved data index_size unused
- ------ ------ --------- ------ ---------- ------
- titles 18 48 KB 6 KB 4 KB 38 KB
-
- (0 rows affected)
-
- Executing sp_spaceused regularly lets you monitor the amount of database
- space available. For example, if the value of reserved is close to the total
- database_size, you are close to running out of space for new objects. If
- unused is also quite small, you are close to running out of space for
- additional data as well.
-
- It is a good idea to execute sp_spaceused regularly on the syslogs table
- since the transaction log can grow rapidly if there are frequent database
- modifications. This is a particular problem if the transaction log is not in
- a separate device─in which case it will be competing with the rest of the
- database for database space.
-
- You may want to write some of your own queries for additional information
- about physical storage. For example, to determine how much total storage
- space exists on SQL Server, you would query sysdevices:
-
- ╓┌─────────────────┌─────────────────────────────────────────────────────────╖
- ────────────────────────────────────────────────────────────────────────────
- select sum(high - low)
- from sysdevices
- where status in (2, 3)
-
- ------------
- 7168
- (1 row affected)
- ────────────────────────────────────────────────────────────────────────────
- (1 row affected)
-
-
- Advanced users may want to query the sysusages table for additional
- information on login IDs. See Appendix B, "System Tables," for a description
- of this table.
-
-
- How SQL Server Allocates Space for a Database
-
- SQL Server first makes an entry for the new database in sysdatabases. Then
- it checks master..sysdevices to make sure that the database devicenames
- specified in the CREATE DATABASE statement actually exist and are database
- devices. Next it looks through master..sysusages to find space for the new
- database.
-
- The storage space from which SQL Server gathers the specified amount of
- storage need not be contiguous and can be extracted from whatever free space
- is available. The database storage space can even be drawn from more than
- one database device. Of course, a database is treated as a logical whole
- even if it is stored in more than one database device.
-
- Each piece of storage for a database must be at least 1 allocation unit─half
- a megabyte, or 256 contiguous 2K pages. The first of the 256 pages is the
- allocation page. It does not contain database rows like all the other pages.
- Rather, it contains an array that shows how the other 255 pages are used.
-
- The database storage information is listed in the master database table
- sysusages. Each row in master..sysusages represents allocation units
- assigned to some database. Thus, each database has one row in sysusages for
- each piece of noncontiguous storage space assigned to it. Each piece of
- noncontiguous storage assigned to the database can be a different size (a
- different number of allocation units).
-
-
- Dropping Databases
-
- When you drop a database, the database and all its objects are deleted.
- Dropping a database also frees the storage space that had been allocated for
- it and deletes references to it from the system tables in the master
- database.
-
- Only the Database Owner has permission to drop databases. This permission
- cannot be transferred.
-
- The DROP DATABASE statement has the following syntax:
-
- DROP DATABASE database_name [, database_name]...
-
- You can drop more than one database in a single statement. For example:
-
- drop database newpubs, newdb
-
- You must drop all the databases in a database device before you can drop the
- database device. (See the next section, "Dropping Database Devices and Dump
- Devices.")
-
- ────────────────────────────────────────────────────────────────────────────
- WARNING
-
- You should dump the master database after you drop a database.
- ────────────────────────────────────────────────────────────────────────────
-
-
- Dropping Database Devices and Dump Devices
-
- When you drop a database device or dump device, that storage space is freed
- for other use. Permission to drop database devices and dump devices defaults
- to the SA, who can transfer it.
-
- Database devices and dump devices are deleted with the sp_dropdevice system
- procedure. This procedure has the following syntax:
-
- sp_dropdevice logical_name
-
- ────────────────────────────────────────────────────────────────────────────
- WARNING
-
- You should dump the master database after you drop a database device or dump
- device. You must shut down and restart SQL Server after you drop a device.
- For instructions on shutting down and restarting SQL Server, see Chapter 4,
- "Starting and Shutting Down SQL Server."
- ────────────────────────────────────────────────────────────────────────────
-
-
-
-
-
-
- Chapter 6 Managing User Accounts
- ────────────────────────────────────────────────────────────────────────────
-
-
- Introduction
-
- The SA is usually responsible for adding login IDs to SQL Server. Once users
- can log in to SQL Server, Database Owners are usually responsible for adding
- login IDs to the appropriate databases. This chapter describes how to
-
-
- ■ Add login IDs to SQL Server
-
- ■ Add users to a specific database within SQL Server
-
- ■ Combine users into groups within a database
-
- ■ Create aliases for users within a database
-
- ■ Change database ownership
-
- ■ Display information on current users
-
-
-
- Managing Login IDs
-
- To be authorized to work on SQL Server, each user needs a login ID, a
- password, and a default database.
-
- This section describes how to
-
-
- ■ Manage login IDs with the SAF Admin menu
-
- ■ Manage login IDs by executing system procedures
-
- ■ Display information on login IDs
-
-
-
- Login IDs and Passwords
-
- The SA assigns login IDs and passwords when new users are added to SQL
- Server. This login ID and password give the user access to SQL Server but
- not to a specific database.
-
- The default password is NULL (no password). Unless the SA assigns a
- password, the user will have no password.
-
-
- Special Login IDs
-
- There are two special login IDs: sa and probe. The SA uses the sa login ID,
- and the two-phase commit service in DB-LIBRARY uses the probe login ID. Do
- not try to log in using the probe login ID. (See the SQL Server Programmer's
- Reference for more information on probe.)
-
-
- Default Databases
-
- A default database is the database to which the user is connected
- immediately after logging in to SQL Server. For example, if a user's default
- database is pubs, he or she will be connected to the pubs database after
- logging in.
-
- After assigning a default database, make sure that the user is authorized to
- access that database. (See "Managing Database Usernames," later in this
- chapter, for details.) If the user is not authorized to access the default
- database, then master will remain his or her default database (assuming that
- the master database includes the guest username). It's a good idea to assign
- default databases other than master to discourage users from creating
- objects in the master database.
-
-
- Visitor Login IDs
-
- You may want to add a login ID for visiting users (this login ID might be
- called visitor). A password and a default database can be assigned, if
- desired. Typically, visiting users are granted restricted permissions. (See
- Chapter 7, "Managing User Permissions," for information on permissions.)
- Note that the visitor login ID is different from the guest user. (See "Guest
- User," later in this chapter.)
-
-
- Managing Login IDs Using the Admin Menu
-
- The SA can use the Admin menu to add login IDs, passwords, and default
- databases. Only the SA has permission to perform these tasks.
-
-
- Adding a Login ID
-
- To add a login ID and assign a default database:
-
-
- 1. Select the Admin menu and choose Manage login IDs.
-
- The "Manage Login IDs" dialog box appears.
-
- 2. Choose Add.
-
- The "Add a Login ID" dialog box appears.
-
- 3. Complete the following information in the text boxes:
-
- ■ The login ID for the user. The login ID must follow the rules for
- identifiers (see the SQL Server Language Reference) and must be
- unique in SQL Server.
-
- ■ The user's password (enter twice). The password must follow the
- rules for identifiers (see the SQL Server Language Reference). If
- no password is entered, the new user is assigned the NULL password
- (no password) and so does not have to enter a password to log in
- to SQL Server.
-
- ■ The (optional) username. Enter this field only if you want the
- username in the default database to be different from the login
- ID. If you make no entry here, the username will default to the
- login ID. The username must follow the rules for identifiers (see
- the SQL Server Language Reference) and must be unique in SQL
- Server.
-
-
- 4. From the "Default database" text box, select the default database for
- this user.
-
- 5. Choose OK.
-
- A message appears:
-
- New login created.
-
- 6. Choose OK.
-
- A message appears:
-
- New user added.
-
- 7. Choose OK.
-
- The "Manage Login IDs" dialog box appears. The new login ID should
- appear in the "Login ID" list box.
-
- 8. Choose Done.
-
-
-
- Changing a User's Password
-
- To change a password:
-
-
- 1. Select the Admin menu and choose Manage login IDs.
-
- The "Manage Login IDs" dialog box appears.
-
- 2. From the "Login ID" list box, select the login ID of the user whose
- password you want to change.
-
- 3. Choose Change password.
-
- The "Change User Password" dialog box appears.
-
- 4. Enter the new password twice.
-
- The password must follow the rules for identifiers. (See the SQL
- Server Language Reference.)
-
- 5. Choose OK.
-
- A message appears:
-
- Password changed.
-
- 6. Choose OK.
-
- The "Manage Login IDs" dialog box appears.
-
- 7. Choose Done.
-
-
- See "Displaying Information on Login IDs," later in this chapter, for a list
- of SQL Server passwords.
-
-
- Changing a User's Default Database
-
- To change a user's default database:
-
-
- 1. Select the Admin menu and choose Manage login IDs.
-
- The "Manage Login IDs" dialog box appears.
-
- 2. From the "Login ID" list box, select the login ID of the user whose
- default database you want to change.
-
- 3. Choose Change default DB.
-
- The "Change Default Database" dialog box appears.
-
- 4. From the "New default database" list box, select the new default
- database for this user.
-
- 5. Choose OK.
-
- A message appears:
-
- Default database changed.
-
- 6. Choose OK.
-
- The "Manage Login IDs" dialog box appears.
-
- 7. Choose Done.
-
-
-
- Deleting a Login ID
-
- To delete a login ID:
-
-
- 1. Select the Admin menu and choose Manage login IDs.
-
- The "Manage Login IDs" dialog box appears.
-
- 2. From the "Login ID" list box, select the login ID for the user to be
- deleted.
-
- 3. Choose Delete.
-
- A message appears:
-
- Login dropped.
-
- 4. Choose OK.
-
- The "Manage Login IDs" dialog box appears. The deleted login ID should
- not appear in the "Login ID" list box.
-
- 5. Choose Done.
-
-
- After you delete a login ID, the user cannot log in to SQL Server.
-
- ────────────────────────────────────────────────────────────────────────────
- NOTE
-
- Remember to delete the username from all databases associated with the login
- ID you are deleting. (See "Deleting a Username," later in this chapter.)
- ────────────────────────────────────────────────────────────────────────────
-
-
- Managing Login IDs Using System Procedures
-
- You can add login IDs, change a user's password, change a user's default
- database, and delete login IDs using system procedures.
-
-
- Adding a Login ID
-
- To add a login ID, use the sp_addlogin system procedure.
-
- The sp_addlogin system procedure has the following syntax:
-
- sp_addlogin login_id [, password [, defaultdb]]
-
- ────────────────────────────────────────────────────────────────────────────
- login_id
- The user's login ID. Login IDs must follow rules for identifiers and must
- be unique on SQL Server.
-
- password
- The user's password. If no password is given, the default password is NULL
- (no password).
-
- defaultdb
- The name of the user's default database─the database to which the user is
- connected when he or she logs in. If no defaultdb is given, the default is
- master.
-
- ────────────────────────────────────────────────────────────────────────────
- The following statement sets up an account for the user maryd with the
- default password (NULL) and the default database (master).
-
- sp_addlogin "maryd"
-
- Once this statement is executed, maryd can log in to SQL Server. If the
- master database contains a guest user, maryd is automatically treated as a
- guest user in master unless she has been specifically given access to
- master.
-
- The following statement sets up a login ID and a password for user
- omar_khayyam and makes pubs his default database:
-
- sp_addlogin "omar_khayyam", rubaiyat, pubs
-
- If omar_khayyam later decides to change his default database, he can do so
- with the sp_defaultdb system procedure. For information on sp_defaultdb, see
- "Changing a User's Default Database," later in this chapter.
-
- ────────────────────────────────────────────────────────────────────────────
- NOTE
-
- Remember to add the new username to the default database you have just
- assigned. (See "Adding a Username," later in this chapter, for more
- information.)
- ────────────────────────────────────────────────────────────────────────────
-
-
- Changing a User's Password
-
- To change a user's password, use the sp_password system procedure. Any user
- can use sp_password to change his or her own password.
-
- The sp_password system procedure has the following syntax:
-
- sp_password old, new [, login_id]
-
- ────────────────────────────────────────────────────────────────────────────
- old
- The user's old password. To locate existing passwords, see "Displaying
- Information on Login IDs," later in this chapter.
-
- new
- The user's new password.
-
- login_id
- The user's login ID. Only the SA can use this option to change a user's
- password.
-
- ────────────────────────────────────────────────────────────────────────────
- For example, Mary can change her password from the default NULL to pine with
- this statement:
-
- sp_password null, pine
-
- Notice that null and pine are not enclosed in quotes.
-
- If the SA doesn't like Mary's new password, he or she can change it with
- this statement:
-
- sp_password pine, spruce, mary
-
- The password is entered into the master.dbo.syslogins.password field.
- Permission to read this field is denied to all users except the SA.
-
-
- Changing a User's Default Database
-
- To change a user's default database, use the sp_defaultdb system procedure.
- Any user can use sp_defaultdb to change his or her own default database.
-
- The sp_defaultdb system procedure has the following syntax:
-
- sp_defaultdb login_id, defaultdb
-
- ────────────────────────────────────────────────────────────────────────────
- login_id
- The login ID of the user
-
- defaultdb
- The name of the user's default database
-
- ────────────────────────────────────────────────────────────────────────────
- Once the procedure is executed, the user will be connected to the new
- default database the next time he or she logs in.
-
- However, sp_defaultdb does not automatically give the user access to the new
- default database. Unless the Database Owner has set up access with
- sp_adduser, sp_addalias, or with a guest user mechanism, the user is
- connected to master even after his or her default database has been changed.
-
-
- Here's how Omar Khayyam would change his default database to accounting:
-
- sp_defaultdb "omar_khayyam", accounting
-
- The SA could change Omar's default database from accounting to purchasing:
-
- sp_defaultdb "omar_khayyam", purchasing
-
-
- Deleting a Login ID
-
- To delete a login ID, use the sp_droplogin system procedure.
-
- The sp_droplogin system procedure has the following syntax:
-
- sp_droplogin login_id
-
- ────────────────────────────────────────────────────────────────────────────
- login_id
- The user's login ID
-
- ────────────────────────────────────────────────────────────────────────────
- Displaying Information on Login IDs
-
- To see a list of users' login IDs, passwords, and default databases, execute
- this SQL statement from the master database:
-
- select name, password, dbname
- from syslogins
-
- A report similar to the one following appears:
-
- name password dbname
- ----------- ------------ ----------
- sa master
- margaret prx7 pubs
- william bill master
- visitor visitor pubs
-
- (4 rows affected)
-
- The report headings have the following descriptions:
-
- ────────────────────────────────────────────────────────────────────────────
- name
- Login ID
-
- password
- Password (this column appears only if you are logged in as sa)
-
- dbname
- Default database name
-
- ────────────────────────────────────────────────────────────────────────────
- Advanced users may want to query the syslogins system table. See Appendix B,
- "System Tables," for information on the structure of this table.
-
-
- Managing Database Usernames
-
- Users who have been given login IDs on SQL Server still need permission to
- access databases. Permission to access databases is granted by each Database
- Owner.
-
- Users who have been given access to a database still need permission to do
- things inside it: to read data, modify data, and use SQL statements. These
- permissions are set up by the Database Owner or the database object owner.
- They are discussed in Chapter 7, "Managing User Permissions."
-
- This section describes:
-
-
- ■ How to manage usernames with the SAF Admin menu
-
- ■ How to manage usernames by executing system procedures
-
- ■ How to display information on usernames
-
-
-
- Usernames
-
- A username is required for a user to access an SQL Server database. It is
- different from a login ID, which gives the user access to SQL Server but not
- to any user databases.
-
- Usernames are supplied to accommodate users' preferences. For example, if
- there are five SQL Server users named Mary, all of them must have different
- login IDs. Mary Doe might log in as maryd, Mary Jones as maryj, and so on.
- However, if the Marys don't use the same databases, each might prefer to be
- known simply as mary inside a particular database.
-
- Each user may belong to only one group in addition to the public group. (See
- "Managing Database Groups," later in this chapter, for details on groups.)
-
- The only special usernames are dbo for Database Owner and guest for guest
- users.
-
-
- Guest User
-
- A guest username is often set up to allow limited access to a database to
- all SQL Server login IDs. If, for example, Jim does not have a username in
- the doc database, but the doc database has a guest username set up, then Jim
- can use doc. A guest user in a user database allows an owner to extend
- database use to all SQL Server login IDs without adding a username for each
- user. Guests usually have very limited permissions. (See Chapter 7,
- "Managing User Permissions," for details on permissions.)
-
- Initially, guest users inherit the permissions of the public group. The
- Database Owner and database objects owners can change these permissions to
- make the permissions of guest either more restrictive or less restrictive
- than those of public.
-
- When SQL Server is installed, both the master and pubs databases include a
- guest username.
-
- The guest user entry in pubs allows new SQL Server users to follow the
- examples and to engage in a certain amount of experimentation. The guest in
- pubs is given a wide range of permissions.
-
- If you want all new databases to have a guest user, add guest to the model
- database.
-
-
- Managing Usernames Using the Admin Menu
-
- The SA or Database Owner can use the Admin menu to add users, change a
- user's group, and delete users. Only the SA and the Database Owner have
- permission to perform these tasks.
-
-
- Adding a Username
-
- When you add a user to a database, you can optionally specify a groupname.
- If no groupname is specified, the user is made a member of the default
- group, public. The user to be added must have a login ID on the server.
-
- To add a user to a database and assign a groupname:
-
-
- 1. Select the Admin menu and choose Manage usernames.
-
- The "Manage Usernames" dialog box appears.
-
- 2. From the "Database" list box, select the database to which you want to
- add a user.
-
- 3. Choose OK.
-
- The "Manage Usernames" dialog box appears.
-
- 4. Choose Add.
-
- The "Add a Username" dialog box appears.
-
- 5. From the "Login ID" list box, select the name of the user to be added
- to the database.
-
- 6. If you want this user to be a member of a group, select a groupname
- from the "Groupname" dialog box.
-
- 7. In the "Username in database" text box, type the username for this
- person.
-
- If you want the username to be the same as the login ID, leave this
- text box blank.
-
- The username must follow the rules for identifiers. (See the SQL
- Server Language Reference.)
-
- 8. Choose OK.
-
- A message appears:
-
- New user added.
-
- 9. Choose OK.
-
- The "Manage Usernames" dialog box appears. The new username should
- appear in the "Username" list box.
-
- 10. Choose Done.
-
-
-
- Changing a User's Group
-
- Each user can be a member of only one group at a time (in addition to the
- public group). To change a user's group:
-
-
- 1. Select the Admin menu and choose Manage usernames.
-
- The "Manage Usernames" dialog box appears.
-
- 2. From the "Database" list box, select the database in which you want to
- change a group assignment.
-
- 3. Choose OK.
-
- The "Manage Usernames" dialog box appears.
-
- 4. From the "Username" list box, select the name of the user whose group
- you want to change.
-
- 5. Choose Change Group.
-
- The "Change Group" dialog box appears.
-
- 6. In the "New usergroup" list box, select a new group.
-
- 7. Choose OK.
-
- A message appears:
-
- Group changed.
-
- 8. Choose OK.
-
- The "Manage Usernames" dialog box appears.
-
- 9. Choose Done.
-
-
-
- Deleting a Username
-
- You can delete a username from a database unless the user owns objects. To
- delete a user from a database:
-
-
- 1. Select the Admin menu and choose Manage usernames.
-
- The "Manage Usernames" dialog box appears.
-
- 2. From the "Database" list box, select the database from which you want
- to delete a user.
-
- 3. Choose OK.
-
- The "Manage Usernames" dialog box appears.
-
- 4. From the "Username" list box, select the username you want to delete.
-
- 5. Choose Delete.
-
- A message appears:
-
- User has been dropped from current database.
-
- 6. Choose OK.
-
- The "Manage Usernames" dialog box appears. The username you deleted
- should not appear in the "Username" list box.
-
- 7. Choose Done.
-
-
- Before a username is deleted, SQL Server checks the current database to make
- sure the user being deleted does not own any objects or have any aliases.
-
-
- Managing Usernames Using System Procedures
-
- You can add usernames, change a user's group, and delete usernames using
- system procedures.
-
-
- Adding a Username
-
- To add a username to the current database, use the sp_adduser system
- procedure.
-
- The sp_adduser system procedure has the following syntax:
-
- sp_adduser login_id [, username [, grpname]]
-
- ────────────────────────────────────────────────────────────────────────────
- login_id
- The user's login ID.
-
- username
- A name for this user in the current database. Omitting this optional
- parameter causes the username to default to the user's login ID.
-
- grpname
- The name of an existing group in the database. If you don't specify a
- group, the user becomes a member of the default group, public.
-
- ────────────────────────────────────────────────────────────────────────────
- The following statements, executed by the owner of the pubs database, allow
- maryh of the (already existing) engineering group access to pubs:
-
- use pubs
- <execute>
- sp_adduser maryh, mary, eng
-
-
- Changing a User's Group
-
- Users who already have access to the database can be made members of an
- existing group with sp_changegroup. The sp_changegroup system procedure
- changes an existing user's group whether the user is a member of the default
- group, public, or of some other group. At any one time, each user can be a
- member of only one group.
-
- The sp_changegroup system procedure has the following syntax:
-
- sp_changegroup grpname, username
-
- ────────────────────────────────────────────────────────────────────────────
- grpname
- The new groupname. Because PUBLIC is a also keyword, you must specify the
- group public in quotation marks in this context.
-
- username
- The user's name in the current database.
-
- ────────────────────────────────────────────────────────────────────────────
- For example, here's how you'd change Jim to the management group:
-
- sp_changegroup manage, jim
-
- Be careful not to confuse this capability with the alias mechanism, which
- maps the identity and permissions of one user to another. (See "Managing
- Aliases," later in this chapter.)
-
- Groups are used in granting and revoking permissions. Groups are discussed
- in "Managing Database Groups," later in this chapter.
-
-
- Deleting a Username
-
- To delete a username from a database, use the sp_dropuser system procedure.
-
-
- The sp_dropuser system procedure has the following syntax:
-
- sp_dropuser username
-
- ────────────────────────────────────────────────────────────────────────────
- username
- The user's name in the current database
-
- ─────────────────────────────────────────────────────────────────────────────
- WARNING
-
- Do not drop users who own database objects. Before dropping a user, first
- check to see if that user owns any database objects. If the user does own
- database objects, drop the objects or change their ownership before dropping
- the user.
- ────────────────────────────────────────────────────────────────────────────
-
-
- Displaying Information on Usernames
-
- To display a report on database users, use the sp_helpuser system procedure.
-
-
- The sp_helpuser system procedure has the following syntax:
-
- sp_helpuser [username]
-
- ────────────────────────────────────────────────────────────────────────────
- username
- The user's name in the current database. If you don't specify a name, the
- system procedure reports on all users of the current database.
-
- ────────────────────────────────────────────────────────────────────────────
- A sample of a report on all users is shown below:
-
- ╓┌─┌──────────────────┌─────────┌────────────┌────────────┌──────────────────╖
- ────────────────────────────────────────────────────────────────────────────
- ────────────────────────────────────────────────────────────────────────────
- sp_helpuser
-
- Users_name ID_in_db Group_name Login_name Default_db
- ---------- -------- ----------- ----------- ----------
- dbo 1 public sa master
- marcy 4 public marcy pubs
- sandy 3 public sandy pubs
- judy 5 public judy pubs
- linda 6 public linda master
- anne 2 public anne pubs
- jim 7 senioreng jim master
- (7 rows affected)
-
-
- The fields of the report have the following meaning:
-
- ────────────────────────────────────────────────────────────────────────────
- Users_name
- Username
-
- ID_in_db
- ID in database, assigned by SQL Server
-
- Group_name
- Groupname
-
- Login_name
- Login ID
-
- Default_db
- Default database
-
- ────────────────────────────────────────────────────────────────────────────
- Advanced users may want to query the sysusers system table for additional
- information on usernames. See Appendix B, "System Tables," for a description
- of this table.
-
-
- Managing Database Groups
-
- Database groups are made up of several users who all have the same
- permissions. This section describes how to:
-
-
- ■ Manage groups with the SAF Admin menu
-
- ■ Manage groups by executing system procedures
-
- ■ Display information on groups
-
-
-
- Groups
-
- Groups are used as a collective name for granting and revoking permissions;
- they provide a convenient way to grant or revoke permissions to more than
- one user in a single statement. Every SQL Server user always belongs to the
- public group. In addition, every user may belong to one additional group.
-
-
- Public Group
-
- A default group, public, is set up each time a database is created. A
- database user is a member of the public group and possibly one other group.
-
-
-
- Managing Database Groups Using the Admin Menu
-
- The SA and Database Owner can use the Admin menu to add and delete database
- groups. Only the SA and Database Owner have permission to perform these
- tasks.
-
-
- Adding a Group
-
- To add a group to a database:
-
-
- 1. Select the Admin menu and choose Manage groups.
-
- The "Manage Groups" dialog box appears.
-
- 2. From the "Database" list box, select the database to which you want to
- add a group.
-
- 3. Choose OK.
-
- The "Manage Groups" dialog box appears.
-
- 4. Choose Add.
-
- The "Add a Groupname" dialog box appears.
-
- 5. In the "Groupname" text box, enter the name of the new group you want
- to add.
-
- The groupname must follow the rules for identifiers.
-
- 6. Choose OK.
-
- A message appears:
-
- New group added.
-
- 7. Choose OK.
-
- The "Manage Groups" dialog box appears. The new groupname should
- appear in the dialog box.
-
- 8. Choose Done.
-
-
- After adding a group, if you want to add group members who already have
- access to the database, see "Changing a User's Group," earlier in this
- chapter, for instructions. To add group members who do not have access to
- the database, see "Adding a Username," earlier in this chapter.
-
-
- Deleting a Group
-
- Before you can delete a group, you must remove all members from the group.
- You remove members from a group by changing the group they belong to (which
- may be public or some other group). See "Changing a User's Group," earlier
- in this chapter, for details on changing a user's group.
-
- Any group except public can be deleted.
-
- To delete a group:
-
-
- 1. Select the Admin menu and choose Manage groups.
-
- The "Manage Groups" dialog box appears.
-
- 2. From the "Database" list box, select the database from which you want
- to delete a group.
-
- 3. Choose OK.
-
- The "Manage Groups" dialog box appears.
-
- 4. From the "Groups" list box, select the name of the group to be
- deleted.
-
- 5. Choose Delete.
-
- A message appears:
-
- Group has been dropped.
-
- 6. Choose OK.
-
- The "Manage Groups" dialog box appears.
-
- 7. Choose Done.
-
-
-
- Managing Groups Using System Procedures
-
- You can add or delete a group using system procedures.
-
-
- Adding a Group
-
- To add a group to the current database, use the sp_addgroup system
- procedure.
-
- The sp_addgroup system procedure has the following syntax:
-
- sp_addgroup grpname
-
- ────────────────────────────────────────────────────────────────────────────
- grpname
- The name of the group. Groupnames must follow the rules for identifiers.
-
- ────────────────────────────────────────────────────────────────────────────
- Once a group is created, the Database Owner can add new users to it with the
- sp_adduser system procedure, discussed under "Adding a Username," earlier in
- this chapter.
-
- Users who already have access to the database can be made members of a group
- with sp_changegroup. (See "Changing a User's Group," earlier in this
- chapter, for more information.)
-
-
- Deleting a Group
-
- To delete a group, use the sp_dropgroup system procedure.
-
- The sp_dropgroup system procedure has the following syntax:
-
- sp_dropgroup grpname
-
- ────────────────────────────────────────────────────────────────────────────
- grpname
- The name of a group in the current database.
-
- ────────────────────────────────────────────────────────────────────────────
- For example, to delete the senior engineering group, execute this statement:
-
-
- sp_dropgroup senioreng
-
- You cannot drop a group that has members. To remove users from a group,
- execute sp_changegroup, discussed in "Changing a User's Group," earlier in
- this chapter.
-
-
- Displaying Information on Groups
-
- To display a report on groups within the current database, use the
- sp_helpgroup system procedure.
-
- The sp_helpgroup system procedure has the following syntax:
-
- sp_helpgroup [grpname]
-
- ────────────────────────────────────────────────────────────────────────────
- grpname
- The name of a group in the current database. If this option is omitted,
- all groups in the current database are displayed. Because PUBLIC is also a
- keyword, you must specify the group public in quotation marks in this
- context.
-
- ────────────────────────────────────────────────────────────────────────────
- The following example displays information about the hackers group:
-
- ╓┌─┌─────────────────────┌─────────┌────────────────┌────────────────────────╖
- ────────────────────────────────────────────────────────────────────────────
- sp_helpgroup hackers
-
- Group_name Group_id Users_in_group Userid
- ---------- -------- ----------- -------
- hackers 16384 ann 4
- hackers 16384 judy 3
-
- (2 rows affected)
-
-
- The report headings have the following descriptions:
-
- ────────────────────────────────────────────────────────────────────────────
- Group_name
- Groupname
-
- Group_id
- Number assigned by SQL Server
-
- Users_in_group
- Username in the database
-
- Userid
- Number assigned by SQL Server
-
- ────────────────────────────────────────────────────────────────────────────
- Advanced users may want to query the sysusers system table for additional
- information on groups. See Appendix B, "System Tables," for a description of
- this table.
-
-
- Managing Aliases
-
- With an alias, you can assume all the permissions of another user in a
- different database.
-
- This section describes how to:
-
-
- ■ Manage aliases with the SAF Admin menu
-
- ■ Manage aliases IDs by executing system procedures
-
- ■ Display information on aliases
-
-
-
- Aliases
-
- An alias allows a user to access a database and to assume all the
- permissions of a user in that database. The user who assumes the permissions
- of another user cannot have a username in the database in which he or she
- will assume permissions.
-
- One use for the alias mechanism is to allow several people to assume the
- role of Database Owner in a database.
-
- For example, suppose that Bob is the Database Owner of the reservations
- database. Bob is going on vacation and Mary has been assigned to take over
- as the reservations Database Owner while Bob is gone. Mary is not a user of
- reservations, but by creating an alias between Mary and Bob, Mary can use
- the reservations database and assume all Bob's permissions as Database
- Owner.
-
-
- Managing Aliases Using the Admin Menu
-
- The SA and Database Owner can use the Admin menu to create and remove
- aliases. Only the SA and Database Owner have permission to perform these
- tasks.
-
-
- Creating an Alias
-
- To create an alias:
-
-
- 1. Select the Admin menu and choose Manage aliases.
-
- The "Manage Aliases" dialog box appears.
-
- 2. From the "Database" list box, select the database in which you want to
- create an alias.
-
- 3. Choose OK.
-
- The "Manage Aliases" dialog box appears.
-
- 4. Choose Create.
-
- The "Create an Alias" dialog box appears.
-
- 5. In the "Login ID" list box, select the login ID of the user who will
- be linked with a username in the database you selected in step 2.
-
- 6. In the "Associated username" list box, select the username that will
- be used as an alias by the login ID you just selected.
-
- 7. Choose Create.
-
- A message appears:
-
- Alias user added.
-
- 8. Choose OK.
-
- The "Manage Aliases" dialog box appears.
-
- 9. Choose Done.
-
-
-
- Removing an Alias
-
- To remove an alias:
-
-
- 1. Select the Admin menu and choose Manage aliases.
-
- The "Manage Aliases" dialog box appears.
-
- 2. From the "Database" list box, select the database from which you want
- to remove an alias.
-
- 3. Choose OK.
-
- The "Manage Aliases" dialog box appears.
-
- 4. From the "User login ID/alias username" list box, select the login
- ID/alias that you want to remove.
-
- 5. Choose Remove.
-
- A message appears:
-
- Alias user dropped.
-
- 6. Choose OK.
-
- The "Manage Aliases" dialog box appears.
-
- 7. Choose Done.
-
-
-
- Managing Aliases Using System Procedures
-
- You can create and remove aliases by using system procedures.
-
-
- Creating an Alias
-
- To create an alias in the current database, use the sp_addalias system
- procedure.
-
- The sp_addalias system procedure has the following syntax:
-
- sp_addalias login_id, username
-
- ────────────────────────────────────────────────────────────────────────────
- login_id
- The name of the user who wants an alternate identity in the current
- database.
-
- username
- The name of the database user to whom the first user wishes to be linked.
-
- ────────────────────────────────────────────────────────────────────────────
- Executing sp_addalias maps the user with the specified login ID to the user
- with the specified username.
-
- As an example, suppose that Mary is the Database Owner of the pubs database.
- She wants both Jane and Sarah to use the database as if they were its
- owners. Jane and Sarah have login IDs on SQL Server but are not authorized
- to use Mary's database. Mary executes these statements:
-
- use pubs
- <execute>
- sp_addalias jane, dbo
- <execute>
- sp_addalias sarah, dbo
-
- Now either Jane or Sarah can access Mary's database and be recognized as the
- owner.
-
-
- Removing an Alias
-
- To drop an alias, use the sp_dropalias system procedure.
-
- The sp_dropalias system procedure has the following syntax:
-
- sp_dropalias login_id
-
- ────────────────────────────────────────────────────────────────────────────
- login_id
- The login ID of the user who has an alias
-
- ────────────────────────────────────────────────────────────────────────────
- Once a user's alias is dropped, the user no longer has access to the
- database unless his or her name is added to the database or the database has
- a guest user.
-
-
- Displaying Information on Aliases
-
- To display a report on groups within the current database, use the
- sp_helpuser system procedure.
-
- The sp_helpuser system procedure has the following syntax:
-
- sp_helpuser [username]
-
- ────────────────────────────────────────────────────────────────────────────
- username
- The username in the current database. If you don't specify a username, the
- system procedure reports on all users of the current database.
-
- ────────────────────────────────────────────────────────────────────────────
- In the following sample report, four login IDs (andy, christa, howard, and
- linda) have the alias dbo in the current database.
-
- ╓┌─┌───────────────────────┌─────────┌───────────┌───────────┌───────────────╖
- ────────────────────────────────────────────────────────────────────────────
- sp_helpuser dbo
-
- Users_name ID_in_db Group_name Login_name Default_db
- ---------- -------- ---------- ---------- ----------
- dbo 1 public sa master
-
- ────────────────────────────────────────────────────────────────────────────
- (1 row affected)
-
- Users aliased to user.
-
- Login_name
- -----------
- andy
- christa
- howard
- linda
- (4 rows affected)
-
-
- Advanced users may want to query the sysalternates system table for
- additional information on login IDs. See Appendix B, "System Tables," for a
- description of this table.
-
-
- Changing a Database Owner
-
- Ownership of a database can be transferred to another user. The new owner
- must already have a login ID on SQL Server, but must not have a username or
- alias in the database. If you want to assign database ownership to such a
- user, drop his or her database name and aliases before changing ownership.
-
- After you have assigned a new owner, the new owner is known as dbo in the
- database. If you (as SA) want to grant permissions to this new owner, grant
- them to dbo─the user is no longer known in the database under any other
- name.
-
- This section describes how to:
-
-
- ■ Change a database owner with the SAF Admin menu
-
- ■ Change a database owner by executing system procedures
-
- ■ Display information on database ownership
-
- ────────────────────────────────────────────────────────────────────────────
- NOTE
-
- The master database is owned by the SA. You cannot change its ownership.
- ────────────────────────────────────────────────────────────────────────────
-
-
-
-
-
- Changing a Database Owner Using the Admin Menu
-
- The SA or Database Owner can use the Admin menu to change database owners.
- Only the SA and Database Owner have permission to perform this task.
-
- To change ownership of a database:
-
-
- 1. Select the Admin menu and choose Change database owner.
-
- The "Change Database Owner" dialog box appears.
-
- 2. From the "Database" list box, select the database for which you want
- to change the owner.
-
- 3. Choose OK.
-
- The "Change Database Owner" dialog box appears. Note that the current
- Database Owner is listed.
-
- 4. In the "New database owner" list box, select the new Database Owner.
-
- 5. Choose OK.
-
- A message appears:
-
- Database owner changed.
-
- 6. Choose OK.
-
-
-
- Changing a Database Owner Using System Procedures
-
- To change a database owner in the current database, use the sp_changedbowner
- system procedure.
-
- The new owner must already have a login ID on SQL Server but must not have a
- database name or alias in the database. If you want to assign database
- ownership to such a user, drop his or her database name and alias before
- executing sp_changedbowner.
-
- The sp_changedbowner system procedure has the following syntax:
-
- sp_changedbowner login_id
-
- ────────────────────────────────────────────────────────────────────────────
- login_id
- The login ID of the new owner of the current database. The new owner must
- not already be known as a user or have an alias.
-
- ────────────────────────────────────────────────────────────────────────────
- For example, the SA decides to transfer ownership of the pubs database to
- Jane. The SA executes these statements:
-
- use pubs
- <execute>
- sp_changedbowner jane
-
-
- Displaying Information on Database Owners
-
- To display information on Database Owners, use the sp_helpuser system
- procedure (described under "Displaying Information on Usernames," earlier in
- this chapter.)
-
- After you change the Database Owner, the new Database Owner's username shows
- up as dbo.
-
-
- Displaying Information on Current Users
-
- You can display information on current users with the Admin menu, or you can
- execute a system procedure.
-
- To display information on current users using the Admin menu:
-
-
- 1. Select the Admin menu and choose Display current users.
-
- The "Display Current Users" dialog box appears. It contains
- information on all current users of SQL Server.
-
- 2. Choose OK.
-
-
- To display information on current users, use the sp_who system procedure.
-
- The sp_who system procedure has the following syntax:
-
- sp_who
-
- The following is a sample report:
-
- ╓┌───────┌──────────┌──────────┌──────────┌──────────┌───────┌──────────┌────
- ─────────────────────────────────────────────────────────────────────────────
- ─────────────────────────────────────────────────────────────────────────────
- spid status loginame hostname blk dbname cmd
-
- ---- -------- -------- -------- ---- ------- ------
-
- 1 sleeping sa plum 0 pubs AWAITI
-
- 2 sleeping sa 0 master NETWOR
-
- 3 sleeping sa 0 master CHECKP
-
- 4 sleeping karenp plum 1 pubs SELECT
-
- 5 runnable karenp plum 0 pubs SELECT
-
-
-
- (5 rows
- affected)
-
-
-
- The report headings have the following descriptions:
-
- ────────────────────────────────────────────────────────────────────────────
- spid
- Server process ID. This number is used in the KILL statement.
-
- status
- Status of the process.
-
- loginame
- Login ID of the process user.
-
- hostname
- Name of workstation.
-
- blk
- Process ID of the blocking process, if there is one.
-
- dbname
- Name of database.
-
- cmd
- Statement name being executed.
-
- ────────────────────────────────────────────────────────────────────────────
- Advanced users may want to query the sysprocesses system table for
- additional information. See Appendix B, "System Tables," for a description
- of this table.
-
-
-
-
-
-
- Chapter 7 Managing User Permissions
- ────────────────────────────────────────────────────────────────────────────
-
-
- Introduction
-
- This chapter describes SQL Server's permissions system. The permissions
- system specifies which users are authorized to use which SQL statements,
- views, and stored procedures. The ability to assign permissions is
- determined by each user's status (as SA, Database Owner, or database object
- owner).
-
- In this chapter, you learn how to
-
-
- ■ Grant and revoke permissions
-
- ■ Use views, stored procedures, and triggers
-
-
-
- Permissions Summary
-
- The following table summarizes the SQL Server permissions system. The type
- of user listed as the one to whom the statement defaults is the "lowest"
- level of user to which the permission is automatically granted. This user
- can grant the permission to other users or revoke it from other users, if it
- is transferable.
-
- Table 7.1 Summary of Protection System
-
- ╓┌────────────┌──────────┌──────────┌──────────┌───────┌──────────┌───┌──────╖
- Can Be
- Defaults Granted /
- to Revoked
- System Db Owner Table Public Yes No N/A
- Admin Owner
- Statement:
- ────────────────────────────────────────────────────────────────────────────
- ALTER X ─ ─ ─ (1) ─ ─
- DATABASE
-
- ALTER TABLE ─ ─ X ─ ─ X ─
-
- BEGIN ─ ─ ─ X ─ ─ X
- TRANSACTION
-
- CHECKPOINT ─ X ─ ─ ─ X ─
-
- Can Be
- Defaults Granted /
- to Revoked
- System Db Owner Table Public Yes No N/A
- Admin Owner
- Statement:
- COMMIT ─ ─ ─ X ─ ─ X
- TRANSACTION
-
- CREATE X ─ ─ ─ X ─ ─
- DATABASE
-
- CREATE ─ X ─ ─ X ─ ─
- DEFAULT
-
- CREATE ─ ─ X ─ ─ X ─
- INDEX
-
- CREATE ─ X ─ ─ X ─ ─
- PROCEDURE
- Can Be
- Defaults Granted /
- to Revoked
- System Db Owner Table Public Yes No N/A
- Admin Owner
- Statement:
- PROCEDURE
-
- CREATE RULE ─ X ─ ─ X ─ ─
-
- CREATE ─ X ─ (2) X(2) ─ ─
- TABLE
-
- CREATE TRIG ─ ─ X ─ ─ X ─
- GER
-
- CREATE VIEW ─ X ─ ─ X ─ ─
-
- DBCC ─ X ─ ─ ─ ─ X
-
- DELETE ─ ─ X(3) ─ X ─ ─
- Can Be
- Defaults Granted /
- to Revoked
- System Db Owner Table Public Yes No N/A
- Admin Owner
- Statement:
- DELETE ─ ─ X(3) ─ X ─ ─
-
- DISK INIT X ─ ─ ─ ─ X ─
-
- DISK REFIT X ─ ─ ─ ─ X ─
-
- DISK REINIT X ─ ─ ─ ─ X ─
-
- DROP (any ─ ─ ─ ─ ─ X ─
- object)(4)
-
- DUMP ─ X ─ ─ X ─ ─
- DATABASE
-
- DUMP ─ X ─ ─ X ─ ─
- Can Be
- Defaults Granted /
- to Revoked
- System Db Owner Table Public Yes No N/A
- Admin Owner
- Statement:
- DUMP ─ X ─ ─ X ─ ─
- TRANSACTION
-
- EXECUTE (5) ─ ─ ─ ─ X ─ ─
-
- GRANT ─ X ─ ─ ─ X ─
-
- GRANT (on ─ ─ ─ ─ ─ X ─
- object) (4)
-
- INSERT ─ ─ X(3) ─ X ─ ─
-
- KILL X ─ ─ ─ ─ X ─
-
- LOAD ─ X ─ ─ ─ X ─
- Can Be
- Defaults Granted /
- to Revoked
- System Db Owner Table Public Yes No N/A
- Admin Owner
- Statement:
- LOAD ─ X ─ ─ ─ X ─
- DATABASE
-
- LOAD ─ X ─ ─ ─ X ─
- TRANSACTION
-
- PRINT ─ ─ ─ X ─ ─ X
-
- RAISERROR ─ ─ ─ X ─ ─ X
-
- READTEXT ─ ─ X(3) ─ X ─ ─
-
- RECONFIGURE X ─ ─ ─ ─ X ─
-
- REVOKE ─ X ─ ─ ─ X ─
- Can Be
- Defaults Granted /
- to Revoked
- System Db Owner Table Public Yes No N/A
- Admin Owner
- Statement:
- REVOKE ─ X ─ ─ ─ X ─
-
- REVOKE (on ─ ─ ─ ─ ─ X ─
- object) (4)
-
- ROLLBACK ─ ─ ─ X ─ ─ X
- TRANSACTION
-
- SAVE ─ ─ ─ X ─ ─ X
- TRANSACTION
-
- SELECT ─ ─ X(3) ─ X ─ ─
-
- SET ─ ─ ─ X ─ ─ X
-
- Can Be
- Defaults Granted /
- to Revoked
- System Db Owner Table Public Yes No N/A
- Admin Owner
- Statement:
- SETUSER ─ X ─ ─ ─ X ─
-
- TRUNCATE ─ ─ X ─ ─ X ─
- TABLE
-
- UPDATE ─ ─ X(3) ─ X ─ ─
-
- UPDATE ─ ─ X ─ ─ X ─
- STATISTICS
-
- WRITETEXT ─ ─ X(3) ─ X ─ ─
-
- ────────────────────────────────────────────────────────────────────────────
-
- Can Be
- Defaults Granted /
- to Revoked
- System Db Owner Table Public Yes No N/A
- Admin Owner
- Statement:
-
-
- (1) Transferred with CREATE DATABASE permission
- (2) Public can create temporary tables, no permission required
- (3) If a view, permission defaults to view owner
- (4) Defaults to object owner
- (5) Defaults to stored procedure owner
-
-
-
- Object and Statement Permissions
-
- There are two categories of permissions: object and statement. Permissions
- for the SELECT, UPDATE, INSERT, DELETE, and EXECUTE statements are called
- object permissions because these statements always apply to database objects
- (in the current database).
-
- The objects to which the object permissions apply are as follows:
-
- ╓┌────────────────────────┌──────────────────────────────────────────────────╖
- Statement Object
- ────────────────────────────────────────────────────────────────────────────
- SELECT Table, view, column
- UPDATE Table, view, column
- INSERT Table, view
- DELETE Table, view
- EXECUTE Stored procedure
- ────────────────────────────────────────────────────────────────────────────
-
-
- Statement permissions are not object specific. They can be granted only by
- the SA or a Database Owner. Statement permissions apply to the following
- statements:
-
-
- ■ CREATE DATABASE (can be granted only by the SA and only to users in
- the master database)
-
- ■ CREATE DEFAULT
-
- ■ CREATE PROCEDURE
-
- ■ CREATE RULE
-
- ■ CREATE TABLE
-
- ■ CREATE VIEW
-
- ■ DUMP DATABASE
-
- ■ DUMP TRANSACTION
-
-
- Each database has its own independent permissions system. In other words,
- being granted permission to use a certain statement in one database has no
- effect in other databases.
-
- If you try to use a statement or database object for which you do not have
- permission, SQL Server responds with an error message.
-
-
- The Permission Hierarchy
-
- SQL Server's permissions system recognizes four types of users:
-
-
- ■ The SA
-
- ■ Database Owners
-
- ■ Database object owners
-
- ■ Other users of the database
-
-
- The different types of users exist in a kind of hierarchy, with the SA at
- the top and other users at the bottom.
-
-
- Permissions of the SA
-
- The SA is the special user who handles tasks not specific to an application.
- There are no restrictions on what the SA can do within SQL Server.
-
- There are several statements that only the SA can execute; they cannot be
- granted to any other user:
-
-
- ■ DISK INIT
-
- ■ DISK REFIT
-
- ■ DISK REINIT
-
- ■ KILL
-
- ■ RECONFIGURE
-
-
- Only the SA can grant CREATE DATABASE permission. Control of this statement
- is reserved for the SA because it determines the amount and location of the
- storage allocated for each database. ALTER DATABASE permission on a database
- defaults to the owner of that database, but only if he or she has CREATE
- DATABASE permission. ALTER DATABASE permission cannot be transferred.
-
-
- Permissions of Database Owners
-
- The Database Owner has full permission to do anything inside that database
- and must grant permissions to other users.
-
- The following permissions are automatically granted to the Database Owner
- and cannot be transferred to other users:
-
-
- ■ CHECKPOINT
-
- ■ DBCC
-
- ■ DROP DATABASE
-
- ■ GRANT and REVOKE statement permissions
-
- ■ LOAD DATABASE
-
- ■ LOAD TRANSACTION
-
- ■ SETUSER
-
-
- Database owners can grant permissions on the following statements to other
- users:
-
-
- ■ CREATE DEFAULT
-
- ■ CREATE PROCEDURE
-
- ■ CREATE RULE
-
- ■ CREATE TABLE
-
- ■ CREATE VIEW
-
- ■ DUMP DATABASE
-
- ■ DUMP TRANSACTION
-
- ■ GRANT and REVOKE object permissions
-
-
-
- Permissions of Database Object Owners
-
- A user who creates a database object (a table, view, or stored procedure) is
- its owner and is automatically granted all object permissions on it. Users
- other than the object owner, including the owner of the database, are
- automatically denied all permissions on that object unless they are granted
- by the owner.
-
- Object permissions are granted on the statements SELECT, UPDATE, INSERT,
- DELETE, and EXECUTE.
-
- As an example, say that Mary is the owner of the pubs database and has
- granted Joe permission to create tables in it. Joe creates the table
- authors; he is the owner of this database object.
-
- Initially, object permissions on authors belong to Joe and Joe alone. Joe
- can grant object permissions for this table to other users, including Mary,
- the Database Owner. (However, the Database Owner can use the SETUSER
- statement to "impersonate" Joe.)
-
- The following statement permissions default to the owner of a table and
- cannot be transferred to other users:
-
-
- ■ ALTER TABLE
-
- ■ CREATE INDEX
-
- ■ CREATE TRIGGER
-
- ■ DROP TABLE
-
- ■ TRUNCATE TABLE
-
- ■ UPDATE STATISTICS
-
-
- Permission to use the GRANT and REVOKE statements cannot be transferred.
-
- Permission to drop an object─a table, view, index, stored procedure, rule,
- or default─defaults to its owner and cannot be transferred.
-
-
- Permissions on System Tables
-
- The SQL Server setup program sets permissions on the system tables in a user
- database so that all database users can read them.
-
- However, the default is that no users─including Database Owners─can modify
- the system tables directly through SQL statements. Rather, the system tables
- are modified by executing system procedures or using the SAF menus. (The SA
- can change this situation so that ad hoc modifications to the system tables
- are allowed. See Chapter 11, "Diagnosing System Problems," for more
- information.)
-
-
- Permissions on System Procedures
-
- Since system procedures are located in the master database, their
- permissions are also set there.
-
- Some of the system procedures can be executed only by Database Owners. These
- procedures make sure that the user executing the procedure is the owner of
- the database from which it is being executed.
-
- Other system procedures (for example, all the sp_help procedures) can be
- executed by any user who has been granted permission─but this permission
- must be granted in master. In other words, a user must have permission to
- execute a system procedure in all databases or in none of them.
-
- SQL Server users who do not have usernames in the master database are
- treated as guest in master and thus are automatically granted permission on
- many of the system procedures. To deny a user permission on a system
- procedure, the SA must add that user to the master database and write a
- REVOKE statement that applies to that procedure. The owner of a user
- database cannot directly control permissions on the system procedures within
- his or her own database.
-
-
- The SETUSER Statement
-
- A Database Owner can use the SETUSER statement to "impersonate" another
- user's identity and permission status in the current database. A Database
- Owner can use SETUSER to access an object owned by another user, to grant
- permissions on an object owned by another user, to create an object that
- will be owned by another user, or to temporarily take on the permissions of
- another user.
-
- SETUSER permission defaults to the Database Owner and cannot be transferred.
- The user being impersonated must be an authorized user of the current
- database.
-
- The SETUSER statement has the following syntax:
-
- setuser ["user_name"]
-
- The SA can use SETUSER to create objects that will be owned by another user.
- However, since the SA operates outside the permissions system, he or she
- cannot use SETUSER to acquire another user's permissions. No matter what
- SETUSER statements have been executed, the SA always retains permission to
- do everything.
-
- To reestablish your original identity, execute the SETUSER statement with no
- name after it.
-
- Here's how the Database Owner would grant Joe permission to read the authors
- table, which is owned by Mary:
-
- setuser "mary"
- <execute>
- grant select on authors to joe
- <execute>
- setuser
-
- When the Database Owner uses the SETUSER statement, SQL Server checks the
- permissions of the user being impersonated.
-
- The SETUSER statement remains in effect until another SETUSER statement is
- executed or until the current database is changed with the USE statement.
-
-
- Granting and Revoking Permissions
-
- Statement and object permissions are granted or removed with the GRANT and
- REVOKE statements.
-
-
- GRANT and REVOKE Statements
-
- The syntax for statement permissions differs slightly from the syntax for
- object permissions.
-
-
- Statement Permissions
-
- Statement permissions have the following syntax:
-
- GRANT {ALL | statement_list}
- TO {PUBLIC | name_list}
-
- REVOKE {ALL | statement_list}
- FROM {PUBLIC | name_list}
-
- ────────────────────────────────────────────────────────────────────────────
- ALL
- Only the SA can use ALL to assign statement permissions since only the SA
- can grant or revoke CREATE DATABASE permission.
-
- PUBLIC
- All the users in the public group.
-
- statement_list
- A list of statements granted or revoked. The statement list can include
- CREATE DATABASE (if the user executing the statement is the SA), CREATE
- DEFAULT, CREATE PROCEDURE, CREATE RULE, CREATE TABLE, CREATE VIEW, DUMP
- DATABASE, and DUMP TRANSACTION.
-
- If several statements are listed, separate them with commas.
-
- name_list
- A list of users' database names and/or groupnames, separated by commas.
-
- ────────────────────────────────────────────────────────────────────────────
- Object Permissions
-
- Object permissions (permission to use tables, views, columns, and stored
- procedures) have the following syntax:
-
- GRANT {ALL | permission_list}
- ON {table_name [(column_list)...] |
- view_name [(column_list)] |
- stored_procedure_name}
- TO {PUBLIC | name_list}
-
- REVOKE {ALL | permission_list}
- ON {table_name [(column_list...)] |
- view_name [(column_list)] |
- stored_procedure_name}
- FROM {PUBLIC | name_list}
-
- ────────────────────────────────────────────────────────────────────────────
- ALL
- Specifies that all permissions applicable to the specified object are
- granted or revoked.
-
- permission_list
- A list of permissions granted or revoked. When permissions are granted or
- revoked on a table or a view, the permission list can include one or more
- of the following items: SELECT, INSERT, DELETE, and UPDATE.
-
- When permissions are granted or revoked on columns, the permission list
- can include one or both of the following items: SELECT and UPDATE.
-
- When permissions are granted or revoked on stored procedures, the
- permission list can include EXECUTE only.
-
- If several permissions are listed, separate them with commas.
-
- table_name
- The name of one table in the current database.
-
- column_list
- A list of columns, separated by commas, to which the permissions apply. If
- columns are specified, only SELECT and UPDATE permissions can be granted.
- If several columns are specified, all columns must be in the same table or
- view.
-
- view_name
- The name of one view in the current database.
-
- stored_procedure_name
- The name of one stored procedure in the current database.
-
- PUBLIC
- All users in the public group.
-
- name_list
- A list of users' database names and/or groupnames, separated by commas.
-
- ────────────────────────────────────────────────────────────────────────────
- Examples
-
- The following statement grants permission to mary and the sales group to
- insert into and delete from the titles table:
-
- grant insert, delete
- on titles
- to mary, sales
-
- The following statement grants permission to harold to use the makelist
- stored procedure:
-
- grant execute
- on makelist
- to harold
-
- The following statement revokes permission from all users to update the
- price and ytd_sales columns of the titles table:
-
- revoke update
- on titles (price, ytd_sales)
- from public
-
- The following examples show how to grant and revoke statement permissions:
-
- grant create table, create view
- to mary, jane, bob
-
- grant dump database, dump tran
- to public
-
- revoke create table, create rule
- from mary
-
-
- Combining GRANT and REVOKE Statements
-
- There are two basic ways of setting up permissions in a database or on a
- database object. The most straightforward way is to assign specific
- permissions to specific users.
-
- However, if most users are going to be granted most permissions, it's easier
- to assign all permissions to all users and then revoke specific permissions
- from specific users.
-
- For example, a Database Owner can grant all permissions on the titles table
- to all users by executing the following statement:
-
- grant all
- on titles
- to public
-
- Then the Database Owner can execute a series of REVOKE statements to remove
- permissions; for example:
-
- revoke update
- on titles (royalty, advance)
- from public
-
- revoke delete
- on titles
- from mary, sales, john
-
-
- Conflicting GRANT and REVOKE Statements
-
- As implied in the preceding section, GRANT and REVOKE statements are
- sensitive to the order in which they are executed. So, for example, if Joe's
- group has been granted select permission on the titles table and then Joe's
- permission to select the advance column has been revoked, Joe can select all
- the columns except advance, while the other users in his group can still
- select all the columns.
-
- A GRANT or REVOKE statement that applies to a group changes any conflicting
- permissions that have been assigned to any member of that group. For
- example, the owner of the titles table has granted different permissions to
- various members of the sales group and then decides to standardize. The
- owner might execute the following statements:
-
- revoke all on titles from sales
- grant select on titles(title, title_id, type, pub_id) to sales
-
- Similarly, a GRANT or REVOKE statement executed for public will change, for
- all users in the public group, any previously executed permissions that
- conflict with the new statement.
-
- The same GRANT and REVOKE statements executed in different order can create
- entirely different situations. For example, following is a set of statements
- that leaves Joe without any select permission on titles (assuming Joe
- belongs to the public group):
-
- grant select on titles(title_id, title) to joe
- revoke select on titles from public
-
- In contrast, the same statements executed in the opposite order result in
- only Joe having select permission, and only on the title_id and title
- columns.
-
- Remember that when you use the PUBLIC keyword, you are including yourself
- (if you are a member of the public group). You may want to deny yourself
- permission to use your own table, while giving yourself permission to access
- a view built on it. (You can always change your mind and reinstitute the
- permission with a GRANT statement.) You will probably use PUBLIC more
- frequently as a quick way of revoking permissions and then defining some
- exceptions, as in the earlier example.
-
-
- Displaying Information on Permissions
-
- The sp_helprotect system procedure reports on permissions by database object
- and (optionally) by user for the specified object. Any user can execute this
- procedure.
-
- The sp_helprotect system procedure has the following syntax:
-
- sp_helprotect name [, user_name]
-
- ────────────────────────────────────────────────────────────────────────────
- name
- The name of a table, view, or stored procedure; or the name of a user or
- group in the current database.
-
- user_name
- A user's name in the current database.
-
- ────────────────────────────────────────────────────────────────────────────
- The following is a series of GRANT and REVOKE statements:
-
- grant select on titles to judy
- grant update on titles to judy
- revoke update on titles(price) from judy
-
- Here is the display that would be generated after executing the GRANT and
- REVOKE statements:
-
- sp_helprotect titles
-
- type action user column
- --------- --------- --------- ---------
- Grant Select public All
- Grant Select guest All
- Grant Update guest All
- Grant Select judy All
- Grant Update judy title_id
- Grant Update judy title
- Grant Update judy type
- Grant Update judy pub_id
- Grant Update judy advance
- Grant Update judy royalty
- Grant Update judy notes
- Revoke Update judy price
-
- (12 rows affected)
-
-
- Permissions on Views and Stored Procedures
-
- Views and stored procedures can serve as security mechanisms. A user can be
- granted permission on a view or on a stored procedure even if he or she has
- no permissions on objects the view or procedure references.
-
-
- Views as Security Mechanisms
-
- Through a view, users can query and modify only the data they can see. The
- rest of the database is neither visible nor accessible.
-
- Permission to access the subset of data in a view must be granted or
- revoked, regardless of the set of permissions in force on the view's
- underlying tables. Data in an underlying table that is not included in the
- view is hidden from users who are authorized to access the view but not the
- underlying table.
-
- By defining different views and selectively granting permissions on them, a
- user (or any combination of users) can be restricted to different subsets of
- data. The following examples illustrate the use of views for security
- purposes:
-
-
- ■ Access can be restricted to a subset of the rows of a base table (a
- value-dependent subset). For example, you might define a view that
- contains only the rows for business and psychology books to keep
- information about other types of books hidden from some users.
-
- ■ Access can be restricted to a subset of the columns of a base table (a
- value-independent subset). For example, you might define a view that
- contains all the rows of the titles table but omits the royalty and
- advance columns, since this information is sensitive.
-
- ■ Access can be restricted to a row-and-column subset of a base table.
-
- ■ Access can be restricted to the rows that qualify for a join of more
- than one base table. For example, you might define a view that joins
- the titles, authors, and titleauthor table to display the names of the
- authors and the books they have written. This view would hide personal
- data about authors and financial information about the books.
-
- ■ Access can be restricted to a statistical summary of data in a base
- table. For example, you might define a view that contains only the
- average price of each type of book.
-
- ■ Access can be restricted to a subset of another view or of some
- combination of views and base tables.
-
-
- As an example, you want to prevent some users from accessing the columns in
- the titles table that have to do with money and sales. You could create a
- view of the titles table that omits those columns and then give all users
- permission on the view but only the Sales Department permission on the
- table. You would execute the following statements:
-
- grant all on bookview to public
- grant all on titles to sales
-
- An equivalent way of setting up these permission conditions without using a
- view is this series of statements:
-
- grant all on titles to public
- revoke select, update on titles (price, advance, royalty, ytd_sales)
- from public
- grant select, update on titles (price, advance, royalty, ytd_sales)
- to sales
-
- One possible problem with the second scheme is that users not in the sales
- group who enter the statement "SELECT * from titles" might be surprised to
- see a "permission denied" message. SQL Server expands the asterisk into a
- list of all the columns in the titles table and since permission on some of
- these columns has been revoked from nonsales users, refuses access to them.
- The error message lists the columns for which the user does not have access.
-
-
- To see all the columns for which they do have permission, the nonsales users
- would have to name them specifically. For this reason, creating a view and
- granting the appropriate permissions on it is a better solution.
-
- In addition to protecting data based on a selection of rows and/or columns,
- views can be used for context-sensitive permission. For example, you can
- create a view that gives a data entry clerk permission to access only those
- rows that he or she has added or updated.
-
- To do so, you would add a uid column to a table in which the user ID of the
- user entering each row is automatically recorded with a default. Define the
- default using the user_id system function and bind it to uid, like this:
-
- create default user_def
- as user_id()
-
- sp_bindefault user_def, "testtable.uid"
-
- Next, define a view that includes all the rows of the table where uid is the
- current user:
-
- create view context_view
- as select *
- from testtable
- where uid = user_id()
-
- The rows retrievable through this view depend on the identity of the person
- who executes the SELECT statement against the view. For more information on
- creating views, see SQL Server Learning TRANSACT-SQL.
-
- Permissions on views are checked when the view is used, not when it is
- created.
-
-
- Stored Procedures as Security Mechanisms
-
- A user with permission to execute a stored procedure can do so even if he or
- she does not have permissions on tables or views referenced in it. For
- example, a user might be given permission to execute a stored procedure that
- updates a row-and-column subset of a specified table even though that user
- does not have any other permissions on that table.
-
- Permissions on stored procedures are checked when the procedure is used, not
- when it is created.
-
-
- Ownership Chains
-
- Views can depend on other views and/or tables. Procedures can depend on
- other procedures, views, and/or tables. These dependencies can be thought of
- as an "ownership chain."
-
- Typically, the owner of a view also owns its underlying objects (other views
- and tables), and the owner of a stored procedure often owns all the
- procedures, tables, and views the procedure references. Also, a view and its
- underlying objects are usually all in the same database, as are a stored
- procedure and all the objects it references.
-
- When a user with permission to access a view does so, SQL Server does not
- check permissions on any of the view's underlying objects if these objects
- and the view are all owned by the same user, and if the view and all its
- underlying objects are in the same database.
-
- Similarly, if the same user owns a stored procedure and all the views or
- tables it references, and if the procedure and the objects it references are
- all in the same database, SQL Server checks only the permissions on the
- procedure.
-
- However, if the ownership chain of a procedure or view is broken─that is, if
- not all the objects in the chain are owned by the same user─SQL Server
- checks permissions on each object in the chain whose next lower "link" is
- owned by a different user. In this way, SQL Server allows the owner of the
- original data to retain control over who is authorized to access it.
-
- Ordinarily, a user who creates a view only has to grant permissions on that
- view. For example, say Mary has created a view called auview1 on the authors
- table, which she also owns. If Mary grants Sue permission to use auview1,
- SQL Server will let Sue access it without checking permissions on authors.
-
- However, a user who creates a view or stored procedure that depends on an
- object owned by another user must be aware that any permissions he or she
- grants depend on the permissions allowed by those other owners.
-
- For example, Joe creates a view called auview2, which depends on Mary's view
- auview1. Joe grants Sue permission to use auview2:
-
- auview2(Joe) --> auview1(Mary) --> authors(Mary)
-
- SQL Server checks the permissions on auview2 and auview1, and finds that Sue
- is allowed to use them.
-
- SQL Server performs no authorization checks at the time the view is created.
- In fact, if Joe has permission on the CREATE VIEW statement, he can define a
- view based on the authors table even if he does not have SELECT permission
- on authors. However, the view would be useless to everyone, including Joe.
-
- Let's take our example a step further. Suppose that Joe's view, auview2,
- depends on auview1, which depends on authors. Mary decides she likes Joe's
- auview2 and creates auview3 on top of it. As you may recall, both auview1
- and authors are owned by Mary. The situation can be depicted like this, with
- the object owner given in parentheses after the object name:
-
- auview3(Mary) --> auview2(Joe) --> auview1(Mary) --> authors(Mary)
-
- When Sue tries to access auview3, SQL Server checks permissions on auview3,
- auview2, and auview1. If Joe has granted Sue access on auview2 and Mary has
- granted her permission on auview3 and auview1, SQL Server allows the access.
- SQL Server checks permissions only if the object immediately before it in
- the chain has a different owner (or if it is the first object in the chain).
- For example, it checks auview2 because the object before it─auview3─is owned
- by a different user. It does not check permission on authors because the
- object whic
-
- (Please refer to the printed book.)
-
- h immediately depends on it, auview1, is owned by the same user. Procedures
- follow the same rules. As an example, suppose the situation is this:
-
- P4(Mary) --> P3(Mary) --> P2(Joe) --> P1(Mary) --> authors(Mary)
-
- To execute P4, Sue must have permission to execute P4, P2, and P1.
- Permission to execute P3 is not necessary, since P3 and P4 have the same
- owner.
-
- SQL Server checks Sue's permissions on P4 and all objects it references each
- time she executes P4. However, SQL Server knows which referenced objects to
- check because it has determined this the first time Sue executes P4 and has
- saved this information with the procedure's execution plan. Unless one of
- the objects referenced by the procedure is dropped or otherwise redefined,
- SQL Server sticks with its initial decision about which objects to check.
-
- Figure 7.1 shows a situation in which procedures and views owned by two
- different users depend on each other in a fairly complex way.
-
- (This figure may be found in the printed book.)
-
- If a user tries to execute procedure1, SQL Server checks permissions on
- procedure1, procedure3, view2, table2, and table3.
-
- In summary, the purpose of this permission hierarchy is to allow every
- object's owner to fully control access to the object. Owners can control
- access to views and stored procedures, as well as to tables.
-
-
- Triggers
-
- Triggers are a special kind of stored procedure used to enforce integrity,
- especially referential integrity. (See SQL Server Learning TRANSACT-SQL or
- the SQL Server Language Reference for details.) Triggers are never executed
- directly, but only as a side effect of modifying a table. There is no way to
- grant or revoke permissions for triggers.
-
- Only the owner of an object can create a trigger on it. However, the
- ownership chain can be broken if a trigger on a table references objects
- owned by different users. The permission hierarchy rules that apply to
- procedures also apply to triggers.
-
- While the objects that a trigger affects are usually owned by the same user
- who owns the trigger, you can write a trigger that modifies an object owned
- by another user. If this is the case, any users modifying your object in a
- way that kicks off the trigger must have permission on the other object as
- well.
-
- If SQL Server denies permission on a data modification statement because of
- a trigger that affects an object for which the user does not have
- permission, the entire data modification statement is aborted.
-
-
-
-
-
-
- Chapter 8 Backup and Recovery
- ────────────────────────────────────────────────────────────────────────────
-
-
- Introduction
-
- SQL Server provides two different kinds of recovery: one that is done
- automatically and one that you are responsible for doing.
-
- Automatic recovery is run every time SQL Server is restarted. This type of
- recovery protects you from system failures.
-
- For the nonautomatic type of recovery, you dump the database at regular
- intervals and then load the dumped database when necessary. This type of
- recovery is the only means of recovering data in case of media failure.
-
- This chapter describes automatic recovery and how to
-
-
- ■ Dump databases and transaction logs
-
- ■ Load databases
-
- ■ Load transaction logs
-
- ■ Move databases
-
- ■ Restore the master database
-
- ■ Recover from media failure
-
-
-
- Automatic Recovery
-
- Whenever SQL Server is restarted, recovery is performed automatically on
- each database. Typically, recovery takes from a few seconds to a few
- minutes.
-
- Automatic recovery does the following:
-
-
- 1. Rolls back uncommitted transactions─those that were ongoing at the
- time of the failure.
-
- 2. Checks the transactions that had been committed between the last
- checkpoint and the failure, and rolls them forward.
-
-
- Automatic recovery begins with the master database, goes on to model, clears
- out the tempdb temporary database, and finally recovers user databases.
- Users can log in to SQL Server as soon as the system databases have been
- recovered but can't access other databases while recovery is in progress.
-
- Two configuration options are relevant to automatic recovery:
-
-
- ■ The recovery interval option controls the maximum time required to
- recover a database by setting the interval at which SQL Server decides
- whether to run an automatic checkpoint.
-
- ■ The recovery flags option determines what information SQL Server
- displays during recovery.
-
-
- For more information on configuration options, see Chapter 9, "Fine-tuning
- Performance and Operations."
-
- In each database, the automatic recovery mechanism looks at the transaction
- log. If the log has been written more recently than the database, the
- recovery mechanism rolls the committed transactions forward so that the
- database looks like the log. However, if the transactions were not
- committed, it rolls them back.
-
-
- Transaction Logs
-
- Unless you specify otherwise, every change to a database is automatically
- recorded in its transaction log. Each database has its own transaction log.
- The transaction log is used by SQL Server during automatic recovery and is
- not queried with SQL statements.
-
- The transaction log records data modification requests (UPDATE, INSERT, or
- DELETE statements) as they are executed. When a transaction begins, a "begin
- transaction" event is recorded in the log. This event is used during
- automatic recovery to determine the starting point of the transaction.
-
- As each data modification statement is received, it is recorded in the log.
- The change is always recorded in the log before that change is made in the
- database itself. This type of log is called a write-ahead log. (Before the
- database or log changes are written to the database device, they are in the
- disk cache in memory.)
-
- The transaction log is shared by all users of the database so that multiple
- changes are frequently recorded each time a log page is written to the
- database device.
-
- ────────────────────────────────────────────────────────────────────────────
- WARNING
-
- Do not access the syslogs system table. It is for the internal use of SQL
- Server only.
- ────────────────────────────────────────────────────────────────────────────
-
-
- Checkpoints
-
- The checkpoint mechanism is an automatic means of guaranteeing that
- completed transactions are regularly written from the disk cache to the
- database device. A checkpoint writes all "dirty" pages─pages that have been
- modified since the last checkpoint─to the database device.
-
- There are two kinds of checkpoints: those executed automatically by SQL
- Server and those "forced" by Database Owners with the CHECKPOINT statement.
-
-
- Forcing the dirty pages onto the database device means that all completed
- transactions are written out. By calling all completed transactions to be
- written out, the checkpoint shortens the time it takes to recover. A typical
- checkpoint takes about a second.
-
- The automatic checkpoint interval is calculated by SQL Server on the basis
- of system activity and the recovery interval configuration option, which
- specifies the maximum acceptable recovery time. For more information on
- configuration options, see Chapter 9, "Fine-tuning Performance and
- Operations."
-
- The checkpoint (actually, the checkpoint checking process) also performs a
- few other "housekeeping" tasks, including truncating the log if this
- database option has been set. For more information on database options, see
- Chapter 9, "Fine-tuning Performance and Operations."
-
- Database Owners can force a checkpoint at any time by executing the
- CHECKPOINT statement:
-
- checkpoint
-
- Permission to execute the CHECKPOINT statement defaults to the Database
- Owner and cannot be transferred to other users.
-
- The CHECKPOINT statement applies to the current database. Like the automatic
- checkpoint, it forces all dirty pages in the database to be written to disk.
-
-
- The CHECKPOINT statement is used in the following ways:
-
-
- ■ As a precautionary measure in special circumstances─for example, just
- before a planned restart so that SQL Server's recovery mechanisms
- won't have anything to recover.
-
- ■ To cause a change in database options to take effect after the
- database options have been reset. (See Chapter 9, "Fine-tuning
- Performance and Operations.")
-
- ■ To make a ROLLBACK TRANSACTION statement take effect when aborting a
- user-defined transaction in which a database option was changed.
-
-
-
- Dumping a Database or Transaction Log
-
- In case of media failure, you can recover your databases if you have been
- making regular backups of your databases and their transaction logs. These
- nonautomatic recovery mechanisms depend completely on the regular use of
- database dumps.
-
- Backup responsibility is usually assigned either to the SA or Database
- Owner. However, permission to dump a database or transaction log can be
- transferred by the Database Owner to other users. In any case, the user
- responsible should set up a regular backup schedule.
-
- There is no "best" schedule for backing up databases and transaction logs,
- but keep in mind that the frequency of your backups determines the largest
- amount of work that could possibly be lost if a media failure should occur.
- At installations with large and active databases, daily backups of the
- transaction log and weekly database backups are typical.
-
- You can dump a database or a transaction log while the database is active.
- This type of backup is known as a dynamic dump. The dynamic dump makes
- backups convenient and continuous operation possible.
-
- The dynamic dump slows SQL Server somewhat; you should execute it only when
- the database is not being heavily updated.
-
- ────────────────────────────────────────────────────────────────────────────
- WARNING
-
- Do not use an MS-DOS workstation when you are backing up a database or
- transaction log to diskettes. (Since the console utility program is not
- available under MS-DOS, you must use an MS OS/2 server or workstation to
- perform diskette backups.)
- ────────────────────────────────────────────────────────────────────────────
-
- As explained in Chapter 5, "Managing Storage," the SA is responsible for
- maintaining the transaction log. These are the steps involved:
-
-
- ■ Putting the transaction log into a separate database device. This is
- recommended for all databases and especially for databases larger than
- 4 megabytes.
-
- ■ Monitoring the transaction log with the sp_spaceused and sp_helpdb
- system procedures.
-
- ■ Keeping the transaction log at a reasonable size by regularly dumping
- (when the log is in a separate database device).
-
-
- The DUMP DATABASE statement executes a checkpoint internally. This forces
- all completed transactions to be written out. It then makes an exact image
- of the database, capturing it as it was the moment the DUMP statement was
- executed.
-
- However, any transactions that were not committed at the start of the dump
- will not appear in the database should it be subsequently loaded. Any
- changes made after the dump begins are not reflected in the image. Only
- pages containing data are dumped.
-
- While the dump is in progress, a change to a data or index page that has
- already been dumped has no effect on the dumped image and takes place
- immediately. If an update is requested on a page that has not yet been
- dumped, the system immediately dumps that page and only then makes the
- change. In other words, users writing a page during a dump have to wait for
- the dump to write the page first.
-
- Remember that each dump of a database or a transaction log overwrites the
- current contents of the disk or diskette dump device.
-
- The procedures described in the following sections apply to dumping both
- user databases and the master database. Reloading the master database is a
- special case that is discussed later in this chapter.
-
-
- When to Dump Databases
-
- It is recommended that you dump databases and transaction logs frequently
- and that you save the diskettes containing those dumps.
-
- The frequency of your dumps and the amount of time you should save the dump
- diskettes depend on your database application. As an example, a typical
- schedule is shown below:
-
- When to Perform What to Dump Minimum Time to Keep
- the Dump to Diskette Dump Diskettes
- ────────────────────────────────────────────────────────────────────────────
- Every day Transaction log Two weeks
-
- Every week Database and Two months
- transaction log
-
- Every month Database and Six months
- transaction log
-
- ────────────────────────────────────────────────────────────────────────────
-
-
-
- Dump Devices
-
- Dump devices are hard disk files or diskette files to which you dump
- databases. You can display a listing of all dump devices by executing the
- sp_helpdevice system procedure.
-
- In the report you get from sp_helpdevice, the ctrltype column shows the type
- of dump device. You can execute more than one dump at the same time, but
- only if you are dumping to devices with different cntrltypes.
-
- For instructions on how to add dump devices, refer to Chapter 5, "Managing
- Storage."
-
-
- Disk Dump Devices
-
- Disk dump devices are hard disk files. Dumping to a file on the same
- physical device as the database is not usually recommended; if the disk
- containing that file crashes, there is no way to recover the database.
- (However, you may want to dump to a hard disk file and then copy that file
- to a different medium, such as tape.) When dumping to a hard disk file, any
- existing contents of the file are overwritten.
-
- Only one dump or load to a disk dump device can be active at a time.
-
-
- Diskette Dump Devices
-
- Diskettes are suitable as dump devices since they permit a library of
- database and transaction log dumps to be kept off-line. A database can span
- several diskettes.
-
- The SAF or the console program is used to prompt you when a diskette is used
- as a dump device.
-
- Diskette dump devices must be located on the computer where SQL Server is
- running. That is, a diskette drive must be physically attached to that
- machine, and a dump device must be accessible on that machine.
-
- You cannot simultaneously dump multiple databases to the same diskette, but
- you can execute more than one dump or load at the same time to two diskette
- dump devices (assuming that the diskette dump devices have different
- controller numbers). You can execute sp_helpdevice to find diskette dump
- device controller numbers.
-
-
- Dumping a Database
-
- Dumping a database backs up an entire database─its system tables,
- user-defined objects, and transaction log (if the transaction log is in the
- same database device).
-
- When you dump a small database (less than 4 megabytes) that stores its
- transaction log on the same database device as the rest of the database, you
- back up both the database and the transaction log at the same time.
-
- With a larger database where you store the transaction log on a different
- database device than the one containing the rest of the database, you will
- probably want to back up the transaction log more frequently than you back
- up the database to capture changes made since the last database dump.
- Dumping the transaction log is discussed in "Dumping a Transaction Log,"
- later in this chapter. See Chapter 5, "Managing Storage," for more
- information.
-
-
- When to Dump a Database
-
- In addition to routine backups, it is important to dump a database at other
- times, as described in the following sections.
-
-
- After Creating a Database
-
- Each database should be dumped just after it is created to provide a base
- point, and on a fixed schedule thereafter. If, for example, you create a
- database on Monday and wait until the weekly Friday afternoon backup time to
- dump it, you risk losing a whole week's work if there's a media failure on
- Friday at noon. Transaction log dumps made between the creation of the
- database and the first database dump are of no use, since you must load them
- after having loaded a database dump.
-
-
- After Performing a Nonlogged Operation
-
- In addition to dumping each database on a fixed schedule, you must dump a
- database any time you perform an operation that is not logged. For example,
- dump a database
-
-
- ■ Every time you are forced to execute DUMP TRANSACTION WITH NO_LOG
- (because you've run out of disk space in the database).
-
- ■ Every time you enable the select into/bulkcopy option and do a "fast"
- bulk copy, or use the SELECT INTO statement to create a permanent
- table, or use the WRITETEXT statement.
-
- ■ Every time you use WRITETEXT, SELECT INTO on a permanent table, and
- "fast" bulk copy (because SQL Server does not log the data insertions
- made by these statements, there would be no way to recover them in
- case of media failure).
-
-
-
- After Creating an Index
-
- It is wise to dump the database each time you create a new index. The pages
- that are written when a new index is created are not recorded in the log;
- instead SQL Server relies on LOAD TRANSACTION to re-create the index in case
- of media failure. This does not mean that CREATE INDEX is unrecoverable, but
- that SQL Server takes just as long to recover the index as to create it in
- the first place. Since you will be using LOAD TRANSACTION after a media
- disaster, when time is likely to be of the essence, it is far better to have
- dumped the database so that you don't have to wait for the index to be
- rebuilt.
-
-
- When to Dump the master Database
-
- The master database is backed up in the same way as user databases and
- should be dumped regularly and frequently. It is important to make backups
- of master after each CREATE DATABASE, ALTER DATABASE, or DISK INIT statement
- is executed.
-
- The backups of the master database are used as part of the recovery
- procedure in case of a failure that affects the master database. If the
- master database is damaged, it is recovered differently than user databases.
- See "Restoring the master Database," later in this chapter.
-
-
- Dumping a Database Using the Admin Menu
-
- The procedure for dumping a database is slightly different depending on
- whether you are dumping to diskettes or to a hard disk.
-
- To dump a database:
-
-
- 1. If you are dumping to diskettes, make sure that you have enough
- formatted diskettes.
-
- 2. Select the Admin menu and choose Backup.
-
- The "Backup (Dump) Database" dialog box appears.
-
- 3. Select "Database".
-
- 4. Select the name of the database to be backed up from the "Database
- name" list box.
-
- 5. Select the name of the dump device to which the database will be
- backed up from the "Dump device" list box.
-
- 6. Choose OK.
-
- 7. If you are dumping the database to a diskette, follow the directions
- on the screen. These directions tell you when to insert diskettes.
-
- If you are dumping the database to a hard disk, the dump begins
- immediately.
-
-
-
- Dumping a Database Using System Procedures
-
- To dump a user database:
-
-
- 1. Make sure the dump device exists, or add it with sp_addumpdevice. (See
- Chapter 5, "Managing Storage," for details on adding a dump device.)
-
- 2. Make sure that the disk or diskette device you dump to or load from is
- attached to the same computer on which SQL Server is running.
-
- 3. For a diskette dump device, make sure that diskettes are formatted and
- not write-protected.
-
- 4. For a diskette dump device, make sure that someone is at the server to
- insert diskettes.
-
- 5. Execute the DUMP DATABASE statement from the SQL Query Window.
-
- If you are backing up to diskettes, follow these additional steps
-
- 6. Switch to a different screen group from the screen group where SAF is
- running.
-
- 7. Execute the console utility program. Its syntax is as follows:
-
- console [/S servername]
-
-
- The /S servername option is required only if you are executing console
- from a remote computer running MS OS/2.
-
- ────────────────────────────────────────────────────────────────────────────
- NOTE
-
- The console utility program is not available under
-
-
- 8. Follow the prompts in the console utility program, which tell you when
- to insert diskettes.
-
-
- The DUMP DATABASE statement has the following syntax:
-
- DUMP DATABASE database_name
- TO dump_device
-
- ────────────────────────────────────────────────────────────────────────────
- database_name
- The name of the database from which you are copying data
-
- dump_device
- The logical name of the dump device to which you are dumping the database
-
- ────────────────────────────────────────────────────────────────────────────
- Here's how you'd dump the pubs database to the diskettedumpa diskette:
-
- dump database pubs
- to diskettedumpa
-
- Permission to dump databases defaults to the Database Owner and can be
- transferred to other users.
-
-
- Dumping a Transaction Log
-
- The transaction log cannot be backed up separately from the database itself
- if it is stored in the same database device as the database. This is
- sometimes the situation with small databases (less than about 4 megabytes).
- If your database is larger than about 4 megabytes, the transaction log
- should be stored in a separate database device and backed up separately from
- the database.
-
- ────────────────────────────────────────────────────────────────────────────
- NOTE
-
- You should not dump a transaction log unless at least one previous dump of
- the database has been made.
- ────────────────────────────────────────────────────────────────────────────
-
- When the log is in a different database device, you can back it up
- separately from the rest of the database with the DUMP TRANSACTION
- statement. The backup copy can be read only by the LOAD TRANSACTION
- statement.
-
- Dumping a transaction log takes less time and uses less storage space than
- dumping a database. Typically, a transaction log dump is made much more
- frequently (possibly once a day) than a database dump (possibly once a
- week).
-
- A transaction log dump, like a database dump, can take place while the
- database is active.
-
- Two database options, select into/bulkcopy and trunc. log on chkpt., affect
- transaction log dumps. When either or both of these database options are set
- to true, you are not allowed to dump the transaction log because changes
- would not be recoverable. In this situation, executing the DUMP TRANSACTION
- statement produces an error message instructing you to use DUMP DATABASE
- instead.
-
- By default, these options are set to "false" in newly created databases. See
- Chapter 9, "Fine-tuning Performance and Operations," for information on
- database options.
-
-
- Dumping a Transaction Log Using the Admin Menu
-
- To dump a transaction log:
-
-
- 1. Select the Admin menu and choose Backup.
-
- The "Backup (Dump) Database" dialog box appears.
-
- 2. Select the "Transaction log" option button.
-
- 3. Select the name of the database whose transaction log will be backed
- up from the "Database name" list box.
-
- 4. Select the name of the dump device to which the transaction log will
- be backed up from the "Dump device" list box.
-
- 5. Choose OK.
-
- 6. If you are dumping the database to a diskette, follow the directions
- on the screen. These directions tell you when to insert diskettes.
-
- If you are dumping the database to a hard disk, the dump begins
- immediately.
-
-
-
- Dumping a Transaction Log Using System Procedures
-
- The DUMP TRANSACTION statement has the following syntax:
-
- DUMP TRANSACTION database_name
- [TO dump_device]
- [WITH TRUNCATE_ONLY]
- [WITH NO_LOG]
-
- ────────────────────────────────────────────────────────────────────────────
- TO dump_device
- The logical name of the dump device to which you are dumping the specified
- transaction log.
-
- The dump device name is optional if you use the WITH TRUNCATE_ONLY or WITH
- NO_LOG clause.
-
- WITH TRUNCATE_ONLY
- Removes the inactive part of the log without making a backup copy of it.
- This frees disk space used by the transaction log.
-
- WITH TRUNCATE_ONLY is used after you have backed up the entire database
- with DUMP DATABASE. The DUMP DATABASE statement backs up the log but does
- not remove the inactive portion of it. If you use WITH TRUNCATE_ONLY and
- do not have a backup created by DUMP DATABASE, the changes that had been
- recorded in the log are not recoverable.
-
- Since the WITH TRUNCATE_ONLY option does not perform a dump, you can use
- any dump device name.
-
- You cannot use both WITH TRUNCATE_ONLY and WITH NO_LOG in the same
- statement.
-
- WITH NO_LOG
- Used only when you have run out of space in the database so that you
- cannot even execute DUMP TRANSACTION WITH TRUNCATE_ONLY to retrieve some
- space from the log. Like WITH TRUNCATE_ONLY, WITH NO_LOG removes the
- inactive part of the log without making a backup copy of it. In addition,
- WITH NO_LOG saves space by not recording this procedure in the transaction
- log.
-
- After the transaction log has been dumped using WITH NO_LOG, the changes
- that had been recorded in the log are not recoverable. You should
- immediately execute DUMP DATABASE and then enlarge the database with ALTER
- DATABASE.
-
- You cannot use both WITH TRUNCATE_ONLY and WITH NO_LOG in the same
- statement.
-
- ────────────────────────────────────────────────────────────────────────────
- DUMP TRANSACTION removes committed transactions from the log after they are
- written to the dump device. DUMP DATABASE, on the other hand, does not.
-
- ────────────────────────────────────────────────────────────────────────────
- NOTE
-
- If you always use DUMP DATABASE (backing up the database and the log) and
- never use DUMP TRANSACTION, the transaction log will never be cleared out
- and will become very large. You can avoid this problem by setting the trunc.
- log on chkpt. option with sp_dboption.
- ────────────────────────────────────────────────────────────────────────────
-
- The DUMP TRANSACTION statement both removes the inactive portion of the log
- and makes a backup copy. The optional phrase WITH TRUNCATE_ONLY removes the
- inactive part of the log without making a backup copy of it.
-
- ────────────────────────────────────────────────────────────────────────────
- WARNING
-
- If you use WITH TRUNCATE_ONLY and do not have a backup of the transaction
- log created by DUMP DATABASE, the changes that had been recorded in the log
- are not recoverable.
- ────────────────────────────────────────────────────────────────────────────
-
- Each time you execute DUMP DATABASE, you should execute DUMP TRANSACTION
- WITH TRUNCATE_ONLY to clear out the log.
-
- The optional WITH NO_LOG clause is used only when you have run out of space
- in the database and cannot execute DUMP TRANSACTION WITH TRUNCATE_ONLY to
- retrieve space from the log. Like WITH TRUNCATE_ONLY, WITH NO_LOG removes
- the inactive part of the log without making a backup copy of it. In
- addition, WITH NO_LOG saves space by not recording this procedure in the
- transaction log.
-
- ────────────────────────────────────────────────────────────────────────────
- WARNING
-
- After the transaction log has been dumped using WITH NO_LOG, the changes
- that had been recorded in the log are not recoverable. You should
- immediately execute DUMP DATABASE and then enlarge the database with ALTER
- DATABASE.
- ────────────────────────────────────────────────────────────────────────────
-
-
- Truncating a Transaction Log
-
- Truncating a transaction log removes the inactive portion of the log. You
- usually truncate a transaction log after you have backed up an entire
- database. Backing up the database also backs up the log but does not remove
- the inactive portion of it.
-
-
- Truncating a Transaction Log Using the Admin Menu
-
- To truncate the transaction log for a specific database:
-
-
- 1. Select the Admin menu and choose Backup.
-
- The "Backup (Dump) Database" dialog box appears.
-
- 2. Select "Truncate log."
-
- 3. Select the name of the database whose transaction log will be
- truncated from the "Database name" list box.
-
- 4. Choose OK.
-
- The specified transaction log is truncated.
-
-
-
- Truncating a Transaction Log Using System Procedures
-
- Use the DUMP TRANSACTION statement to truncate a transaction log. See
- "Dumping a Transaction Log Using System Procedures," earlier in this
- chapter, for more information.
-
-
- Interactions between Backing Up a Database and Its Log
-
- You should not dump a transaction log unless at least one previous dump of
- the database has been made. Figure 8.1 shows the interaction between dumps
- of a database and dumps of its transaction log.
-
- (This figure may be found in the printed book.)
-
- If a media failure were to occur at 5:01 P.M. on Tuesday, all you would need
- to do (assuming that the media failure was not due to a hardware problem) is
- load Diskette set 5, which is a database dump that was made at 5:00 P.M. The
- only work lost would be whatever had been done in the minute between the
- database dump and the failure.
-
- But what if the failure occurred at 4:59 P.M. on Tuesday? In that case,
- you'd load Diskette set 1, the database dump that was made at 5 P.M. on
- Friday. Then you'd load Diskette sets 2, 3, and 4, the transaction dumps
- made since the last complete database dump.
-
- After all the transaction diskettes were loaded, the system would be in the
- exact state it had been in on Tuesday at 10 A.M., resulting in the loss of
- Tuesday's work. This example illustrates the need for frequent transaction
- log dumps.
-
-
- Loading a Database
-
- The real question is not whether you'll need your backups, but when. After a
- media crash, you restart SQL Server in the usual way. If SQL Server cannot
- access (USE) a database, it marks it as suspect, locks it, and displays a
- warning message. A damaged database must be dropped, either with the DROP
- DATABASE statement or with DBCC REPAIR DROPDB. At that point, the SA or
- Database Owner can load the most recent database dump (and any transaction
- logs).
-
-
- Loading a Database Using the Admin Menu
-
- To load a database:
-
-
- 1. Select the Admin menu and choose Restore.
-
- The "Restore (Load) Database" dialog box appears.
-
- 2. Select "Database."
-
- 3. Select the name of the database to be loaded from the "Database name"
- list box.
-
- 4. Select the name of the dump device from which the database will be
- loaded from the "Load device" list box.
-
- 5. Choose OK.
-
- 6. If you are loading the database from a diskette, follow the directions
- on the screen. These directions tell you when to insert diskettes.
-
- If you are loading the database to a hard disk, the load begins
- immediately.
-
-
-
- Loading a Database Using System Procedures
-
- The LOAD DATABASE statement is designed for user databases only. The master
- database is restored differently, as described later in this chapter.
-
- Loading a database locks it so that no one can modify it while recovery is
- in process. Users are free to access and modify other databases on SQL
- Server during this time.
-
- When SQL Server loads a database, it rolls back any uncommitted transactions
- that were active at the moment the dump began. When the load is complete,
- the database is in the same state it was in at the moment the DUMP statement
- was executed, minus any transactions that were active at that point.
-
- If a failure occurs while a database is being loaded, SQL Server does not
- recover the partially loaded database and notifies the SA. The database load
- must be restarted by reexecuting the LOAD statement.
-
- The LOAD DATABASE statement has the following syntax:
-
- LOAD DATABASE database_name
- FROM dump_device
-
- ────────────────────────────────────────────────────────────────────────────
- database_name
- The destination database. It can be either a newly created database with
- no data or an existing database. Loading dumped data to an existing
- database replaces existing data with the loaded data. The database into
- which you load a dumped database must be large enough to hold the dumped
- data.
-
- FROM dump_device
- The logical name of the dump device from which you are loading the
- database.
-
- ────────────────────────────────────────────────────────────────────────────
- The destination database must be large enough to hold the amount of storage
- space that was actually allocated to the dumped database. The actual amount
- of data the dumped database contains is irrelevant.
-
- Information on storage space allocated can be obtained with the DBCC
- CHECKALLOC statement.
-
-
- Loading a Transaction Log
-
- Loading a transaction log recovers as much of a database as possible in case
- of system failure.
-
- The backups of the transaction log must be loaded in the same sequence in
- which they were made. SQL Server checks the timestamps on each dumped
- database and each dumped transaction log to see that the sequence is
- correct.
-
- Loading a transaction log dump results in reexecution of the changes it
- contains and rolling back any transactions that were uncommitted when the
- transaction log was dumped. After the transaction log is loaded, the
- database is in the state it was in at the moment the log was dumped, minus
- any transactions that were active at that point. (The exception to this is
- the DUMP TRANSACTION statement itself, which by definition was active at
- that point. It is not rolled back. Rather, it is completed by the next LOAD
- TRANSACTION statement.)
-
- Thus, when the entire sequence of transaction log dumps has been loaded, the
- database is restored to its state at the time of the last transaction log
- dump (minus active transactions).
-
-
- Loading a Transaction Log Using the Admin Menu
-
- To load a transaction log:
-
-
- 1. Select the Admin menu and choose Restore.
-
- The "Restore (Load) Database" dialog box appears.
-
- 2. Select the "Transaction log" option button.
-
- 3. Select the name of the database whose transaction log will be loaded
- from the "Database name" list box.
-
- 4. Select the name of the dump device from which the transaction log will
- be loaded from the "Load device" list box.
-
- 5. Choose OK.
-
- 6. If you are loading the transaction log to a diskette, follow the
- directions on the screen. These directions tell you when to insert
- diskettes.
-
- If you are loading the transaction log to a hard disk, the load begins
- immediately.
-
-
-
- Loading a Transaction Log Using System Procedures
-
- The LOAD TRANSACTION statement has the following syntax:
-
- LOAD TRANSACTION database_name
- FROM dump_device
-
- ────────────────────────────────────────────────────────────────────────────
- database_name
- The name of the destination database.
-
- FROM dump_device
- The logical name of the dump device from which the transaction log is
- being loaded. LOAD TRANSACTION can be used only after the database has
- been restored from a backup made with the DUMP DATABASE statement. Once
- you've reloaded a database, you can load one or more transaction logs.
-
- ────────────────────────────────────────────────────────────────────────────
- Keeping Transaction Logs Small
-
- In a development environment, the most important system administration
- requirement may be to maximize the amount of space available in database
- devices at all times. In this situation, the ability to recover databases
- may not be as stringent a requirement as in a production environment.
-
- An SA can exercise various options for truncating the transaction logs of
- databases to keep them as small as possible. These options are as follows:
-
-
- ■ The DUMP TRANSACTION statement with the WITH TRUNCATE_ONLY option
-
- ■ The DUMP TRANSACTION statement with the WITH NO_LOG option
-
- ■ sp_dboption with the trunc. log on checkpoint option
-
-
- All three of these options truncate the log of a specified database without
- making a backup copy of the log.
-
- The trunc. log on chkpt. option of sp_dboption clears out the transaction
- log every time SQL Server initiates the checkpoint checking process (about
- once a minute). Set this option only if the log is in the same file as the
- database so that you are always dumping entire databases or if you don't
- care about recovering from a media crash. If you plan to dump the complete
- database and never to dump the transaction log alone, you should also
- consider setting this option.
-
- If you leave the trunc. log on chkpt. option off (the default condition) and
- never dump the transaction log, it will continue to grow and you may run out
- of space in your database.
-
-
- If You Run Out of Space in a Database
-
- If you run out of space in a database, execute the DUMP TRANSACTION
- statement with the WITH TRUNCATE_ONLY option or (if you've also run out of
- space in the log) with the WITH NO_LOG option to recover space occupied by
- the log. Then immediately dump the database. You can subsequently use ALTER
- DATABASE to extend your database onto another database device.
-
- The null device name diskdump can be used with either of the DUMP
- TRANSACTION statements.
-
- Setting the trunc. log on chkpt. option is a sure way to save space, but it
- means that you can only recover the state of the database as it was at the
- last database dump.
-
-
- Moving a Database
-
- You can use the DUMP and LOAD statements to move a database to another
- database device. The procedure follows:
-
-
- 1. Make sure the new database device is listed in sysdevices.
-
- 2. Dump the database.
-
- 3. Use the DROP DATABASE statement to remove the old database.
-
- 4. Use the CREATE DATABASE statement to create the new database, and
- specify the new database device.
-
- 5. Use the LOAD DATABASE statement to load the database from the backup.
-
-
- To move a database to another server, follow the same procedure. However, if
- the syslogins table on the new server is different than the old one, the
- ownership of databases and database objects will be incorrect. Use aliases
- to map owners to their objects on the new SQL Server.
-
-
- Restoring the master Database
-
- The procedure to recover a damaged master database is different than for
- recovery of user databases. A damaged master database makes itself known
- either with an inability to start SQL Server, by segmentation faults or
- input/output errors, and/or in a report from DBCC. It can be caused by a
- media failure in the area in which master is stored.
-
- If the master database becomes unusable, it must be restored from a previous
- dump. All changes made to the master database after the last dump will be
- lost when the dump is reloaded. They must be reapplied.
-
- Therefore, it is strongly recommended that the master database be backed up
- each time it is changed. This is best accomplished by prohibiting the
- creation of user-defined objects in master and by being aware of the
- statements and system procedures that modify it. The most common are as
- follows:
-
-
- ■ DISK INIT, sp_addumpdevice, and sp_dropdevice
-
- ■ CREATE DATABASE and ALTER DATABASE
-
- ■ sp_addlogin and sp_droplogin
-
-
- Changes such as adding or dropping a dump device, or adding or deleting a
- login ID can be reapplied manually or with batch files.
-
- Changes using DISK INIT, CREATE DATABASE, and ALTER DATABASE are far more
- serious. If a user database is created or expanded after the most recent
- dump of the master database and if it becomes necessary to reload the master
- database, then the user database and all of the data in it will be lost.
- This is why the master database should be dumped after the creation or
- expansion of user databases.
-
- To restore a damaged master database, the SA must follow these steps:
-
-
- 1. Rebuild the master database with the bldmastr program. (See the next
- section, "Building the master Database.")
-
- 2. Start SQL Server in single-user mode. (See "Starting SQL Server in
- Single-User Mode," later in this chapter.)
-
- 3. Add a dump device if the dump was not made to diskettes. (See "Adding
- a Dump Device," later in this chapter.)
-
- 4. Reload the master database from the most recent dump. (See "Reloading
- the master Database," later in this chapter.)
-
- 5. Apply changes (if any) not included in the most recent dump. (See
- "Applying Changes," later in this chapter)
-
-
-
- Building the master Database
-
- If the MS OS/2 file containing master is physically intact, you can rebuild
- the master database without altering configuration (or other) data. Execute
- bldmastr with the /d and /m options, as follows:
-
- bldmastr /d c:\sql\data\master.dat /m
-
- "c:\sql\data\master.dat" is the physical filename of the master database
- device.
-
- If the MS OS/2 file containing master is unusable due to media failure, you
- must create a completely new master.dat file and execute bldmastr. For
- example, to rebuild a new non-case-sensitive master database with a size of
- 15 megabytes, execute bldmastr as follows:
-
- bldmastr /d c:\sql\data\master.dat /s 7680 /C
-
- ────────────────────────────────────────────────────────────────────────────
- /d
- Specifies the physical filename of the master database device
-
- /s
- Specifies the size in 2K blocks (10 megabytes = 5120 2K blocks)
-
- /C
- Specifies non-case-sensitive (optional)
-
- ────────────────────────────────────────────────────────────────────────────
- See the SQL Server Language Reference for complete information on the
- bldmastr utility program.
-
-
- Starting SQL Server in Single-User Mode
-
- Start SQL Server in single-user mode by executing sqlservr as follows:
-
- sqlservr /d c:\sql\data\master.dat /m
-
- ────────────────────────────────────────────────────────────────────────────
- /d
- Specifies the physical filename of the master database device
-
- /m
- Specifies single-user mode
-
- ────────────────────────────────────────────────────────────────────────────
- You can execute sqlservr from the server or from a workstation.
-
-
- Adding a Dump Device
-
- If the dump of master was made to a hard disk rather than to a diskette, you
- must add a dump device with sp_addumpdevice before performing the load. To
- do this, you must first load the stored procedures.
-
- Load the stored procedures from the instmstr.sql batch file using isql.
-
- isql /U sa /P /i c:\sql\install\instmstr.sql
-
- When this is done, use isql to add the dump device as follows:
-
- isql /U sa /P
- sp_addumpdevice 'disk', 'logical_name', 'physical_name', 2
-
- ────────────────────────────────────────────────────────────────────────────
- logical_name
- The logical name of the disk dump device
-
- physical_name
- The physical name of the MS OS/2 file that contains the dump of master
-
- 2
- The controller type (2 = hard disk)
-
- ────────────────────────────────────────────────────────────────────────────
- Reloading the master Database
-
- Reload the most recent dump of the master database using the LOAD DATABASE
- statement. The server must be in single-user mode for this statement to
- operate on master. When the load of master is complete, the server
- automatically shuts itself down.
-
- Unless it has been changed by the SA, the master database does not have a
- separate transaction log device, and no special action is required to load
- it.
-
- If the master database has been changed to use a separate log device and if
- that transaction log has been dumped after the most recent dump of the
- master database, then you must reload the transaction log for the master
- database. The server must be shut down to do this. Use the LOAD TRANSACTION
- statement to load the transaction log.
-
-
- Applying Changes
-
- If there have been no changes to the master database since the last dump,
- then you are done. Restart the server in multiuser mode.
-
- If login IDs or devices have been added to or dropped from the master
- database since the last dump, those changes must be reapplied. Restart the
- server and reapply the changes manually or from saved batch files.
-
- If databases have been created or expanded since the last dump of master,
- those databases must be re-created and all of data contained in them must be
- reentered. This can be done manually, from saved batch files, or by
- reloading dumps of those databases after they have been re-created.
-
- If you have made many changes and have no recent dump, it is possible in
- some cases to regain data in user databases that has been lost by reloading
- master. The technique requires the use of DISK REINIT and DISK REFIT and may
- involve manual modifications to master database tables. If you feel this
- technique is necessary, contact your vendor's technical support before
- beginning the recovery process.
-
- The safest approach is to always dump the master database after creating or
- altering databases.
-
- After all the changes since the last dump of master have been applied,
- restart the server in multiuser mode.
-
-
- Recovering from Media Failure
-
- To recover user databases from media failure, re-create the lost devices and
- then load the affected databases from backups. Anything done after the
- backups were created must be reapplied.
-
-
- Re-creating Lost Devices and Reloading Lost Databases
-
- To restore a backup, the target database must already exist. It doesn't have
- to occupy the same devices, but it must have enough space allocated to hold
- the information in that database at the time it was dumped.
-
- To re-create the lost devices:
-
-
- 1. Start SQL Server in single-user mode.
-
- 2. Execute the DISK REFIT statement.
-
- DISK REFIT drops entries in the sysusages table that can no longer be
- physically accessed and drops the related sysdatabases entries.
-
- 3. Drop sysusages entries related to databases that have been dropped:
-
- DELETE FROM SYSUSAGES WHERE DBID NOT IN
- (SELECT DBID FROM SYSDATABASES)
-
-
- 4. Drop lost devices using the sp_dropdevice system procedure.
-
- 5. Execute CHECKPOINT, shut down SQL server, and then start in normal
- mode.
-
- 6. Re-create lost devices by executing the DISK INIT statement using the
- virtual device number (VDEVNO) and size of the original devices. (If
- you do not know the virtual device number and size of the original
- devices, see the next section, "Finding Information on Lost Devices
- and Databases.")
-
-
- To re-create and reload the affected databases:
-
-
- 1. Re-create affected databases using the same size and device assignment
- as the original databases. (If you do not know the size and device
- assignment, see the next section, "Finding Information on Lost Devices
- and Databases.")
-
- 2. Assign log devices, if necessary, with the sp_logdevice system
- procedure.
-
- 3. Load the affected databases and transaction logs from the latest
- backups.
-
-
-
- Finding Information on Lost Devices and Databases
-
- If the virtual device number and size of the original devices are not known,
- they can be derived from the sysdevices, sysdatabases, and sysusages tables
- in the master database.
-
- The virtual device number (VDEVNO) and device size can be derived from the
- low and high columns in sysdevices. VDEVNO is low divided by 16777216.
- Device size ishigh - low (2K blocks).
-
- The size and device assignment of databases can be derived from the
- sysdevices, sysusages, and sysdatabases tables. Each chunk of disk space
- assigned to a database is represented by a row in the sysusages table. The
- size of each chunk is in the row. The dbid of the database to which the
- chunk is assigned is also in the row, and the corresponding database name
- can be obtained from sysdatabases. The device containing the chunk of disk
- space can be deduced by noticing which low/high range in sysdevices contains
- the starting virtual address (VSTART) specified in the sysusages table.
-
- To determine whether a device is a log device, look at the value of segmap
- in sysusages. The value "7" indicates log and data, "4" indicates log only,
- and "3" indicates data only.
-
-
- Examples of Recovery from Media Failure
-
- The following examples assume two user databases in addition to the master
- database and two database devices in addition to the master database device.
- Device 1 is 4 megabytes and was created first (VDEVNO = 1), while device 2
- is 6 megabytes and was created after device 1 (VDEVNO = 2). User database 1
- was allocated 2 megabytes on device 1, 2 megabytes on master.dat, and a
- 1-megabyte log on device 2. User database 2 was allocated 2 megabytes on
- device 2 and 2 megabytes on device 1.
-
-
- Example 1: One Device Lost; Other Devices Intact
-
- For this example, assume that user database device 1 has been lost and the
- other devices are intact.
-
- Follow these steps:
-
-
- 1. Start SQL Server in single-user mode (use the -m option).
-
- 2. Execute the DISK REFIT statement. All entries in the sysusages table
- that were allocated on device 1 are dropped. User database 1 is also
- dropped because its first entry in the sysusages table was dropped.
- The other entries in the sysusages table for databases 1 and 2 that
- were allocated on device 2 and master.dat are not dropped, even though
- they relate to the dropped database.
-
- 3. Drop the remaining sysusages entries that relate to the dropped
- database.
-
- 4. Drop device 1 using the sp_dropdevice system procedure.
-
- 5. Execute CHECKPOINT, shut down SQL Server, and then start SQL Server in
- normal mode.
-
- 6. Re-create device 1 by executing the DISK INIT statement with a size of
- 4 megabytes and a virtual device number (VDEVNO) of 1.
-
- 7. Re-create user database 1 with 2 megabytes on device 1, 2 megabytes on
- master.dat, and 1 megabyte on device 2. Re-create user database 2 with
- 2 megabytes on device 2 and 2 megabytes on device 1.
-
- 8. Designate the log for database 1 using the sp_logdevice system
- procedure.
-
- 9. Load database 1 and its transaction log from backup. Load database 2
- from backup.
-
-
-
- Example 2: User Devices Lost; master.dat Intact
-
- For this example, assume that both user database devices have been lost and
- master.dat is intact.
-
- Follow these steps:
-
-
- 1. Start SQL Server in single-user mode (using the -m option).
-
- 2. Execute the DISK REFIT statement. All entries in the sysusages table
- that were allocated on devices 1 and 2 are dropped. User databases 1
- and 2 are also dropped because their first entries in the sysusages
- table were dropped. The single sysusages entry for database 1 that was
- allocated on master.dat is not dropped, even though it relates to a
- dropped database.
-
- 3. Drop the remaining sysusages entry that relates to database 1.
-
- 4. Drop devices 1 and 2 using the sp_dropdevice system procedure.
-
- 5. Execute CHECKPOINT, shut down SQL Server, and then start in normal
- mode.
-
- 6. Re-create device 1 by executing the DISK INIT statement with a size of
- 4 megabytes and a virtual device number (VDEVNO) of 1. Re-create
- device 2 by executing the DISK INIT statement with a size of 6
- megabytes and a virtual device number (VDEVNO) of 2.
-
- 7. Re-create user database 1 with 2 megabytes on device 1, 2 megabytes on
- master.dat, and 1 megabyte on device 2. Re-create user database 2 with
- 2 megabytes on device 2 and 2 megabytes on device 1.
-
- 8. Designate the log for database 1 using the sp_logdevice system
- procedure.
-
- 9. Load database 1 and its transaction log from backup. Load database 2
- from backup.
-
-
-
- Example 3: All Devices Lost
-
- For this example, assume that all three database devices have been lost. In
- this case, master.dat must be restored first.
-
- Follow these steps:
-
-
- 1. Run bldmastr to re-create master.dat using the original size and
- case-sensitivity option.
-
- 2. Start SQL Server in single-user mode and restore the latest backup of
- the master database. If your dump of master was made with a
- user-supplied dump device, that dump device must be re-added to the
- sysdevices table before the restore can take place.
-
- The quickest way to do this is to insert a row into sysdevices. It can
- also be done with the sp_addumpdevice system procedure, but that
- method requires the instmstr.sql script to be run first to re-add the
- stored procedures.
-
- The server shuts itself down when the restore is complete.
-
- 3. Re-create device 1 by executing the DISK INIT statement with a size of
- 4 megabytes and a virtual device number (VDEVNO) of 1. Re-create
- device 2 by executing the DISK INIT statement with a size of 6
- megabytes and a virtual device number (VDEVNO) of 2.
-
- 4. Re-create user database 1 with 2 megabytes on device 1, 2 megabytes on
- master.dat, and 1 megabyte on device 2. Re-create user database 2 with
- 2 megabytes on device 2 and 2 megabytes on device 1.
-
- 5. Designate the log for database 1 using the sp_logdevice system
- procedure.
-
- 6. Load database 1 and its transaction log from backup. Load database 2
- from backup.
-
-
-
-
-
-
-
- Chapter 9 Fine-tuning Performance and Operations
- ────────────────────────────────────────────────────────────────────────────
-
-
- Introduction
-
- Once an application is up and running, the SA will want to monitor its
- performance, and may want to customize and fine-tune it. SQL Server provides
- software tools for these purposes.
-
- This chapter explains how to
-
-
- ■ Tune queries and stored procedures
-
- ■ Set a variety of database options
-
- ■ Monitor SQL Server activity
-
- ■ Ensure that SQL Server makes the best use of existing indexes with the
- UPDATE STATISTICS statement.
-
- ■ Set configuration options
-
-
-
- Setting Query Options
-
- The query options allow you to instruct SQL Server to handle queries and
- stored procedures in a variety of ways. These options are turned on or off
- for the duration of the user's work session with the SET statement. No
- permissions are required for using the SET statement.
-
- The SET statement has the following syntax:
-
- SET
- {{ ARITHABORT | ARITHIGNORE |
- NOCOUNT | NOEXEC |
- OFFSETS {keyword_list} | PARSEONLY | PROCID |
- SHOWPLAN | STATISTICS IO | STATISTICS TIME }
- {ON | OFF} |
- ROWCOUNT number | TEXTSIZE n}
-
- ────────────────────────────────────────────────────────────────────────────
- ARITHABORT
- Aborts a query when an overflow or divide-by-zero error occurs during
- query execution.
-
- ARITHIGNORE
- Returns NULL when an overflow or divide-by-zero error occurs during a
- query. No warning message is displayed. If neither ARITHABORT nor
- ARITHIGNORE is set, SQL Server returns NULL and prints a warning message
- after the query is executed.
-
- NOCOUNT
- Turns off the message returned at the end of each statement that tells you
- how many rows were affected by the statement. The global variable
- @ROWCOUNT is updated even when NOCOUNT is set.
-
- NOEXEC
- Compiles each query but does not execute it. NOEXEC is often used with
- SHOWPLAN. Once NOEXEC is set, no subsequent statements are executed
- (including other SET statements) until NOEXEC is turned off.
-
- OFFSETS keyword_list
- Returns the offset (position in relation to the beginning of the query) of
- specified keywords in SQL statements. The keyword list is a list,
- separated with commas, that can include any of the following SQL
- statements: SELECT, FROM, ORDER, COMPUTE, TABLE, PROCEDURE, STATEMENT,
- PARAM, and EXECUTE.
-
- PARSEONLY
- Checks the syntax of each query and returns any error messages without
- generating a sequence tree, compiling, or executing the query. PARSEONLY
- returns offsets if the OFFSETS option is set and there are no errors.
-
- PROCID
- Returns the ID number of the stored procedure to DB-LIBRARY (not to the
- user) before sending rows generated by that stored procedure.
-
- SHOWPLAN
- Generates a description of the processing plan for the query and
- immediately processes it unless NOEXEC is set.
-
- STATISTICS IO
- Displays the number of scans, the number of logical reads (pages
- accessed), and the number of physical reads (disk accesses) for each table
- referenced in the statement; STATISTICS IO displays the number of pages
- written for each statement.
-
- STATISTICS TIME
- Displays the time it took to parse and compile each statement and the time
- it took to execute each step of the statement. Times are given in
- timeticks. Each timetick in MS OS/2 is 31.25 milliseconds (1/32 second).
-
- ROWCOUNT number
- Causes SQL Server to stop processing the query after the specified number
- of rows are returned. To turn this option off so that all rows are
- returned, use "SET ROWCOUNT 0".
-
- TEXTSIZE n
- Specifies the size (in bytes) of text type data to be returned with a
- SELECT statement. The @TEXTSIZE global variable stores the current
- setting.
-
- ────────────────────────────────────────────────────────────────────────────
- The SET options are divided into four categories:
-
-
- ■ PARSEONLY, NOEXEC, SHOWPLAN, BACKGROUND, ROWCOUNT, and NOCOUNT control
- the way a query is executed. It doesn't make sense to set both
- PARSEONLY and NOEXEC.
-
- The default setting for ROWCOUNT and TEXTSIZE is 0 (return
- everything); the default for the others is OFF.
-
- ■ The STATISTICS IO and STATISTICS TIME options display performance
- statistics after each query. The default setting for these options is
- OFF.
-
- ■ ARITHABORT and ARITHIGNORE handle exceptional cases during query
- execution. You cannot set both ARITHABORT and ARITHIGNORE. The default
- setting for these options is OFF.
-
- ■ OFFSETS and PROCID are used by application programs to interpret
- results from SQL Server. The default setting for these options is ON.
-
-
- If you use the SET statement inside a trigger or stored procedure, the
- option reverts to its former setting after the trigger or procedure
- executes.
-
- The following statement causes SQL Server to return a description of the
- processing plan for each query but not execute it:
-
- set showplan on
- <execute>
- set noexec on
- <execute>
-
- This statement causes SQL Server to stop processing each query after it
- returns the first ten rows:
-
- set rowcount 10
-
- Any options set with a SET statement take effect at the end of the batch.
- You can combine SET statements and queries in the same batch, but the SET
- options won't apply to the queries in that batch. Since this batch contains
- a SET statement and a query, the SET option doesn't take effect:
-
- set showplan on
- select * from publishers
- <execute>
-
- pub_id pub_name city state
- ----- -------------------- -------- -----
- 0736 New Age Books Boston MA
- 0877 Binnet & Hardley Washington DC
- 1389 Algodata Infosystems Berkeley CA
-
- (3 rows affected)
-
- If the two statements are put into separate batches, here's what happens:
-
- set showplan on
- <execute>
- select * from publishers
- <execute>
-
- STEP 1
- The type of query is SELECT
- FROM TABLE
- publishers
- Nested iteration
- Table Scan
-
- pub_id pub_name city state
- ------ --------------------- ---------- ------
- 0736 New Age Books Boston MA
- 0877 Binnet & Hardley Washington DC
- 1389 Algodata Infosystems Berkeley CA
-
- (3 rows affected)
-
-
- Setting and Changing Database Options
-
- You can set a number of database options for each database and change them
- as necessary.
-
- The sp_dboption system procedure is used both to display and to change a
- series of database options. None of the master database's option settings
- can be changed: only user database's options can be changed. However, to
- change a database option in a user database (or to display a list of the
- database options), sp_dboption must be executed while using the master
- database.
-
- The sp_dboption system procedure has the following syntax:
-
- sp_dboption [dbname, optname, {true | false}]
-
- ────────────────────────────────────────────────────────────────────────────
- dbname
- The name of the database in which you want to set the option. You must be
- using master to execute sp_dboption with parameters (that is, to change a
- database option). However, the database name cannot be master; you cannot
- change master's database options.
-
- optname
- The name of the option you want to set or turn off. SQL Server understands
- any unique string that is part of the option name. Use quotation marks
- around the option name if it includes embedded blanks.
-
- true, false
- Use true if you want to set the option and false if you want to turn off
- the option.
-
- ────────────────────────────────────────────────────────────────────────────
- To make an option or options take effect for every new database, change the
- option in the model database.
-
- The following database options are available:
-
- ────────────────────────────────────────────────────────────────────────────
- dbo use only
- When this option is set, only the Database Owner can use the database.
-
- no chkpt on recovery
- When this option is set, an up-to-date copy of a database is kept. In
- these situations, there is a "primary" and a "secondary" database.
- Initially, the primary database is dumped and loaded into the secondary
- database. Then, at intervals, the transaction log of the primary database
- is automatically dumped and loaded into the secondary database.
-
- If this option is turned off─the default condition─a checkpoint record is
- added to the database after it is recovered due to restarting SQL Server.
- This checkpoint, which ensures that the recovery mechanism won't
- unnecessarily be rerun, changes the sequence number on the database. If
- the sequence number on the secondary database has changed, a subsequent
- dump of the transaction log from the primary database could not be loaded
- into it.
-
- Setting this option for the secondary database causes it not to get a
- checkpoint from the recovery process so that subsequent transaction log
- dumps from the primary database can be loaded into it.
-
- read only
- When this option is set, you can retrieve data from the database but can't
- modify anything.
-
- select into/bulkcopy
- When this option is set, you can perform nonlogged operations: the
- WRITETEXT statement, the SELECT INTO statement, or the bcp utility
- program. By default, tables with no indexes are copied with the fast
- version of bcp, which means that these operations are not logged to save
- time. You do not have to set the select into/bulkcopy option to select
- into a temporary table since the tempdb temporary database is never
- recovered anyway. The option need not be set to run bcp on a table that
- has indexes because inserts are logged.
-
- When the select into/bulkcopy option is set, you are not allowed to dump
- the transaction log. In this situation, executing the DUMP TRANSACTION
- statement produces an error message instructing you to use DUMP DATABASE
- instead.
-
- By default, the select into/bulkcopy option is off in newly created
- databases. To change the default, set this option in the model database.
-
- single user
- When this option is set, only one user at a time can access the database.
-
- trunc. log on chkpt.
- When this option is set, the transaction log is truncated (committed
- transactions are removed) every time the CHECKPOINT checking process
- occurs (usually more than once per minute).
-
- It may be useful to set this option while doing development work during
- which backups of the transaction log are not needed. If this option is off
- (the original default condition) and the transaction log is never dumped,
- the transaction log will continue to grow, and you may run out of space in
- your database.
-
- While the trunc. log on chkpt. option is set, you cannot dump the
- transaction log because the log is being truncated, and changes therefore
- are not recoverable from transaction log dumps. In this situation,
- executing the DUMP TRANSACTION statement produces an error message
- instructing you to use DUMP DATABASE instead.
-
- By default, the trunc. log on chkpt. option is off in newly created
- databases. To change the default, set this option in the model database.
-
- ────────────────────────────────────────────────────────────────────────────
- For a report on which database options are set in a particular database,
- execute the sp_helpdb system procedure in that database.
-
- Only the SA and Database Owner can change a user database's options by
- executing sp_dboption while using the master database. Then, for the change
- to take effect, the CHECKPOINT statement must be executed while using the
- database for which the option was changed.
-
- Remember that none of the master database's options can be changed.
-
- Here's how you'd use the read only option with sp_dboption to change the
- pubs database:
-
- use master
- <execute>
- sp_dboption pubs, "read only", true
- <execute>
- Execute the CHECKPOINT statement in the database that was changed.
- use pubs
- <execute>
- checkpoint
- <execute>
-
- For the optname parameter, SQL Server understands any unique string that is
- part of the option name. To set the trunc. log on chkpt. option, execute
- this statement:
-
- use master
- <execute>
- sp_dboption pubs, trunc, true
-
- If you enter a value for optname that is ambiguous, an error message is
- displayed. For example, two of the database options are dbo use only and
- read only. Using "only" for the optname parameter generates an error message
- because it matches both names. The complete names that match the supplied
- string are printed out so that you can see how to make the optname more
- specific.
-
- More than one database option can be set at a time.
-
- If you change a database option with sp_dboption inside a user-defined
- transaction and then roll back that transaction, you must execute a
- CHECKPOINT statement to make the rollback take effect. Here's an example:
-
- begin tran
- use master
- <execute>
- sp_dboption 'orderentry', 'single', 'true'
- <execute>
- use orderentry
- <execute>
- checkpoint
- <execute>
- rollback tran
- <execute>
- /*
- ** If the following checkpoint is not executed, the
- ** orderentry database remains single-user.
- */
- checkpoint
- <execute>
-
-
- Displaying Information on Database Options
-
- All users with access to the master database can execute sp_dboption with no
- parameters to display a list of database options. The report from
- sp_dboption looks like this:
-
- sp_dboption
-
- Settable database options.
- database_options
- --------------------
- ALL SETTABLE OPTIONS
- dbo use only
- no chkpt on recovery
- read only
- select into/bulkcopy
- single user
- trunc. log on chkpt.
-
- (7 rows affected)
-
-
- Monitoring SQL Server Activity
-
- SQL Server keeps track of how much work it has done in a series of
- predefined global variables. Global variables are distinguished from local
- variables by having two "at" signs (@) preceding their names, for example,
- @ERROR and @ROWCOUNT.
-
- You can query the global variables directly or execute sp_monitor to display
- the current values of some of these global variables and how much they have
- changed since the last time the procedure was executed.
-
- The sp_monitor system procedure takes no parameters. Here's how you use it
- and a sample report from it:
-
- sp_monitor
-
- last_run current_run seconds
- ------------------- ------------------------- -----------
- Jan 29 1987 10:11AM Jan 29 1987 10:17AM 314
-
- cpu_busy io_busy idle
- -------------- --------- -------------
- 4250(215)-68% 67(1)-0% 109(100)-31%
-
- pack_received pack_sent packet_errors
- ------------- ------------ ----------------
- 781(15) 10110(9596) 0(0)
-
- total_read total_write total_errors connections
- ------------ ------------- ------------- ------------
- 394(67) 5392(53) 0(0) 15(1)
-
- (0 rows affected)
-
- For each column, the statistic is printed in the form number(number)-number%
- or number(number). The first number refers to the number of seconds (for
- cpu_busy, io_busy, and idle) or the total number (for the other variables)
- since SQL Server was restarted. The number in parentheses refers to the
- number of seconds or total number since the last time sp_monitor was
- executed. The percentage is the percent of time since sp_monitor was last
- executed.
-
- For example, this report shows cpu_busy as 4250(215)-68%. This means that
- the CPU has been busy 4250 seconds since SQL Server was last started and 215
- seconds since sp_monitor was last executed. The 68% means that the CPU has
- been busy 68% of the time since sp_monitor was last executed.
-
- For the total_read variable, the value 394(67) means there have been 394
- reads since SQL Server was restarted, 67 of them since the last time
- sp_monitor was run.
-
- The sp_monitor report has the following columns:
-
- ────────────────────────────────────────────────────────────────────────────
- last_run
- The clock time at which sp_monitor was last executed
-
- current_run
- The current clock time
-
- seconds
- The number of seconds since sp_monitor was last executed
-
- cpu_busy
- The number of milliseconds in CPU time that SQL Server's CPU was doing SQL
- Server work
-
- io_busy
- The number of milliseconds in CPU time that SQL Server has spent doing
- input and output operations
-
- idle
- The number of milliseconds in CPU time that SQL Server has been idle
-
- pack_received
- The number of input packets read by SQL Server
-
- pack_sent
- The number of output packets written by SQL Server
-
- packet_errors
- The number of errors detected by SQL Server while reading and writing
- packets
-
- total_read
- The number of disk reads by SQL Server
-
- total_write
- The number of disk writes by SQL Server
-
- total_errors
- The number of errors detected by SQL Server while reading and writing
-
- connections
- The number of logins or attempted logins to SQL Server
-
- ────────────────────────────────────────────────────────────────────────────
- With the exception of last_run, current_run, and seconds, all these column
- headings are also the names of global variables─except that all global
- variables are preceded by @. There is also a difference in the units of the
- numbers reported by the global variables; the numbers reported by the global
- variables are not milliseconds of CPU time, but ticks. Each tick on MS OS/2
- is 31.25 milliseconds (1/32 second).
-
- Here's how you'd query a global variable directly:
-
- ╓┌───────────────────┌───────────────────────────────────────────────────────╖
- ────────────────────────────────────────────────────────────────────────────
- select @cpu_busy
-
- ------------
- 4250
-
- (1 row affected)
-
-
- There are some other global variables whose values are not reported by
- sp_monitor. They are as follows:
-
- ────────────────────────────────────────────────────────────────────────────
- @@ERROR
- The last return code generated by your process. The @ERROR global variable
- is commonly used to check the error status (succeeded or failed) of the
- most recently executed statement. A statement such as "if @error != 0
- return" would cause an exit if an error had occurred.
-
- @@ROWCOUNT
- The number of rows affected by your last statement.
-
- @@PROCID
- The stored procedure ID of the currently executing procedure.
-
- @@NESTLEVEL
- The nesting level of the current execution (initially zero). Each time a
- stored procedure calls another stored procedure, the nesting level is
- incremented. If the maximum of 32 is exceeded, the transaction aborts.
-
- @@VERSION
- The date of the current version of SQL Server.
-
- @@TRANCOUNT
- The number of currently active transactions for the current user.
-
- @@TIMETICKS
- The number of microseconds per tick.
-
- @@MAX_CONNECTIONS
- The maximum number of simultaneous connections that can be made with SQL
- Server in this computer environment. The user can configure SQL Server for
- fewer connections with sp_configure.
-
- @@TEXTSIZE
- The size (in bytes) of text or image data to be returned with a SELECT
- statement.
-
- ────────────────────────────────────────────────────────────────────────────
- Any user can query the global variables. However, only the SA can execute
- sp_monitor because the procedure updates a table in the master database
- called spt_monitor.
-
-
- Updating Statistics
-
- The UPDATE STATISTICS statement helps SQL Server make the best decisions
- about which indexes to use when it processes a query by keeping it up to
- date about the distribution of the key values in the indexes. You should use
- this statement when you create an index on already existing data or when a
- large amount of data in an indexed column has been added, changed, or
- deleted.
-
- Permission to execute the UPDATE STATISTICS statement defaults to the table
- owner and cannot be transferred. The UPDATE STATISTICS statement has the
- following syntax:
-
- UPDATE STATISTICS table_name [index_name]
-
- If you do not specify an index name, the statement updates the distribution
- statistics for all the indexes in the specified table. Giving an index name
- updates statistics for that index only.
-
- You can find the name of the indexes by using the sp_helpindex system
- procedure. This procedure takes a table name as a parameter.
-
- To list the indexes for the authors table and then update the statistics for
- all of the indexes in the table, type
-
- sp_helpindex authors
- update statistics authors
-
- To update the statistics for the index on the au_id column only, type
-
- update statistics authors auidind
-
- Since TRANSACT-SQL does not require index names to be unique in a database,
- you must give the name of the table with which the index is associated.
-
-
- Locking and the HOLDLOCK Keyword
-
- To prevent other users from interfering with data being used for an active
- transaction, SQL Server protects the relevant tables or data pages of the
- database by locking them. Locking is a concurrency control mechanism. It is
- necessary in a multiuser environment since several users may be working with
- the same data at the same time.
-
- SQL Server handles locking decisions on its own. It always applies exclusive
- locks for data modification operations (UPDATE, INSERT, or DELETE). When an
- exclusive lock is set, no other transaction can acquire a lock of any kind
- on those objects until the original lock is released at the end of the
- transaction. The data modification statements are sometimes called "write"
- operations because they add, remove, or modify data.
-
- For nonupdate or "read" operations, such as SELECT, SQL Server applies
- shared locks. If a shared lock has been applied to a table or data page,
- other transactions can also acquire a shared lock even though the first
- transaction hasn't completed. However, no transaction can acquire an
- exclusive lock until all shared locks on it have been released. That is,
- many transactions can simultaneously read the table or page, but no one can
- write to it.
-
- Conversely, if a transaction has an exclusive lock, another transaction
- can't acquire a shared lock on it. Exclusive locks and shared locks can be
- applied either at the table level or at the page level─a data page or a leaf
- page of an index.
-
-
- Displaying Information on Locking
-
- To get a report on the locks currently being held on SQL Server, use the
- sp_lock system procedure:
-
- ╓┌─┌──────────────────┌──────────┌───────────┌──────┌────────────────────────╖
- ────────────────────────────────────────────────────────────────────────────
- sp_lock
-
- spid locktype table_id page dbname
- ------ --------- ---------- ----- ----------
- 1 Sh_intent 16003088 0 master
- 4 Ex_extent 0 440 pubs
- 4 Ex_extent 0 504 pubs
- 4 Sh_table 112003430 0 pubs
- 4 Ex_table 240003886 0 pubs
-
- (5 rows affected)
- ────────────────────────────────────────────────────────────────────────────
- (5 rows affected)
-
-
- The locktype column indicates not only whether the lock is a shared lock
- (Sh) or an exclusive lock (Ex), but also whether it is held on a table or a
- page, and whether it is an intent lock, an extent lock, or a demand lock.
-
- An intent lock indicates the intention to acquire a shared or exclusive lock
- on a data page. Setting an intent lock prevents another transaction from
- subsequently acquiring an exclusive lock on the table that contains that
- page.
-
- An extent lock is a lock held on a group of eight database pages while they
- are being allocated or freed. Extent locks are set while a CREATE or DROP
- statement is executing, or while an INSERT operation that requires new data
- or index pages is running.
-
- A demand lock prevents any more shared locks from being set. It indicates
- that a transaction is next in line to lock a table or page. Demand locks are
- necessary because shared locks can overlap so that read transactions keep
- monopolizing a table or page, forcing a write transaction to wait
- indefinitely. After waiting on four different read transactions, a write
- transaction is given a demand lock. As soon as the existing read
- transactions finish, the write transaction is allowed to proceed. Any new
- read transactions will then have to wait for the write transaction to finish
- and release its exclusive lock.
-
- Advanced users may want to query the syslocks system table for additional
- information on locks. See Appendix B, "System Tables," for a description of
- this table.
-
-
- HOLDLOCK Keyword
-
- The HOLDLOCK keyword, used after a table name or view name in the FROM
- clause of a SELECT statement, makes a shared lock more restrictive. It
- applies only to shared locks, only to the table or view for which it is
- specified, and only for the duration of the transaction defined by the
- statement in which it is used.
-
- HOLDLOCK instructs SQL Server to hold the shared lock that it has set until
- the completion of the transaction, instead of releasing it as soon as the
- required table, view, or data page is no longer needed, whether or not the
- transaction has been completed.
-
- SQL Server's normal handling of shared locks─releasing them as soon as the
- table, view, or data page is no longer needed─allows continued interactive
- use of the database even while a lengthy transaction is proceeding. However,
- it also means that if the same entry is read twice within the same
- transaction, it won't necessarily be the same both times.
-
-
- Deadlocks and Livelocks
-
- SQL Server automatically detects and resolves both deadlocks and livelocks.
-
-
- A deadlock occurs when two users each have a lock on a separate object. Each
- wants to acquire an additional lock on the other user's object. When this
- happens, the first user is waiting for the second to let go of the lock, but
- the second user won't let it go until the lock on the first user's object is
- freed.
-
- SQL Server detects this situation and chooses one of the users. SQL Server
- rolls back that user's transaction, notifies the application program of this
- action with message number 1205, and allows the other user's processes to
- move forward. The first user's process is killed and everything starts
- moving.
-
- In a multiuser situation, each user's application program should check every
- transaction for message 1205. It indicates that the user was chosen for a
- deadlock. The application program must restart that transaction.
-
- It is possible to encounter a deadlock when several long-running
- transactions are being executed at the same time in the same database.
-
- In a livelock, a request for an exclusive lock is repeatedly denied because
- a series of overlapping shared locks keeps interfering.
-
- SQL Server detects this situation, too. After four denials to the user
- requesting the exclusive lock (who has been assigned a demand lock), SQL
- Server refuses further requests from shared locks. The request for the
- exclusive lock is then granted without noticeable effect on the application.
-
-
-
- Setting Configuration Options
-
- The configuration options control various aspects of SQL Server's memory
- allocation and performance. The SA can reset these configuration options to
- fine-tune performance and refine storage allocation. The setup program
- adjusts the amount of memory available to SQL Server and the total number of
- users, based on the amount of memory in your computer. The setup program
- assumes the following:
-
-
- ■ An application in which there is a great deal of update activity
-
- ■ An application in which a relatively small number of stored procedures
- are used repeatedly
-
-
- If your application differs significantly from these assumptions, you may
- reset the configuration options to improve performance. You should also
- change the configuration options if you change the amount of memory in your
- computer.
-
-
- Configuration Options
-
- The following sections describe each of the configuration options.
-
-
- Recovery Interval
-
- The recovery_interval configuration option sets the maximum number of
- minutes per database that SQL Server needs to complete its recovery
- procedures in case of a system failure.
-
- The default value for this option is 5 (minutes per database).
-
- SQL Server uses this number and the amount of activity on each database to
- decide when to do a checkpoint on each database. When SQL Server does a
- checkpoint, it writes all dirty pages (data pages that have been changed by
- data modification statements) to the disk. The checkpoint also performs a
- few other "housekeeping" tasks, including truncating the log if this option
- has been set with sp_dboption. A typical checkpoint takes about one second.
-
-
- You may want to change the recovery interval as your application and its
- usage change. For example, to guarantee that changes are frequently written
- to the disk, you may want to shorten the recovery interval when there is a
- lot of update activity on SQL Server. Shortening the recovery interval
- causes more frequent checkpoints, which slows the system very slightly. On
- the other hand, setting the recovery interval too high might cause the
- recovery time to be unacceptably long.
-
- This option is one of the two dynamic ones, which means that an updated
- value takes effect as soon as the SA executes the RECONFIGURE statement.
-
-
- Allow Updates
-
- By default, system tables can be updated only indirectly with system
- procedures or the SAF menus. The allow updates configuration option allows
- the SA to change this.
-
- The allow updates option is either on or off. When the value is changed from
- the default 0 (off) to 1 (on), any user with appropriate permissions can
- update the system tables directly with ad hoc queries and can create stored
- procedures that update the system tables.
-
- ────────────────────────────────────────────────────────────────────────────
- WARNING
-
- Updating certain fields in the system tables prevents SQL Server from
- running. Therefore, allowing direct updates to the system tables is risky.
- Stored procedures that are created while the allow updates option is on will
- always be able to update the system tables, even after the option has been
- turned off. Whenever you turn the allow updates option on, you are creating
- a "window of vulnerability"─a period of time during which SQL Server users
- can alter the system tables or create a stored procedure with which the
- system tables can be altered in the future.
- ────────────────────────────────────────────────────────────────────────────
-
- Because the system tables are so critical, it is best to turn this option on
- only in highly controlled situations. If you want to guarantee that no other
- users can access SQL Server while the system tables can be directly updated,
- you can restart SQL Server with
-
- sqlservr /m
-
- This option starts SQL Server in a single-user mode, which allows only one
- SA to log in, and turns on the allow updates configuration option. For
- details, see the SQL Server Language Reference.
-
- The allow updates option is a dynamic option, which means that a new value
- takes effect as soon as the SA executes the RECONFIGURE WITH OVERRIDE
- statement. The WITH OVERRIDE clause is always required for this
- configuration option as an added measure of protection.
-
-
- User Connections
-
- The user connections configuration option sets the maximum number of
- simultaneous connections─user and background processes─to SQL Server. It
- does not refer to the maximum number of users; that number depends not only
- on the value of this option but also on other system activity.
-
- The maximum number of connections is 250. The effective number is based upon
- your system configuration and is stored in the global variable
- @MAX_CONNECTIONS. You can get a report on the maximum number of file
- descriptors that your system can use with this statement:
-
- select @max_connections
-
- The memory overhead per connection is 40K.
-
- There is no formula for determining how many connections to allow for each
- user. Rather, you must estimate this number based on the system and user
- requirements outlined here. You must also take into account that on a system
- with many users, there is more likelihood that connections needed only
- occasionally can be shared among users.
-
- The following user connections are required:
-
-
- ■ Each user who runs a utility program simultaneously with another user
- needs one connection.
-
- ■ Application developers use one connection for each editing session.
- The number of connections required by users running an application
- depends entirely on how the application has been programmed.
-
- ■ Users writing DB-LIBRARY programs need one connection for each call to
- dbopen.
-
- In addition to the connections required for users, SQL Server needs a
- number of connections for system activity: a minimum of five
- connections must be reserved for such things as error logging, access
- to the master database, and listening to the network.
-
- ■ In addition to the connection used by the master database device, a
- connection is opened and permanently allocated for each additional
- database device when SQL Server is started or when the database device
- is initialized.
-
- ■ Each dump device needs one connection, but only while a dump or load
- is in progress.
-
- ■ In addition to the connection required for the console utility's
- network pipe, a new connection is created for reading and writing when
- the console utility is started.
-
-
- It's a good idea to figure out the maximum number of connections that will
- be used by SQL Server and to keep this number in mind as you add physical
- devices or users to the system.
-
-
- Memory
-
- The memory configuration option sets the size of available memory in 2K
- units. The default run value is set by the setup program based on the amount
- of memory in your computer.
-
- To optimize this number for your system, subtract the memory required for MS
- OS/2 in the network (and other system uses, if the machine is not wholly
- dedicated to SQL Server) from the total physical memory.
-
- The amount of memory specified must be sufficient for SQL Server's static
- memory needs (kernel overhead, user stack space, and so on), as well as for
- the procedure cache and the data cache (also called buffer cache). The
- caches are discussed later.
-
- The memory left over after SQL Server's memory needs are met is divided
- between the procedure cache and the data cache. The percentage allocated to
- the procedure cache is set by the procedure cache configuration option.
-
- Change this value only when you add or remove memory, or when the use of the
- computer system changes.
-
-
- Open Databases
-
- The open database configuration option sets the maximum number of databases
- that can be open at one time on SQL Server.
-
- The default value is 10. Setting the number of open databases higher does
- not have a significant impact on performance or storage requirements.
- Therefore, don't hesitate to increase this value if SQL Server displays a
- message saying that you've exceeded the allowable number of open databases.
-
-
-
- Locks
-
- The locks configuration option sets the number of available locks. Locks are
- not shared the way open databases and database objects are.
-
- The default value is 5000. Increase this value if SQL Server displays a
- message saying that you have exceeded the number of available locks. Since
- locks consume memory, increasing this value may make it necessary to
- increase the amount of memory dedicated to the server.
-
-
- Open Objects
-
- The open objects configuration option sets the maximum number of database
- objects that can be open at one time on SQL Server.
-
- The default value is 300. Increase this value if SQL Server displays a
- message saying that you have exceeded the number of open objects. Since open
- objects consume memory, increasing this value may make it necessary to
- increase the amount of memory dedicated to the server.
-
-
- Procedure Cache
-
- The procedure cache configuration option gives the percentage of memory
- allocated to the procedure cache after SQL Server's memory needs are met.
- SQL Server's memory needs are the sum of memory necessary for locks, user
- connections, the code itself (which varies slightly from release to
- release), and so on. The remaining memory is divided between the procedure
- cache and the data cache according to the percentage given by this
- configuration option.
-
- The procedure cache is the area of memory where the most recently used
- procedures are stored. The procedure cache is also used when a procedure is
- being created and when a query is being compiled. If SQL Server finds a
- procedure or a compilation already in the cache, it isn't necessary to read
- it from the disk.
-
- The data cache is the area of memory where the most recently used data pages
- and index pages are stored. If SQL Server finds a data page or index page
- that has already been called by a user in the cache, it isn't necessary to
- read it from the disk.
-
- Both caches are managed in an LRU-MRU (least recently used, most recently
- used) fashion.
-
- The default value for this configuration option is 20, which gives the
- procedure cache 20% of the remaining memory after SQL Server's requirements
- are met. By default, the data cache gets the other 80%.
-
- Since the optimum value for this configuration option is different from
- application to application, resetting it may improve SQL Server's
- performance. For example, if you run a lot of different procedures or ad hoc
- queries, your application will use the procedure cache more heavily, so you
- may want to increase this value.
-
- Many applications fall in this category while they are being developed. You
- may want to try setting this option to 50 during your development cycle and
- then resetting it to 20 when your application has stabilized.
-
-
- Fill Factor
-
- The fill factor configuration option determines how full SQL Server makes
- each page when it is creating a new index on existing data (unless the user
- specifies some other value in the CREATE INDEX statement). The fill factor
- percentage affects performance because SQL Server must take the time to
- split pages when they fill up.
-
- The fill factor percentage is used only at the time the index is created and
- becomes less important as changes to the data are made. The pages are not
- maintained at any particular level of fullness.
-
- The default fill factor value is 0; legal values are 0 to 100. A fill factor
- of 0 does not mean that pages are 0% full. Rather, it is treated like a fill
- factor of 100 in that SQL Server creates clustered indexes with full data
- pages and nonclustered indexes with completely full leaf pages. It is
- different from 100 in that SQL Server leaves a comfortable amount of space
- within the index B-tree in both cases. There is seldom a reason to change
- the fill factor option, especially since you can override it in the CREATE
- INDEX statement.
-
- If the fill factor is set to 100, SQL Server creates both clustered and
- nonclustered indexes with each page 100% full. A fill factor of 100 makes
- sense only for read-only tables─tables to which no additional data will ever
- be added.
-
- Smaller fill factor values cause SQL Server to create new indexes with pages
- that are not full. For example, a fill factor of 10 might be a reasonable
- choice if you are creating an index on a table that you know contains a
- small portion of the data it will eventually hold. Smaller fill factor
- values cause each index to take more storage space.
-
-
- Time Slice
-
- The time slice configuration option sets the number of milliseconds that a
- user process is allowed to run by SQL Server's scheduler (which is invisible
- to the user). If the time slice is set too low, SQL Server may spend too
- much time switching processes. If it is set too high, users may experience
- long response time.
-
- The default value is 100 milliseconds. There is seldom reason to change it.
-
-
-
- Database Size
-
- The database size configuration option sets the default number of megabytes
- allocated to each new user database. A database size given in a CREATE
- DATABASE statement takes precedence over the value set by this configuration
- option.
-
- The default value is 2 (megabytes). If most of the new databases on your SQL
- Server require more than 2 megabytes you may want to increase this value.
- You must increase it if your model database grows to be larger than 2
- megabytes, since the CREATE DATABASE statement causes SQL Server to copy
- model to create a new user database.
-
-
- Media Retention
-
- The media retention configuration option can be used to set the number of
- days that you expect to retain each diskette after it has been used for a
- database or transaction log dump. If you try to use the diskette before that
- many days have passed, SQL Server issues a warning message. You can override
- the warning if you wish.
-
- The default value is 0. Unless you change it, no warning is issued. A
- typical value might be 7 (days).
-
-
- Recovery Flags
-
- The recovery flags configuration option determines what information SQL
- Server displays on the console during recovery. The default value is 0,
- which means that SQL Server displays only the database name and a message
- saying that recovery is in progress. The other legal value is 1, which means
- that SQL Server displays information about each individual transaction,
- including whether it was aborted or committed.
-
-
- Serial Number
-
- The serial number option is reserved for future use.
-
-
- Changing Configuration Options Using the Config Menu
-
- You can easily change the configuration options using the Config menu. The
- SAF groups these options into three categories:
-
-
- ■ Memory options
-
- ■ User connections
-
- ■ Memory
-
- ■ Procedure cache
-
-
- ■ General options
-
- ■ Open databases
-
- ■ Time slice
-
- ■ Open objects
-
- ■ Database size
-
- ■ Locks
-
- ■ Media retention
-
- ■ Fill factor
-
- ■ Recovery flags
-
-
- ■ Dynamic options
-
- ■ Recovery interval
-
- ■ Allow updates
-
- After changing values for the memory and general configuration options, you
- have to shut down and restart SQL Server before these new values will take
- effect. The dynamic options take effect immediately.
-
-
-
- Changing Memory and General Configuration Options
-
- To change memory and general configuration options:
-
-
- 1. Select the Config menu and choose the appropriate menu item, depending
- on which option you want to change.
-
- The appropriate dialog box appears. The range of values for each
- option is shown to the far right of the option. The text box where you
- place the desired value is to the immediate right of the option.
-
- 2. Enter the new value in the text box.
-
- 3. Choose OK.
-
- After you change the Memory and General configuration options with the
- SAF, you must shut down and restart SQL Server before these new
- options take effect.
-
-
-
- Changing Dynamic Configuration Options
-
- To change dynamic configuration options:
-
-
- 1. Select the Config menu and choose Dynamic Options.
-
- The "Dynamic Options" dialog box appears. The range of values for each
- option is shown to the far right of the option. The text box where you
- place the desired value is to the immediate right of the option.
-
- 2. Enter the new value in the text box.
-
- 3. Choose OK.
-
- The configuration option takes effect immediately. You do not have to
- restart SQL Server.
-
-
-
- Changing Configuration Options Using System Procedures
-
- To reset the configuration options:
-
-
- 1. Execute the sp_configure system procedure.
-
- 2. Execute the RECONFIGURE statement.
-
- 3. Restart SQL Server if dynamic configuration options have been changed.
-
-
- The sp_configure system procedure has the following syntax:
-
- sp_configure [configname [, configvalue]]
-
- ────────────────────────────────────────────────────────────────────────────
- configname
-
- The name of the configuration option
-
- configvalue
- The value for the configuration option
-
- ────────────────────────────────────────────────────────────────────────────
- The most frequently changed configuration options are as follows:
-
-
- ■ User connections
-
- ■ Memory
-
- ■ Procedure cache
-
-
- Here's how you would increase the number of user connections:
-
- sp_configure "user conn", 30
-
- After executing sp_configure, execute the RECONFIGURE statement. The
- RECONFIGURE statement has the following syntax:
-
- RECONFIGURE [WITH OVERRIDE]
-
- Only the SA has permission to use the RECONFIGURE statement. It cannot be
- transferred to other users.
-
- When the SA executes the RECONFIGURE statement, SQL Server checks to make
- sure that the new values in sysconfigures are acceptable and reasonable.
-
- User-supplied values that seem unreasonable to SQL Server cause it to abort
- the RECONFIGURE statement and display a warning message. The SA can then
- re-execute sp_configure with a new value, or re-execute the RECONFIGURE
- statement with the WITH OVERRIDE clause, which causes SQL Server to accept
- whatever values the SA supplies.
-
- One of the configuration options, allow updates, always requires RECONFIGURE
- WITH OVERRIDE. This requirement is meant to supply a small measure of added
- precaution─to cause the SA to consider the consequences of allowing direct
- updates to the system tables.
-
- For any values set to zero, SQL Server calculates a default. For example, if
- the user gives 0 for the number of open databases, SQL Server might
- substitute the value 10.
-
- When the RECONFIGURE statement is accepted, SQL Server writes the new
- configuration options to the area of the disk that holds the configuration
- structure. Then it updates any of the dynamic options (recovery interval or
- allow updates) that were changed. These dynamic configuration changes take
- effect immediately.
-
- None of the nondynamic configuration options (everything except recovery
- interval and allow updates) takes effect until the next time SQL Server is
- restarted.
-
-
- Displaying Information on Configuration Options
-
- To get a report on current settings of configuration options, use the SAF
- Config menu:
-
-
- 1. Choose the Config menu.
-
- 2. Choose Memory Options, General Options, or Dynamic Options.
-
- A dialog box appears. Current settings of each configuration option
- are displayed immediately to the right of the option name. The range
- of values allowed for each option is displayed to the right of the
- current setting.
-
-
- Advanced users may want to query the sysconfigures and syscurconfigs system
- tables for additional information on configuration options. See Appendix B,
- "System Tables," for a description of these tables.
-
-
-
-
-
-
- Chapter 10 Transferring Data to and from SQL Server
- ────────────────────────────────────────────────────────────────────────────
-
-
- Introduction
-
- This chapter explains how to move data between SQL Server and an operating
- system file or a diskette. There are two direct ways to accomplish this:
-
-
- ■ With the bulk copy utility program, bcp, used as a stand-alone program
- from the operating system
-
- ■ With DB-LIBRARY functions from inside an application program
-
-
- This chapter discusses data transfer with bcp. For information about
- DB-LIBRARY, see the SQL Server Programmer's Reference.
-
- There are no SQL commands for the bulk transfer of data.
-
- The bcp program is most frequently used to transfer into a database data
- that was previously associated with another program, usually another
- database management system. The data to be transferred must be put into an
- operating system file or onto diskette with some kind of dump facility
- provided by the old program.
-
- The bcp program can also be used for temporary transfers of data for use
- with other programs─for example, with spreadsheet programs. The data is
- moved from SQL Server into an operating system file or onto diskette; from
- there, the other program can import the data. When you are through using
- your data with the other program, it can be transferred back into an
- operating system file or onto diskette and then back into SQL Server with
- bcp.
-
- SQL Server can accept data in any ASCII or binary format if you can describe
- the terminators (the characters used to separate columns). The table
- structures need not be identical. Data copied into SQL Server is appended to
- any existing contents of a table; data copied out to a file overwrites any
- previous contents of the file.
-
- To use bcp, you must have an SQL Server account and the appropriate
- permissions on the database tables and operating system files. To copy data
- out of a table, you must have SELECT permission on that table; to copy data
- into a table, you must have INSERT permission on the table.
-
- In general, you must supply the following information for transferring data
- to and from SQL Server:
-
-
- ■ The name of the database and table
-
- ■ The name of the operating system file or diskette drive
-
- ■ The direction of the transfer (in or out)
-
-
- In addition, for each column, you can optionally modify the datatype,
- length, and terminator.
-
-
- Permissions Needed to Copy Data
-
- To copy data from an operating system file into a table, the user must have
- INSERT permission on the table.
-
- To copy a table out to an operating system file, the user must have SELECT
- permission on the following tables:
-
-
- ■ The table being copied
-
- ■ sysobjects
-
- ■ syscolumns
-
- ■ sysindexes
-
-
-
- Transferring Data with the Bulk Copy Utility
-
- The bcp program transfers data between an existing database table and an
- operating system file in a format that can be specified by the user, and is
- executed from the operating system.
-
- The bcp program has the following syntax:
-
- bcp [[database_name.]owner.]table_name {in | out} datafile
- [/m maxerrors] [/f formatfile] [/e errfile]
- [/F firstrow] [/L lastrow] [/b batchsize]
- [/n native_type] [/c character_type]
- [/t field_term] [/r row_term]
- [/i input_file] [/o output_file]
- [/U login_id] [/P password]
- [/I interface] [/S servername]
- [/v version]
-
- ────────────────────────────────────────────────────────────────────────────
- database_name
- The database name, which is optional if the table being copied is in your
- default database. Otherwise, you must specify a database name.
-
- owner
- The owner's name, which is optional only if you own the table being
- copied. If no owner is specified and you do not own a table of that name,
- the bulk copy will fail.
-
- table_name
- The name of the database table you want to copy.
-
- in, out
- The direction of the copy. The in option is a copy from a file into the
- database table, while the out option is a copy to a file from the database
- table.
-
- datafile
- The full pathname of an operating system file. The pathname can be from 1
- to 255 characters in length. It can also indicate a diskette drive name.
-
- /m maxerrors
- The maximum number of errors before the copy is aborted. Each row that
- can't be rebuilt by bcp is thrown out and counted as one error. The
- default used if this option is not included is 10.
-
- /f formatfile
- The full pathname of a file with stored responses from a previous use of
- bcp on the same table; creation of the format file is optional. Use this
- option when you have already created a format file that you want to use
- for a copy in or out. After you answer bcp's format questions, it will ask
- you if you want to save your answers in a format file. The default
- filename is bcp.fmt. The bcp program can refer to a format file when
- copying data so that you do not have to duplicate your previous format
- responses interactively. If this option is not used, bcp queries you for
- format information interactively.
-
- /e errfile
- The full pathname of an error file where bcp stores any rows that it was
- unable to transfer from the file to the database. Error messages from the
- bcp program go to the user's workstation. If this option is not used, no
- error file is created.
-
- /F firstrow
- The number of the first row to copy (the default is the first row).
-
- /L lastrow
- The number of the last row to copy (the default is the last row).
-
- /b batchsize
- The number of rows per batch of data copied (the default copies all the
- rows in one batch).
-
- /n native_type
- Performs the copy operation using the data's native (database) datatypes
- as the defaults. This option does not prompt for each field; it uses the
- default values.
-
- /c character_type
- Performs the copy operation with character type as the default. This
- option does not prompt for each field; it uses char as the default storage
- type, no prefixes, \t as the default field separator, and \n as the
- default row terminator.
-
- /t field_term
- Specifies the default field terminator.
-
- /r row_term
- Specifies the default row terminator.
-
- /i input_file
- Specifies the input file.
-
- /o output_file
- Specifies the output file.
-
- /U login_id
- Specifies a login ID.
-
- /P password
- Allows the user to specify a password. If the /P option is not used, bcp
- prompts for a password. If the /P option is used at the end of the command
- line without any password, bcp uses the default password (NULL).
-
- /I interface
- Allows the user to specify a pathname for the interface file. This is for
- compatibility with bcp in other environments only.
-
- /S servername
- Allows the user to specify the name of the SQL Server to connect to. This
- is the name that SQL Server looks up in the interfac file.
-
- /v version
- Reports the current version of the bcp program.
-
- ────────────────────────────────────────────────────────────────────────────
- When the transfer is complete, the program reports the number of rows
- successfully copied and some performance information. Here is a complete
- list of steps that may need to be performed to copy data into SQL Server at
- maximum speed:
-
- ╓┌─────────────────────────────────────┌─────────────────────────────────────╖
- Steps Notes / Who Can Do It
- ────────────────────────────────────────────────────────────────────────────
- 1. Use sp_dboption to set select SA.
- into/bulkcopy to true, and then
- execute CHECKPOINT in the database
- that was changed.
- Steps Notes / Who Can Do It
- ────────────────────────────────────────────────────────────────────────────
- that was changed.
-
- 2. Drop the indexes on the table. Table owner.
-
- 3. Be sure that you have insert Can be changed by table owner.
- permission on the table.
-
- 4. Perform the copy with bcp. Any user with insert permission.
-
- 5. Use DUMP DATABASE to back up the SA or Database Owner.
- newly inserted data.
-
- 6. Re-create the indexes. Check to be sure that you have
- enough space.
-
- 7. Reset sp_dboption, if desired, SA.
- and execute CHECKPOINT in the
- database that was changed.
-
- Steps Notes / Who Can Do It
- ────────────────────────────────────────────────────────────────────────────
- 8. Execute stored procedures or Table owner or stored procedure
- queries to check if any of the newly owner.
- loaded data violates rules.
-
- ────────────────────────────────────────────────────────────────────────────
-
-
-
-
- Native and Character Options
-
- The bcp program provides two command line options that create files with
- frequently used default formats. The /n option uses "native" (database)
- datatypes. The /c option uses "character" (char) for all columns, providing
- tabs between fields on a row and a newline at the end of each row. If you
- are using the /n or /c options, bcp operates noninteractively. It does not
- query you for any information on a column-by-column basis.
-
-
- Native Format
-
- The following command copies the publishers table to the file called
- publ_out, using native data format:
-
- bcp pubs..publishers out publ_out /n /S yourserver /U sa
-
- Here are the contents of publ_out:
-
- 0736^MNew Age Books^FBoston^BMA0877^PBinnet & Hardley^J
- Washington^BDC1389^TAlgodata Infosystems^HBerkeley^BCA
-
- The bcp program has prefixed each field (except the pub_id, which is a
- char(4) datatype) with an ASCII character equivalent to the length of the
- data in the field. For example, "New Age Books" is 13 characters; and M
- (CTRL-M) is ASCII 13. All of the data in this table is char or varchar data,
- so we can read it. In a table with numeric data, the information would be
- written to the file in MS OS/2 system data format.
-
-
- Character Format
-
- Here is how you would copy the same file in character format:
-
- bcp pubs..publishers out publ_out /c /S yourserver /U sa
-
- This is the output:
-
- 0736 New Age Books Boston MA
- 0877 Binnet & Hardley Washington DC
- 1389 Algodata Infosystems Berkeley CA
-
-
- Changing Terminators for Character Format
-
- The /t and /r options can be used with the /c option to change the
- terminators. The following example uses the comma as a field terminator and
- the return (\r) as the row terminator:
-
- bcp pubs..publishers out publ_out /c /t , /r \r /S yourserver
- /U sa
-
- This produces:
-
- 0736,New Age Books,Boston,MA
- 0877,Binnet & Hardley,Washington,DC
- 1389,Algodata Infosystems,Berkeley,CA
-
- You can also use the /t and /r options to change the default terminators
- when the /c option is not used.
-
- ────────────────────────────────────────────────────────────────────────────
- NOTE
-
- The /n and /c options provide the easiest means of copying data to and from
- SQL Server. If these options meet your needs, you can skip to "Example of
- Copying a File to a Database Table," later in this chapter.
- ────────────────────────────────────────────────────────────────────────────
-
-
- Changing the Defaults: Interactive bcp
-
- If you do not use /n or /c, the program prompts you for further information,
- including the storage type, prefix length, and terminator for each column of
- data being copied. For fields that are to be stored as char or binary, bcp
- also prompts for a field length. (See the next section, "File Storage
- Type.")
-
- The default values at these prompts produce exactly the same results as
- using the /n option and provide a simple means for copying data out of a
- database for later reloading into SQL Server. If you are copying data to or
- from SQL Server for use with other programs, your answers to the prompts
- will depend on the format required by the other software.
-
- You may skip a table column on input or output by specifying 0 prefix
- length, 0 length, and no terminator.
-
- After information is gathered about each field in the table, the last
- prompts from bcp ask if you want to save a format file and then for the
- filename. This format file can be used to copy the data back into SQL Server
- or to copy data out from the table at another time. When you are copying
- data in or out using an existing format file, you are not prompted for
- information; the format file provides the information needed.
-
- The following table shows the defaults and possible responses for each of
- the four prompts:
-
- Prompt Default Provided Possible Responses
- ────────────────────────────────────────────────────────────────────────────
- File Storage Type Database storage type for char to create or read an
- most fields; char for ASCII file; any SQL Server
- varchar; binary for datatype where implicit
- varbinary. conversion is supported.
-
- Prefix Length 0 for fields defined with 0 if no prefix is desired;
- datatype (not storage defaults are recommended in
- type) char and all all other cases.
- fixed-length datatypes, 1
- for most other datatypes,
- 2 for binary, and
- varbinary 4 for text and
- image.
-
- Length Defined length for char Default values or greater
- and varchar. Defined are recommended.
- length * 2 for binary and
- varbinary saved as char.
- Maximum length needed to
- avoid truncation or data
- overflow for all other
- datatypes.
-
- Field Terminator None. Up to 30 ASCII characters
- or one of the following:
- \t tab
- \n newline
- \r carriage return
- \0 null terminator
- \\ backslash
-
- ────────────────────────────────────────────────────────────────────────────
-
-
- The responses to these four prompts provide an extremely flexible system
- that allows you to write a file that requires little or no editing to
- conform to many other data formats or to read files from other software. The
- following sections describe each of these prompts and the ways that they
- interact to affect the data. Remember that the default responses to these
- prompts are designed for the fastest and easiest method of copying data to
- and from SQL Server and that other acceptable responses provide ways to
- create other data formats.
-
-
- File Storage Type
-
- The file storage type describes the way the data is stored in the file. You
- can copy data into a file either as its database table type or as a
- character string in ASCII format, or as any datatype for which implicit
- conversion is supported for the datatype in question. User-defined datatypes
- are copied as their base types. The following table shows the storage types
- that can be used with bcp and the defaults for each SQL Server datatype. For
- the most compact storage, use the default value; for ASCII files, use char.
-
-
- ╓┌────────────────────────────┌──────────────────────────────────────────────╖
- Storage Type Abbreviation
- Storage Type Abbreviation
- ────────────────────────────────────────────────────────────────────────────
- char c[har]
- varchar c[har]
- text T[ext]
- binary x
- varbinary x
- image I[mage]
- int i[nt] *
- smallint s[mallint] *
- tinyint t[inyint] *
- float f[loat] *
- bit b[it]
- money m[oney] *
- date d[ate] *
- ────────────────────────────────────────────────────────────────────────────
-
-
- * Length is dependent on the data. For example, an int of 23 has a storage
- length of 2 bytes plus the prefix and terminator (if any); an int of 5, 238,
- 876 has a storage length of 7 bytes plus the prefix and terminator (if any).
-
-
- Giving a type other than char or a datatype that represents a legitimate
- implicit conversion causes bcp to fail. For example, you cannot use smallint
- for int data (you will get overflow errors), but you can use int for
- smallint.
-
- When numeric datatypes are stored as their database types, the data is
- written to the file in MS OS/2 data representation format, rather than in
- human-readable form.
-
-
- Prefix Length
-
- To provide the most compact file storage, bcp's default mode precedes each
- field, except those defined as char, with a string of one or more characters
- that indicate the length of the field. The default values in the prompts
- indicate the most efficient prefix lengths.
-
- For fields of 255 characters or less, the default prefix length is 1. For
- text or image datatypes, the default prefix length is 4. When binary and
- varbinary datatypes are being converted to char storage types, the default
- prefix length is 2, since 2 bytes of storage are required for each byte of
- table data.
-
- To store data with no prefix before the column, use a prefix length of 0.
- Each stored field is padded with spaces to the full length specified at the
- next "length" prompt.
-
-
- Length
-
- In almost all cases, you want to accept the bcp default value for the
- storage length. If you are making a file for later reloading into SQL
- Server, using a prefix with the default storage type and the default length
- keeps the storage space needed to a minimum. If you are creating an ASCII
- file, using the default length ensures that you won't truncate the data or
- create overflow errors that cause bcp to fail.
-
- You can change the default length by supplying another value.
-
- If the storage type is noncharacter, the data is stored in MS OS/2 native
- data representation. You are not asked to provide a length.
-
- When bcp converts noncharacter data to character storage, it suggests a
- default field length large enough to store the data without truncating
- datetime data or causing overflow of numeric data. These are the default
- field lengths:
-
- ╓┌───────────────────────────┌───────────────────────────────────────────────╖
- Datatype Length
- ────────────────────────────────────────────────────────────────────────────
- int 12 bytes
- smallint 6 bytes
- tinyint 3 bytes
- float 25 bytes
- money 24 bytes
- datetime 20 bytes
- bit 1 byte
- ────────────────────────────────────────────────────────────────────────────
-
-
- If you specify a field length that is too short for numeric data when you
- are copying data out, bcp prints an overflow message and does not copy the
- data. When datetime data is stored as a character string of less than 20
- bytes, the data is silently truncated.
-
- The default length for binary and varbinary fields is twice the length
- defined for the column since 2 bytes of storage are required for each byte
- of the field. If you accept the default, the actual amount of storage space
- allocated depends on whether or not you specify a prefix length and/or
- terminators:
-
-
- ■ If you do specify a prefix length of 1, 2, or 4, the storage space
- used is the actual length of the data plus the length of the prefix,
- plus any terminators.
-
- ■ If you specify a prefix length of 0 and no terminator, bcp allocates
- the maximum amount of space shown in the prompt, which is the maximum
- space that may be needed for the datatype in question. In other words,
- the field is treated as if it were fixed length so that it is possible
- to determine where one field ends and the next begins. For example, if
- the field is defined as varchar(30), bcp uses 30 characters for each
- value, even if some of the values are only one character long. The
- char datatypes are always padded to their full specified length.
-
-
- The following tables show the interaction of prefix lengths, terminators,
- and field length on the information in the file. "P" indicates the prefix in
- the stored table, "T" indicates the terminator, and dashes "--" indicate
- appended spaces. "..." indicates that the pattern repeats for each field.
- The field length is 8 for each column, and the 6-character field "string" is
- stored each time.
-
- Table 10.1 SQL Server char Data
-
- Prefix Length = 0 Prefix Length 1, 2, or 4
- ────────────────────────────────────────────────────────────────────────────
- No terminator string--string--... Pstring--Pstring--...
- Terminator string--Tstring--T... Pstring--TPstring--T...
- ────────────────────────────────────────────────────────────────────────────
-
- Table 10.2 Other Datatypes Converted to char
-
- Prefix Length = 0 Prefix Length 1, 2, or 4
- ────────────────────────────────────────────────────────────────────────────
- No terminator string--string--... PstringPstring...
- Terminator stringTstringT... PstringTPstringT...
- ────────────────────────────────────────────────────────────────────────────
-
-
- Field Terminator
-
- You can use an optional terminator to mark the end of a column, separating
- one from the next. The default is no terminator. To accept the default,
- press ENTER when prompted.
-
- When you are preparing data for use with other programs and when you want to
- use bcp to prepare tabular data, you will often want to supply your own
- terminators. The following terminators can be used:
-
-
- ■ Tabs, indicted by \t.
-
- ■ Newlines, indicated by \n.
-
- ■ Carriage returns, indicated by \r.
-
- ■ Backslash, indicated by \\.
-
- ■ Null terminators (no visible terminator), indicated by \0.
-
- ■ Any printable character (*, A, t, |, and so on).
-
- ■ Strings of up to 10 printable characters, including some or all of the
- terminators listed earlier (**\t**, end, !!!!!!!!!!, \t--\n, and so
- on). Control characters are not printable.
-
-
- Note that no terminator is different from the null terminator. The former
- puts no terminator after the column. The latter puts a true NULL after the
- column. A NULL character is an invisible but real character.
-
- The /t and /r options let you change the default terminators. When you use
- these options, the default that is listed on the prompt changes to the value
- you specify on the command line. The following example changes the default
- field terminator to the TAB character (\t) and the default row terminator to
- newline (\n):
-
- bcp pubs..publishers out publ_out /t \t /r \n /S yourserver
- /U sa
-
-
- Indexes
-
- For copying data in, the bcp program is fastest if your database table has
- no indexes. Fast bcp does not log data inserts in the transaction log.
-
- When you copy into a table that has indexes, a slower version of the bcp is
- automatically used. The slow version, which does log data inserts in the
- transaction log, can cause the transaction log to become very large. After
- backing up your database with DUMP DATABASE, you can truncate the
- transaction log with DUMP TRANSACTION WITH TRUNCATE_ONLY.
-
- ────────────────────────────────────────────────────────────────────────────
- NOTE
-
- For any user to copy in data using the fast version of bcp, the SA or
- Database Owner must first execute the sp_dboption system procedure, setting
- the select into/bulkcopy option. If the option is not set and a user tries
- to copy data into a table that does not have indexes, SQL Server generates
- an error message.
- ────────────────────────────────────────────────────────────────────────────
-
- You don't need to set the select into/bulkcopy option to copy data out or
- run bcp on a table that does have indexes because tables with indexes are
- always copied with the slower version and are logged.
-
- While the select into/bulkcopy option is set, you are not allowed to dump
- the transaction log because these operations are not logged and changes are
- therefore not recoverable from transaction logs. In this situation,
- executing the DUMP TRANSACTION statement produces an error message
- instructing you to use DUMP DATABASE instead.
-
- This table shows which version of bcp will be used when copying in, the
- necessary settings for the select into/bulkcopy option, and whether the
- transaction log is kept and can be dumped.
-
- select into/bulk copy
- ON OFF
- ────────────────────────────────────────────────────────────────────────────
- Fast bcp OK prohibited
- (no indexes on DUMP TRAN prohibited
- target table)
-
- Slow bcp OK OK
- (one or more indexes) DUMP TRAN prohibited DUMP TRAN OK
-
- ────────────────────────────────────────────────────────────────────────────
-
-
- By default, the select into/bulkcopy option is off in newly created
- databases. To change the default, set this option in the model database.
-
- The performance penalty for copying data into a table that has indexes in
- place can be severe. If you are copying a very large number of rows, it may
- be faster to drop all the indexes beforehand with DROP INDEX, set the
- database option, copy the data into the table, dump the database, and then
- re-create the indexes. However, you need to allocate disk space for the
- construction of the indexes─about 2.2 times the amount of space needed for
- the data.
-
-
- Data Integrity: Defaults, Rules, and Triggers
-
- When data is copied into a table, any defaults defined for the columns and
- datatypes in the table are observed. That is, if there is a null field in
- the data in a file, the default value is loaded instead during the copy. For
- example, here are two rows in a file that are to be loaded into authors:
-
- 409-56-7008,Bennet,Abraham,415 658-9932,6223 Bateman
- St.,Berkeley,CA,94705,1
- 213-46-8915,Green,Marjorie,,309 63rd St. #411,Oakland,CA,94618,1
-
- Commas separate the fields; a newline separates the rows. Note that there is
- no phone number for Marjorie Green. If the phone column of the titles table
- had a default of "unknown," the rows in the loaded table would look like
- this:
-
- 409-56-7008 Bennet Abraham 415 658-9932 6223 Bateman St.
- Berkeley CA 94705 1
- 213-46-8915 Green Marjorie unknown 309 63rd St. #41
- Oakland CA 94618 1
-
- However, rules and triggers are ignored to load data at the maximum speed.
- To find any rows that violate rules and triggers, copy the data into the
- table and run queries or stored procedures that test the rule or trigger
- conditions.
-
-
- Example of Copying a Database Table to a File
-
- In the following example, bcp copies data from the publishers table to a
- file for later reloading into SQL Server using a format file. It creates an
- output file, delimited with commas, with a newline at the end of each row
- and commas between all fields in a row.
-
- bcp pubs..publishers out publ_out /S yourserver /U sa
- Password:
-
- Enter the file storage type of field pub_id [char]:
- Enter prefix length of field pub_id [0]:
- Enter length of field pub_id [4]:
- Enter field terminator [none]:
-
- Enter the file storage type of field pub_name [char]:
- Enter prefix length of field pub_name [1]: 0
- Enter length of field pub_name [40]:
- Enter field terminator [none]:,
-
- Enter the file storage type of field city [char]:
- Enter prefix length of field city [1]: 0
- Enter length of field city [20]:
- Enter field terminator [none]:,
-
- Enter the file storage type of field state [char]:
- Enter prefix length of field state [1]: 0
- Enter length of field state [2]:
- Enter field terminator [none]: \n
-
- Do you want to save this format information in a file? [Y/n] y
- Host filename: [bcp_fmt] pub_fmt
-
- Starting copy...
-
- 3 rows copied.
- Clock Time (ms.): total = 0 Avg = 0 (3.00 rows per sec.)
-
- These are the results in publ_out:
-
- 0736,New Age Books,Boston,MA
- 0877,Binnet & Hardley,Washington,DC
- 1389,Algodata Infosystems,Berkeley,CA
-
- To copy this data back into SQL Server using the saved format file, type:
-
- bcp pubs..publishers in publ_out /f pub_fmt /S yourserver /U
- sa
-
- You could use the pub_fmt file to copy any data with the same format into
- SQL Server.
-
-
- Copying Data for Use with Other Programs
-
- By changing the default values of the prompts to bcp, you can prepare data
- for use with other software. In most cases, you'll want an ASCII file. The
- usual responses to the bcp prompts are as follows:
-
-
- ■ The storage type should be char.
-
- ■ The prefix length should be 0.
-
- ■ The field length should be the default.
-
- ■ The terminator depends on the software you plan to use. For output
- delimited with commas, use a comma as the terminator for each field.
- For tabular output, terminate the last field with the newline
- character, \n, and all other fields with the tab character, \t.
-
-
- The following example creates output in the personal computer format called
- SDF, or "system data format." Each field has a fixed length with spaces to
- pad the fields. Adjacent fields where the data completely fills the first
- field seem to run together since there are no field separators on each line
- of output. Only the final field has a terminator, \n, the newline character.
- This format can be easily read or produced by other software.
-
- bcp pubs..sales out sal_out /S yourserver /U sa
- Password:
-
- Enter the file storage type of field stor_id [char]:
- Enter prefix-length of field stor_id [1]: 0
- Enter length of field stor_id [4]:
- Enter field terminator [none]:
-
- Enter the file storage type of field ord_num [char]:
- Enter prefix-length of field ord_num [1]: 0
- Enter length of field ord_num [6]:
- Enter field terminator [none]:
-
- Enter the file storage type of field date [datetime]: char
- Enter prefix-length of field date [1]: 0
- Enter length of field date [6]:
- Enter field terminator [none]:
-
- Enter the file storage type of field qty [smallint]: char
- Enter prefix-length of field qty [1]: 0
- Enter length of field qty [6]:
- Enter field terminator [none]:
-
- Enter the file storage type of field payterms [char]:
- Enter prefix-length of field payterms [1]: 0
- Enter length of field payterms [12]:
- Enter field terminator [none]:
-
- Enter the file storage type of field title_id [char]:
- Enter prefix-length of field title_id [1]: 0
- Enter length of field title_id [6]:
- Enter field terminator [none]: \n
-
- Do you want to save this format information in a file? [Y/n]
- Host filename: [bcp_fmt] sal_fmt
-
- Starting copy...
-
- 21 rows copied.
- Clock Time (ms.): total = 1000 Avg = 47 (21.00 rows per sec.)
- Change total and Avg to Total = 1000 Avg = 47
-
- The following output is produced by bcp:
-
- 7066QA7442.3 Sep 13 1985 12:00AM 75 On invoice PS2091
- 7067D4482 Sep 14 1985 12:00AM 10 Net 60 PS2091
- 7131N914008 Sep 14 1985 12:00AM 20 Net 30 PS2091
- 7131N914014 Sep 14 1985 12:00AM 25 Net 30 MC3021
- 8042423LL922 Sep 14 1985 12:00AM 15 On invoice MC3021
- 8042423LL930 Sep 14 1985 12:00AM 10 On invoice BU1032
- 6380722a Sep 13 1985 12:00AM 3 Net 60 PS2091
- 63806871 Sep 14 1985 12:00AM 5 Net 60 BU1032
- 8042P723 Mar 11 1988 12:00AM 25 Net 30 BU1111
- 7896X999 Feb 21 1988 12:00AM 35 On invoice BU2075
- 7896QQ2299 Oct 28 1987 12:00AM 15 Net 60 BU7832
- 7896TQ456 Dec 12 1987 12:00AM 10 Net 60 MC2222
- 8042QA879.1 May 22 1987 12:00AM 30 Net 30 PC1035
- 7066A2976 May 24 1987 12:00AM 50 Net 30 PC8888
- 7131P3087a May 29 1987 12:00AM 20 Net 60 PS1372
- 7131P3087a May 29 1987 12:00AM 25 Net 60 PS2106
- 7131P3087a May 29 1987 12:00AM 15 Net 60 PS3333
- 7131P3087a May 29 1987 12:00AM 25 Net 60 PS7777
- 7067P2121 Jun 15 1987 12:00AM 40 Net 30 TC3218
- 7067P2121 Jun 15 1987 12:00AM 20 Net 30 TC4203
- 7067P2121 Jun 15 1987 12:00AM 20 Net 30 TC7777
-
-
- Example of Copying a File to a Database Table
-
- If you are copying data from a file into a table that has no indexes, make
- sure that the select into/bulkcopy option has been set. The SA or Database
- Owner can set this option by executing the sp_dboption system procedure.
- After you have completed the copy, back up the database with the DUMP
- DATABASE statement so that the copy and any subsequent changes can be
- recovered.
-
- In this example, bcp copies data from the file newpubs into the table
- pubs..publishers. First, here's what the newpubs file looks like:
-
- 1111 Stone Age Books Boston MA
- 2222 Harley & Davidson Washington DC
- 3333 Infodata Algosystems Berkeley CA
-
- To copy data successfully into a table from a file, you must know what the
- terminators in the file are, and you must specify them when you use bcp. In
- the newpubs file, each field in a row is ended with a tab character (\t);
- each row ends with a newline (\n). Since the file is all character data, we
- can use the /c option and specify the terminators with /t for the field
- terminator and /r for the row terminator:
-
- bcp pubs..publishers in newpubs /c /t \t /r \n /S yourserver
- /U sa
- Password:
-
- Starting copy...
-
- 3 rows copied.
- Clock Time (ms.): total = 0 Avg = 0 (3.00 rows per sec.)
-
- When you log in to SQL Server and access publishers, you see that the data
- from newpubs has been appended to the table:
-
- select * from publishers
-
- pub_id pub_name city state
- ------ -------------------- ---------- -----
- 0736 New Age Books Boston MA
- 0877 Binnet & Hardley Washington DC
- 1111 Stone Age Books Boston MA
- 1389 Algodata Infosystems Berkeley CA
- 2222 Harley & Davidson Washington DC
- 3333 Infodata Algosystems Berkeley CA
-
- (6 rows affected)
-
- Since there is a unique clustered index on the pub_id column of publishers,
- the new rows were sorted into order. Had there been any violations of the
- unique index on the pub_id column in the data being copied from the file,
- the violating row would have been discarded. If the types being copied in
- are incompatible with the database types, the entire copy fails.
-
- Note that the pub_id numbers of the three new publishers violate the rule on
- this column. An attempt to add these rows with the INSERT statement would
- have failed since they violate the rule. As explained earlier, bcp ignores
- rules so that data can be loaded at the highest possible speed.
-
-
- Error Files
-
- When the /e option is used when copying data from a file into a table, bcp
- stores all rows that it cannot copy into SQL Server in the specified error
- file. Error messages are sent to the user's workstation. The following
- example shows how the newpubs file would be loaded into the publishers
- database, with any error rows stored in the file pub_err:
-
- bcp pubs..publishers in newpubs /e pub_err /S yourserver /U
- sa
-
-
-
-
-
-
- Chapter 11 Diagnosing System Problems
- ────────────────────────────────────────────────────────────────────────────
-
-
- Introduction
-
- This chapter describes the following methods of diagnosing system problems:
-
-
-
- ■ Interpreting error messages
-
- ■ Stopping processes being carried out by SQL Server
-
- ■ Using the Database Consistency Checker (DBCC)
-
-
-
- Error Log
-
- Most error messages from SQL Server go to the user's screen.
-
- The backtrace from fatal error messages (severity levels 19 and higher) and
- error messages from the kernel are sent to a file named errorlog. See the
- SQL Server Language Reference.
-
- SQL Server creates errorlog if it does not already exist.
-
- Each time a particular server is started with net start sqlserver, a backup
- of the errorlog file is made in the \sql\log subdirectory. Seven log backups
- are kept. Information on the success (or failure) of the start is appended
- to the errorlog file. Subsequent fatal error messages and all kernel error
- messages are appended to errorlog.
-
-
- Error Messages
-
- When SQL Server encounters a problem─whether caused by the user or the
- system─it displays an error message. Error messages contain the following
- information:
-
-
- ■ A message number, which uniquely identifies the error message
-
- ■ A severity level between 10 and 25
-
- ■ An error state number, which allows unique identification of the line
- of SQL Server code at which the error occurred
-
- ■ A message, which tells you what the problem is and possibly how to fix
- it
-
-
- For example, if you try to access a table that doesn't exist, you would get
- the following message:
-
- select * from pulbihsers
-
- Msg 208, Level 16, State 1:
- Invalid object(table) name pulbihsers
-
- A single error condition can have more than one error message. For example,
- SQL Server responds to a syntax error as follows:
-
- slect * from publishers
-
- Msg 101, Level 15, State 1:
- Line 1: SQL syntax error.
- Msg 102, Level 15, State 1:
- Incorrect syntax near '*'.
-
- If there is more than one error in a statement, SQL Server displays
- information about the first one.
-
- The error messages are stored in master..sysmessages. The first few rows
- look like this:
-
- error severity dlevel
- description
- ------------------------------------------------------------
- 101 15 2
- Line %d: SQL syntax error.
- 102 15 2
- Incorrect syntax near '%.*s'.
- 103 15 2
- The %s/ '%.*s' is too long. Maximum length is %d.
- 105 15 2
- Unclosed quote before the character string '%.*s'.
- 106 16 2
- Too many table names in the query. The maximum allowable is
- %d.
-
- (5 rows affected)
-
- You can generate the list of error messages by querying sysmessages.
-
-
- Message Numbers
-
- The message number uniquely identifies the text of each error message.
-
- The error message text is a description of the problem. The descriptions
- often include a line number and a reference to a kind of database object (a
- table, column, stored procedure, and so on), or the name of a particular
- database object.
-
- In the description field of sysmessages, a percent symbol (%) followed by a
- character serves as a placeholder for these pieces of data, which SQL Server
- supplies when it encounters the problem and generates the error message.
- "%d" is a placeholder for a number; "%s" is a placeholder for a kind of
- database object; "%.*s" (within single quotation marks) is a placeholder for
- the name of a particular database object.
-
- For example, the description field for message number 103 is
-
- The %s that starts with '%.*s' is too long. Maximum length
- is %d.
-
- The actual error message displayed to a user might be
-
- The column that starts with 'title' is too long. Maximum length
- is 80.
-
- For errors that you report, it is important to include the numbers, object
- types, and object names. (See "Reporting Errors," later in this chapter, for
- more information.)
-
-
- Severity Levels
-
- The severity level provides a clue about the kind of problem SQL Server has
- encountered.
-
- Severity levels begin with level 10. Levels 10 through 16 indicate problems
- caused by mistakes in what users have entered.
-
- Severity levels 17 or higher indicate software or hardware errors. If the
- number is 17 or 18, you can continue the work you're doing (though you may
- not be able to execute a particular statement).
-
- Severity levels 19 or higher are system problems. They are fatal errors,
- which means that the process (the program code that is running to accomplish
- the task that you specified in your statement) is no longer running. The
- process freezes its state before it stops, recording information about what
- was happening. It is then stopped and disappears.
-
- These errors break the user's connection to SQL Server. Depending on the
- problem, a user may or may not be able to reconnect and resume working. Some
- problems with severity levels in this range affect only one user and one
- process. Others affect all the processes in the database. These problems
- don't necessarily damage a database or its objects, but they can. Still
- other problems are caused by hardware malfunctions.
-
- A backtrace of error messages from the kernel is directed to the error log
- file, where the SA can review it. See "Error Messages," earlier in this
- chapter, for information on the errorlog file.
-
- Users should be instructed to inform the SA whenever problems that generate
- severity levels 17 or higher occur. The SA is responsible for resolving them
- and tracking their frequency. The SA should monitor all problems that
- generate severity levels 18 through 24 and print out a hard copy of the
- error log, which contains the backtrace from the fatal error.
-
- If the problem affects an entire database, the SA may have to use the
- Database Consistency Checker (DBCC) to determine the extent of the damage.
- The DBCC may identify some objects that must be removed. It can repair some
- damage, but the database may also have to be reloaded. See "Database
- Consistency Checker," later in this chapter, for more information on the
- DBCC. Loading a database is discussed in Chapter 8, "Backup and Recovery."
-
- The following list discusses each severity level.
-
- ────────────────────────────────────────────────────────────────────────────
- Severity Levels 10 through 18
- Error messages with severity level 10 are informative only. Error messages
- with severity levels 11 through 16 are generated by user errors and can be
- corrected by the user. Severity levels 17 and 18 don't indicate infected
- processes, so the user's session is not interrupted.
-
- Error messages with severity levels 17 or higher should be reported to the
- SA or Database Owner.
-
- Severity Level 10: Status Information
- Messages with severity level 10 are not errors; they provide additional
- information after certain statements have been executed. For example,
- after a CREATE DATABASE statement has executed, SQL Server displays a
- message telling the user how much space has actually been allocated for
- the new database.
-
- Severity Level 11: Specified Database Object Not Found
- Messages with severity level 11 indicate that SQL Server can't find an
- object referenced in the statement. This is often because you have made a
- mistake in typing the name of a database object or you are confused about
- which database is current.
-
- Check spelling of object names and make sure you're in the correct
- database.
-
- Severity Level 12: Wrong Datatype Encountered
- Messages with severity level 12 indicate a problem with datatypes. For
- example, you may have tried to enter a value of the wrong datatype into a
- field or compare fields of different (and incompatible) datatypes.
-
- To correct comparison problems, use the CONVERT function with SELECT. For
- information on CONVERT, see the SQL Server Language Reference or SQL
- Server Learning TRANSACT-SQL.
-
- Severity Level 13: User Transaction Syntax Error
- Messages with severity level 13 indicate that something is wrong with the
- current user-defined transaction. For example, you may have executed a
- COMMIT TRANSACTION statement without having executed a BEGIN TRANSACTION,
- or you may have tried to roll a transaction back to a savepoint that has
- not been defined (sometimes there may be a typing or spelling mistake in
- the name of the savepoint).
-
- Severity level 13 can also indicate a deadlock, in which case your process
- is stopped. You must restart your statement.
-
- Severity Level 14: Insufficient Permission to Execute Command
- Messages with severity level 14 indicate that the user doesn't have the
- permission necessary to execute the statement or access the database
- object.
-
- The owner of the database object, the owner of the database, or the SA can
- grant the user permission to use the statement or object in question.
-
- Severity Level 15: Syntax Error in SQL Statements
- Messages with severity level 15 indicate that you have made a mistake in
- the syntax of the statement. The text of these error messages include the
- line number(s) on which the mistake occurred and the specific word near
- which it occurred.
-
- Severity Level 16: Miscellaneous User Error
- Error messages with severity level 16 indicate that you have made some
- kind of nonfatal mistake that doesn't fall into any of the above
- categories.
-
- For example, you may have tried to update a view in a way that violates
- the restrictions. Another error that falls into this category is
- unqualified column names: including in a statement the unqualified name
- of a column when that name is used in more than one table. SQL Server has
- no way to determine which one you intend. Check statement syntax and
- current database context.
-
- Severity Level 17: Insufficient Resources
- Error messages with severity level 17 indicate that the statement has
- caused SQL Server to run out of resources (usually space for the database
- on the disk) or to exceed some limit set by the SA.
-
- These system limits include the number of databases that can be open at
- the same time and the number of connections allowed to SQL Server. They
- are stored in master..sysconfigures and can be changed with the
- RECONFIGURE statement. (See Chapter 9, "Fine-tuning Performance and
- Operations," for more information on RECONFIGURE.)
-
- Level 17 error messages that indicate you have run out of space will
- probably be corrected by the Database Owner. Other level 17 error messages
- are probably better addressed by the SA.
-
- Severity Level 18: Nonfatal Internal Error Detected
- Error messages with severity level 18 indicate some kind of internal
- software bug. However, the statement executes to completion, and the
- connection to SQL Server is maintained.
-
- Since problems that generate such messages don't keep users from their
- work, users may have a tendency not to report them. Users should be
- instructed to inform the SA every time an error message with this severity
- level (and higher levels) occurs so that the SA can report them.
-
- An example of a situation that generates severity level 18 is SQL Server
- detecting that a decision about the access path for a particular query has
- been made without a valid reason.
-
- Severity Levels 19 through 24
- Problems that generate error messages with severity levels 19 and higher
- are fatal. They can sometimes leave ongoing infected processes and break
- your connection to SQL Server. To continue working, restart the
- application program.
-
- Severity Level 19: SQL Server Fatal Error in Resource
- Error messages with severity level 19 indicate that some nonconfigurable
- internal limit has been exceeded and that SQL Server cannot recover
- gracefully. You must reconnect to SQL Server. See your SA.
-
- Severity Level 20: SQL Server Fatal Error in Current Process
- Error messages with severity level 20 indicate that SQL Server has
- encountered a bug in some statement. The problem has affected only the
- current process; it is unlikely that the database itself has been damaged.
- Run the DBCC diagnostics. You must reconnect to SQL Server. See your SA.
-
- Severity Level 21: SQL Server Fatal Error in Database (dbid) Processes
- Error messages with severity level 21 indicate that SQL Server has
- encountered a bug that affects all the processes in the current database.
- However, it is unlikely that the database itself has been damaged. Run the
- DBCC diagnostics. You must reconnect to SQL Server. See your SA.
-
- Severity Level 22: SQL Server Fatal Error Table Integrity Suspect
- Error messages with severity level 22 indicate that the table or index
- specified in the message has been damaged at some previous time by a
- software or hardware problem.
-
- The first step is to run DBCC to determine if other objects in the
- database are also damaged. Whatever the report from DBCC, it's possible
- that the problem is in the cache only and not on the disk itself. If so,
- restarting SQL Server will fix the problem.
-
- If restarting doesn't help, the problem is on the disk as well. Sometimes
- it can be solved by destroying the object specified in the error message.
- For example, if the message tells you that SQL Server has found a row with
- length 0 in a nonclustered index, there's no reason not to delete the
- index and rebuild it. Of course, there are a lot of objects you won't want
- to destroy.
-
- You must reconnect to SQL Server. See your SA.
-
- Severity Level 23: SQL Server Fatal Error: Database Integrity Suspect
- Error messages with severity level 23 indicate that the integrity of the
- entire database is suspect. The damage has been caused at some previous
- time by a software or hardware problem. Run DBCC to determine the extent
- of the damage.
-
- Even when the whole database is suspect, it's possible that the damage is
- confined to the cache and that the disk itself is fine. If so, restarting
- SQL Server fixes the problem.
-
- Severity Level 24: Hardware Error
- Error messages with severity level 24 indicate some kind of media failure.
- The SA may have to reload the database. It may be necessary to call the
- hardware vendor.
-
- ────────────────────────────────────────────────────────────────────────────
- Reporting Errors
-
- When you report an error, be sure to include the following information:
-
-
- ■ The message number, severity level, and error state number.
-
- ■ Any numbers, database object types, or database object names that are
- included in the error message.
-
- ■ The context in which the message was generated─which statement was
- running at the time. You can help by providing a hard copy of the
- backtrace from the error log. See "Error Log," earlier in this
- chapter, for information on the error log.
-
-
-
- Stopping Processes
-
- A process is a task being carried out by SQL Server. Processes can be
- initiated by a user giving a statement or by SQL Server itself. Each process
- is assigned a unique process identification number when it starts up. These
- ID numbers and other information about each process are stored in
- master..sysprocesses.
-
- The KILL statement is used to get rid of an ongoing process. Only the SA can
- execute the KILL statement; permission to use it cannot be transferred. The
- most frequent reason for stopping a process is that it interferes with other
- users and the person responsible for running it isn't available.
-
- To keep the system operating smoothly, the SA may want to check ongoing
- processes regularly by using the sp_who stored procedure. Another system
- procedure, sp_lock, also reports on processes. It gives information about
- all the locks currently held on SQL Server, including the spid of the
- process holding each one. The sp_lock system procedure is discussed in
- Chapter 9, "Fine-tuning Performance and Operations."
-
- You cannot stop processes called NETWORK HANDLER or CHECKPOINT. Other
- processes are stopped with the KILL statement. The KILL statement has the
- following syntax:
-
- KILL spid
-
- You can stop only one process at a time. A KILL statement is not reversible
- and cannot be put inside a user-defined transaction.
-
- ────────────────────────────────────────────────────────────────────────────
- NOTE
-
- Server processes cannot be killed. If you try to kill a server process, it
- will not be killed and will still be listed when you execute the sp_who
- system procedure.
- ────────────────────────────────────────────────────────────────────────────
-
-
- Database Consistency Checker
-
- The Database Consistency Checker (DBCC) program is a set of utility
- statements that checks the logical and physical consistency of a database.
- It is used for the following reasons:
-
-
- ■ A system error with a severity level of 20 to 23 has been generated.
-
- ■ The SA wants to make a periodic check.
-
- ■ You suspect that a database is damaged. (For example, if using a
- particular table generates the message corrupted data, you can use
- DBCC to determine if other tables in the database are also damaged.)
-
-
- The Database Owner is automatically granted permission to use the DBCC
- statement and its options. Permission for DBCC CHECKTABLE defaults to the
- table owner. Permission to run DBCC is not transferable.
-
- The DBCC program has the following syntax:
-
- DBCC {CHECKTABLE (table_name) |
- CHECKDB [(database_name)] |
- CHECKALLOC [(database_name)] |
- CHECKCATALOG [(database_name]) |
- DBREPAIR (database_name, DROPDB) }
-
- DBCC can be run while the database is active if the DBREPAIR option is not
- used.
-
- Because of the special status of sysindexes as a system catalog, it is
- necessary to qualify the update and restrict it to a single row in the
- manner described earlier. The value for the qualification's comparison to
- indid is 1 if there is a clustered index on that table and 0 if there is
- none.
-
- The following sections describe each option.
-
-
- The CHECKTABLE Option
-
- The CHECKTABLE option checks the specified table to see that index and data
- pages are correctly linked, that indexes are in properly sorted order, that
- all pointers are consistent, and that the data on each page and page offsets
- is reasonable.
-
- Here's an example:
-
- dbcc checktable (titles)
-
- Checking titles
- Message number is 2536.
- The total number of data pages in this table is 3.
- Message number is 2579.
- DBCC execution completed. If DBCC printed error
- messages, see your System Administrator.
- Message number is 2528.
-
- A warning message may be issued by DBCC, either during CHECKTABLE or
- CHECKDB, stating that the value in the dpages column of the sysindexes row
- is not the same as DBCC's count of data pages for some table. To correct
- this inconsistency:
-
-
- 1. Use the sp_configure stored procedure to enable updates to system
- catalogs.
-
- 2. Execute the SQL statement RECONFIGURE WITH OVERRIDE for that change in
- configuration to take effect.
-
- 3. When using the database where the DBCC check was done, execute this
- SQL statement:
-
- update sysindexes set dpages=<count from DBCC>
- where id=<id of table> and indid=<0 or 1>
-
-
- 4. Execute the CHECKPOINT statement in the database where the DBCC check
- was done.
-
- 5. Use sp_configure to disable updates to system catalogs.
-
- 6. Execute the RECONFIGURE statement.
-
-
-
- The CHECKDB Option
-
- The CHECKDB option runs the same checks as CHECKTABLE, but on each table in
- the specified database. If no database name is given, CHECKDB checks the
- current database. CHECKDB gives the same type of message as CHECKTABLE.
-
-
- The CHECKALLOC Option
-
- The CHECKALLOC option checks the specified database to see that all pages
- are correctly allocated and that no page is allocated that isn't used. If no
- database name is given, CHECKALLOC checks the current database.
-
- CHECKALLOC reports on the amount of space allocated and used. For example,
- here's a CHECKALLOC report on pubs:
-
- Checking pubs
- Message number is 2536.
- Database 'pubs' is not in single user mode - may find spurious allocation
- problems due to transactions in progress.
- Message number is 2572.
- Alloc page 0 (# of extent=3145759 used pages=117375024 ref pages=1)
- Message number is 2538.
- Alloc page 256 (# of extent=1376272 used pages=117374997 ref pages=1)
- Message number is 2538.
- Alloc page 512 (# of extent=65537 used pages=117374977 ref pages=1)
- Message number is 2538.
- Alloc page 768 (# of extent=65537 used pages=117374977 ref pages=1)
- Message number is 2538.
- Total (# of extent=46531052 used pages=117375047 ref pages=1) in
- this
- database
- Message number is 2539.
- DBCC execution completed. If DBCC printed error messages, see your
- System
- Administrator.
- Message number is 2528.
-
- This database contains four allocation units of one-half megabyte each, or 2
- megabytes in all (the default size of a database). There can be as many as
- 32 extents (required for the creation of new database objects) per
- allocation unit; the number of extents tells you whether or not you can
- create new objects in this database. There are 8 pages per extent; the
- number of used pages tells you whether you can add data to existing objects.
-
-
- To get an approximation of the space used, multiply the total number of used
- pages by 2K.
-
-
- The CHECKCATALOG Option
-
- The CHECKCATALOG option checks for consistency within and between system
- tables. For example, it makes sure that every type in syscolumns has a
- matching entry in systypes, that every table and view in sysobjects has at
- least one column in syscolumns, and that the last checkpoint in syslogs is
- valid. If no database name is given, CHECKCATALOG checks the current
- database.
-
- Here's an example:
-
- dbcc checkcatalog (pubs)
-
- Checking pubs
- The following segments have been defined for database 4
- (database name pubs).
-
- virtual start addr size segments
- ------------------ ----- --------
- 3076 1024 0
- 1
- 5124 1024 0
- 1
- DBCC execution completed. If DBCC printed error messages, see your SA.
-
-
- The DBREPAIR Option
-
- The DBREPAIR option drops a damaged database. DROP DATABASE does not work on
- a damaged database.
-
- No users can be using the database being dropped or repaired when the
- DBREPAIR statement is executed (including the one who executed the
- statement). Execute the DBREPAIR statement from master.
-
-
-
-
-
-
- Appendix A The pubs Sample Database
- ────────────────────────────────────────────────────────────────────────────
-
- This appendix describes the sample database, pubs. The pubs database has
- eight tables:
-
-
- ■ publishers
-
- ■ titleauthor
-
- ■ sales
-
- ■ stores
-
- ■ discounts
-
- ■ roysched
-
- ■ authors
-
- ■ titles
-
-
- Each database table is described by two figures. The first figure documents
- the structure of the table; for each table field, the figure lists its
- datatype, its NULL/NOT NULL status, and any defaults, rules, triggers, and
- indexes. The second figure lists the table contents.
-
- Table publishers ─ Structure
-
- pub_id pub_name city state
- ────────────────────────────────────────────────────────────────────────────
- Datatype char(4) varchar(40) varchar(20) char(2)
- Null not null null null null
- Rule pub_idrule(1) ─ ─ ─
- Index clust, uniq ─ ─ ─
- ────────────────────────────────────────────────────────────────────────────
-
- (1) The pub_idrule states that the data must be 1389, 0736, 0877, 1622, or
- 1756, or must match the pattern 99[0-9][0-9].
-
-
- pub_id pub_name city state
- ────────────────────────────────────────────────────────────────────────────
- 1389 Algodata Berkeley CA
- Infosystem
- s
-
- 0736 New Age Boston MA
- Books
-
- 0877 Binnet & Washington DC
- Hardley
-
- Table titleauthor ─ Structure
-
- au_id title_id au_ord royaltyper
- ────────────────────────────────────────────────────────────────────────────
- Datatype id tid smallint int
-
- Null not null not null null null
-
- Index nonclust nonclust ─ ─
-
- uniq, nonclust,
- composite
-
- ────────────────────────────────────────────────────────────────────────────
-
-
- Table titleauthor ─ Contents
-
- ╓┌────────────┌─────────┌───────┌────────────────────────────────────────────╖
- au_id title_id au_ord royaltyper
- ────────────────────────────────────────────────────────────────────────────
- 409-56-7008 BU1032 1 60
- 213-46-8915 BU1032 2 40
- 238-95-7766 PC1035 1 100
- 213-46-8915 BU2075 1 100
- 998-72-3567 PS2091 1 50
- 899-46-2035 PS2091 2 50
- 998-72-3567 PS2106 1 100
- 722-51-5454 MC3021 1 75
- 899-46-2035 MC3021 2 25
- 807-91-6654 TC3218 1 100
- 486-29-1786 PS7777 1 100
- au_id title_id au_ord royaltyper
- ────────────────────────────────────────────────────────────────────────────
- 486-29-1786 PS7777 1 100
- 486-29-1786 PC9999 1 100
- 712-45-1867 MC2222 1 100
- 172-32-1176 PS3333 1 100
- 274-80-9391 BU7832 1 100
- 427-17-2319 PC8888 1 50
- 846-92-7186 PC8888 2 50
- 756-30-7391 PS1372 1 75
- 724-80-9391 PS1372 2 25
- 724-80-9391 BU1111 1 60
- 267-41-2394 BU1111 2 40
- 672-71-3249 TC7777 1 40
- 267-41-2394 TC7777 2 30
- 472-27-2349 TC7777 3 30
- 648-92-1872 TC4203 1 100
- ────────────────────────────────────────────────────────────────────────────
-
-
- Table sales ─ Structure
-
- stor_id ord_num date qty payterms title_id
- ────────────────────────────────────────────────────────────────────────────
- Datatype char(4) varchar(20) datetime smallint varchar(12) tid
- Null not null not null not null not null not null not null
- Index ─ ─ ─ ─ ─ nonclust
- ────────────────────────────────────────────────────────────────────────────
-
- Table sales ─ Contents
-
- ╓┌────────┌─────────┌─────────┌────┌───────────┌─────────────────────────────╖
- stor_id ord_num date qty payterms title_id
- ────────────────────────────────────────────────────────────────────────────
- 7066 QA7442.3 09/13/85 75 On invoice PS2091
- 7067 D4482 09/14/85 10 Net 60 PS2091
- 7131 N914008 09/14/85 20 Net 30 PS2091
- 7131 N914014 09/14/85 25 Net 30 MC3021
- 8042 423LL922 09/14/85 15 On invoice MC3021
- 8042 423LL930 09/14/85 10 On invoice BU1032
- 6380 722a 09/13/85 03 Net 60 PS2091
- 6380 6871 09/14/85 05 Net 60 BU1032
- stor_id ord_num date qty payterms title_id
- ────────────────────────────────────────────────────────────────────────────
- 6380 6871 09/14/85 05 Net 60 BU1032
- 8042 P723 03/11/88 25 Net 30 BU1111
- 7896 X999 02/21/88 35 On invoice BU2075
- 7896 QQ2299 10/28/87 15 Net 60 BU7832
- 7896 TQ456 12/12/87 10 Net 60 MC2222
- 8042 QA879.1 05/22/87 30 Net 30 PC1035
- 7066 A2976 05/24/87 50 Net 30 PC8888
- 7131 P3087a 05/29/87 20 Net 60 PS1372
- 7131 P3087a 05/29/87 25 Net 60 PS2106
- 7131 P3087a 05/29/87 15 Net 60 PS3333
- 7131 P3087a 05/29/87 25 Net 60 PS7777
- 7067 P2121 05/15/87 40 Net 30 TC3218
- 7067 P2121 05/15/87 20 Net 30 TC4203
- 7067 P2121 05/15/87 20 Net 30 TC7777
- ────────────────────────────────────────────────────────────────────────────
-
-
- Table stores ─ Structure
-
- stor_id stor_name stor_addres city state zip
- s
- ─────────────────────────────────────────────────────────────────────────────
- Datatype char(4) varchar(40) varchar(40) varchar(20) char(2) char(5)
-
- Null not null null null null null null
-
- ─────────────────────────────────────────────────────────────────────────────
-
-
- Table stores ─ Contents
-
- ╓┌────────┌────────────────────┌────────────────────┌──────────┌──────┌──────╖
- stor_id stor_name stor_address city state zip
- ────────────────────────────────────────────────────────────────────────────
- 7066 Barnum's 567 Pasadena Ave. Tustin CA 92789
-
- 7067 News & Brews 577 First St. Los Gatos CA 96745
-
- 7131 Doc-U-Mat: Quality 24-A Avrogado Way Remulade WA 98014
- Laundry and Books
- stor_id stor_name stor_address city state zip
- ────────────────────────────────────────────────────────────────────────────
- Laundry and Books
-
- 8042 Bookbeat 679 Carson St. Portland OR 89076
-
- 6380 Eric the Read Books 788 Catamaugus Ave. Seattle WA 98056
-
- 7896 Fricative Bookshop 89 Madison St. Fremont CA 90019
-
- ────────────────────────────────────────────────────────────────────────────
-
-
-
-
- A.1.1
-
-
- discounts ─ Structure
-
- - discounttype stor_id lowqty highqty discount
- ────────────────────────────────────────────────────────────────────────────
- Datatype varchar(40) char(4) smallint smallint float
-
- Null not null null null null not null
-
-
- discounts ─ Contents
-
- discounttype stor_id lowqty highqty discount
- ────────────────────────────────────────────────────────────────────────────
- Initial Customer ─ ─ ─ 10.5
-
- Volume Discount ─ 100 1000 6.7
-
- Customer Discount 8042 ─ ─ 5.0
-
-
- roysched ─ Structure
-
- - title_id lorange hirange royalty
- ────────────────────────────────────────────────────────────────────────────
- Datatype tid int int int
-
- Null not null null null null
-
- Index nonclust ─ ─ ─
-
- Table roysched ─ Contents
-
- ╓┌─────────┌────────┌─┌────────┌─┌───────────────────────────────────────────╖
- title_id lorange hirange royalty
- ────────────────────────────────────────────────────────────────────────────
- BU1032 0 5000 10
- BU1032 5001 50000 12
- PC1035 0 2000 10
- PC1035 2001 3000 12
- PC1035 3001 4000 14
- PC1035 4001 10000 16
- PC1035 10001 50000 18
- BU2075 0 1000 10
- BU2075 1001 3000 12
- BU2075 3001 5000 14
- title_id lorange hirange royalty
- ────────────────────────────────────────────────────────────────────────────
- BU2075 3001 5000 14
- BU2075 5001 7000 16
- BU2075 7001 10000 18
- BU2075 10001 12000 20
- BU2075 12001 14000 22
- BU2075 14001 50000 24
- PS2091 0 1000 10
- PS2091 1001 5000 12
- PS2091 5001 10000 14
- PS2091 10001 50000 16
- PS2106 0 2000 10
- PS2106 2001 5000 12
- PS2106 5001 10000 14
- PS2106 10001 50000 16
- MC3021 0 1000 10
- MC3021 1001 2000 12
- MC3021 2001 4000 14
- MC3021 4001 6000 16
- MC3021 6001 8000 18
- title_id lorange hirange royalty
- ────────────────────────────────────────────────────────────────────────────
- MC3021 6001 8000 18
- MC3021 8001 10000 20
- MC3021 10001 12000 22
- MC3021 12001 50000 24
- TC3218 0 2000 10
- TC3218 2001 4000 12
- TC3218 4001 6000 14
- TC3218 6001 8000 16
- TC3218 8001 10000 18
- TC3218 10001 12000 20
- TC3218 12001 14000 22
- TC3218 14001 50000 24
- TC3218 0 2000 10
- TC3218 2001 4000 12
- TC3218 4001 6000 14
- TC3218 6001 8000 16
- TC3218 8001 10000 18
- TC3218 10001 12000 20
- TC3218 12001 14000 22
- title_id lorange hirange royalty
- ────────────────────────────────────────────────────────────────────────────
- TC3218 12001 14000 22
- TC3218 14001 50000 24
- PC8888 0 5000 10
- PC8888 5001 10000 12
- PC8888 10001 15000 14
- PC8888 15001 50000 16
- PS7777 0 5000 10
- PS7777 5001 50000 12
- PS3333 0 5000 10
- PS3333 5001 10000 12
- PS3333 10001 15000 14
- PS3333 15001 50000 16
- BU1111 0 4000 10
- BU1111 4001 8000 12
- BU1111 8001 10000 14
- BU1111 12001 16000 16
- BU1111 16001 20000 18
- BU1111 20001 24000 20
- BU1111 24001 28000 22
- title_id lorange hirange royalty
- ────────────────────────────────────────────────────────────────────────────
- BU1111 24001 28000 22
- BU1111 28001 50000 24
- MC2222 0 2000 10
- MC2222 2001 4000 12
- MC2222 4001 8000 14
- MC2222 8001 12000 16
- MC2222 8001 12000 16
- MC2222 12001 20000 18
- MC2222 20001 50000 20
- TC7777 0 5000 10
- TC7777 5001 15000 02
- TC7777 15001 50000 14
- TC4203 0 2000 10
- TC4203 2001 8000 12
- TC4203 8001 16000 14
- TC4203 16001 24000 16
- TC4203 24001 32000 18
- TC4203 32001 40000 20
- TC4203 40001 50000 22
- title_id lorange hirange royalty
- ────────────────────────────────────────────────────────────────────────────
- TC4203 40001 50000 22
- BU7832 0 5000 10
- BU7832 5001 10000 12
- BU7832 10001 15000 14
- BU7832 15001 20000 16
- BU7832 20001 25000 18
- BU7832 25001 30000 20
- BU7832 30001 35000 22
- BU7832 35001 50000 24
- PS1372 0 10000 10
- PS1372 10001 20000 12
- PS1372 20001 30000 14
- PS1372 30001 40000 16
- PS1372 40001 50000 18
- ────────────────────────────────────────────────────────────────────────────
-
-
- Table authors ─ Structure
-
- au_id au_lname au_fname phone address city
-
- ─────────────────────────────────────────────────────────────────────────────
- Datatype id varchar(40) varchar(20) char(12) varchar(40) varchar(2
-
- Null not not null not null not null null null
- null
-
- Default ─ ─ ─ UNKNOWN1 ─ ─
-
-
- Index clust, nonclust, ─ ─ ─
- uniq composite
-
- ─────────────────────────────────────────────────────────────────────────────
-
-
- (1) The default UNKNOWN is inserted if no data is entered.
- (2) The rule ziprule states that the zip code must match the pattern
- [0-9][0-9][0-9][0-9][0-9].
-
-
- Table authors ─ Contents
-
- ╓┌────────────┌───────────────┌────────────┌─────────┌─────────────┌─────────
- au_id au_lname au_fname phone address city
-
- ─────────────────────────────────────────────────────────────────────────────
- 409-56-7008 Bennet Abraham 415 6223 Bateman Berkeley
- 658-9932 St.
-
- 213-46-8915 Green Marjorie 415 309 63rd St. Oakland
- 986-7020 #411
-
- 238-95-7766 Carson Cheryl 415 589 Darwin Berkeley
- 548-7723 Ln.
-
- 998-72-3567 Ringer Albert 801 67 Seventh Salt Lake
- 826-0752 Av. City
-
- 899-46-2035 Ringer Anne 801 67 Seventh Salt Lake
- 826-0752 Av. City
- au_id au_lname au_fname phone address city
-
- 826-0752 Av. City
-
- 722-51-5454 DeFrance Michel 219 3 Balding Pl. Gary
- 547-9982
-
- 807-91-6654 Panteley Sylvia 301 1956 Rockville
- 946-8853 Arlington Dr.
-
- 893-72-1158 McBadden Heather 707 301 Putnam Vacaville
- 448-4982
-
- 724-08-9931 Stringer Dirk 415 5420 Oakland
- 843-2991 Telegraph Av.
-
- 274-80-9391 Straight Dick 415 5420 College Oakland
- 834-2919 Av.
-
- 756-30-7391 Karsen Livia 415 5720 McAuley Oakland
- 534-9219 St.
- au_id au_lname au_fname phone address city
-
- 534-9219 St.
-
- 724-80-9391 MacFeather Stearns 415 44 Upland Oakland
- 354-7128 Hts.
-
- 427-17-2319 Dull Ann 415 3410 Blonde Palo Alto
- 836-7128 St.
-
- 672-71-3249 Yokomoto Akiko 415 3 Silver Ct. Walnut
- 935-4228 Creek
-
- 267-41-2394 O'Leary Michael 408 22 Cleveland San Jose
- 286-2428 Av. #14
-
- 472-27-2349 Gringlesby Burt 707 PO Box 792 Covelo
- 938-6445
-
- 527-72-3246 Greene Morningstar 615 22 Graybar Nashville
- 297-2723 House Rd.
- au_id au_lname au_fname phone address city
-
- 297-2723 House Rd.
-
- 172-32-1176 White Johnson 408 10932 Bigge Menlo
- 496-7223 Rd. Park
-
- 712-45-1867 del Castillo Innes 615 2286 Cram Pl. Ann Arbor
- 996-8275 #86
-
- 846-92-7186 Hunter Sheryl 415 3410 Blonde Palo Alto
- 836-7128 St.
-
- 486-29-1786 Locksley Chastity 415 18 Broadway San
- 585-4620 Av. Francisco
-
- 648-92-1872 Blotchet-Halls Reginald 503 55 Hillsdale Corvallis
- 745-6402 Bl.
-
- 341-22-1782 Smith Meander 913 10 Lawrence
- 843-0462 Mississippi
- au_id au_lname au_fname phone address city
-
- 843-0462 Mississippi
- Dr.
-
- ─────────────────────────────────────────────────────────────────────────────
-
-
-
- Table titles ─ Structure
-
- ╓┌─────────┌──────────┌────────────┌───────────┌────────┌──────┌──────┌─────┌
- title_id title type pub_id price advan roya yt
- ce lty sa
- s
- ─────────────────────────────────────────────────────────────────────────────
- Datatype tid varchar(80) char(12) char(4) money money int in
-
- Null not null not null not null null null null null nu
-
- Default ─ ─ UNDECIDED1 ─ ─ ─ ─ ─
- title_id title type pub_id price advan roya yt
- ce lty sa
- s
- Default ─ ─ UNDECIDED1 ─ ─ ─ ─ ─
-
- Rule ─ ─ ─ ─ ─ ─ ─ ─
-
- Trigger deltitle3 ─ ─ ─ ─ ─ ─ ─
-
- Index clust, nonclust ─ ─ ─ ─ ─ ─
- uniq
-
- ─────────────────────────────────────────────────────────────────────────────
-
-
-
- (1) The default UNDECIDED is inserted if no data is entered in the column.
- (2) The getdate() function inserts the current date as the default if no
- data is entered in the column.
- (3) The deltitle trigger prohibits deleting a title if the title_id is
- listed in the sales table.
-
-
- Table titles ─ Contents
-
- ╓┌───────┌───────────────┌─────────────┌──────┌───────┌──────────┌──────┌────
- title_ title type pub_i price advance royal ytd_s
- id d ty ales
- ─────────────────────────────────────────────────────────────────────────────
- BU1032 The Busy business 1389 $19.99 $5000.00 10 4095
- Executive's
- Database Guide
-
-
-
-
- PC1035 But Is It User popular_comp 1389 $22.95 $7000.00 16 8780
- Friendly?
-
-
-
-
- title_ title type pub_i price advance royal ytd_s
- id d ty ales
- ─────────────────────────────────────────────────────────────────────────────
- BU2075 You Can Combat business 0736 $2.99 $10125.00 24 18722
- Computer
- Stress!
-
-
-
-
-
- PS2091 Is Anger the psychology 0736 10.95 $2275.00 12 2045
- Enemy?
-
-
-
-
- PS2106 Life Without psychology 0736 $7.00 $6000.00 10 111
- Fear
-
- title_ title type pub_i price advance royal ytd_s
- id d ty ales
- ─────────────────────────────────────────────────────────────────────────────
-
-
-
-
-
-
-
-
- MC3021 The Gourmet mod_cook 0877 $2.99 $15000.00 24 22246
- Microwave
-
-
-
- TC3218 Onions, Leeks, trad_cook 0877 $20.95 $7000.00 10 375
- and Garlic:
- Cooking
- Secrets of the
- title_ title type pub_i price advance royal ytd_s
- id d ty ales
- ─────────────────────────────────────────────────────────────────────────────
- Secrets of the
- Mediterranean
-
-
- MC3026 The Psychology UNDECIDED 0877 NULL NULL NULL NULL
- of Computer
- Cooking
-
- PC8888 Secrets of popular_comp 1389 $20.00 $8000.00 10 4095
- Silicon
- Valley
-
-
-
-
- PS7777 Emotional psychology 0736 $7.99 $4000.00 10 3336
- Security:
- A New
- title_ title type pub_i price advance royal ytd_s
- id d ty ales
- ─────────────────────────────────────────────────────────────────────────────
- A New
- Algorithm
-
-
-
-
-
- PS3333 Prolonged Data psychology 0736 $19.99 $2000.00 10 4072
- Deprivation:
- Four Case
- Studies
-
-
-
-
- BU1111 Cooking with business 1389 $11.95 $5000.00 10 3876
- Computers:
- Surreptitious
- title_ title type pub_i price advance royal ytd_s
- id d ty ales
- ─────────────────────────────────────────────────────────────────────────────
- Surreptitious
- Balance Sheets
-
- MC2222 Silicon Valley mod_cook 0877 $19.99 $0.00 12 2032
- Gastronomic
- Treats
-
-
-
-
-
- TC7777 Sushi, Anyone? trad_cook 0877 $14.99 $8000.00 10 4095
-
-
-
-
-
-
- title_ title type pub_i price advance royal ytd_s
- id d ty ales
- ─────────────────────────────────────────────────────────────────────────────
-
-
-
-
- TC4203 Fifty Years in trad_cook 0877 $11.95 $4000.00 14 15096
- Buckingham
- Palace
- Kitchens
-
-
-
- BU7832 Straight Talk business 1389 $19.99 $5000.00 10 4095
- About
- Computers
-
-
-
- title_ title type pub_i price advance royal ytd_s
- id d ty ales
- ─────────────────────────────────────────────────────────────────────────────
- PS1372 Computer psychology 0877 $21.59 $7000.00 10 375
- Phobic and
- Non-Phobic
- Individuals:
- Behavior
- Variations
-
-
-
- PC9999 Net Etiquette popular_comp 1389 NULL NULL NULL NULL
-
-
-
- ─────────────────────────────────────────────────────────────────────────────
-
-
-
- The pubs database contains the following database objects:
-
-
- Rules
-
-
- pub_idrule
-
- create rule pub_idrule
- as @pub_id in ("1389", "0736", "0877", "1622", "1756")
- or @pub_id like "99[0-9][0-9]"
-
-
- ziprule
-
- create rule ziprule
- as @zip like "[0-9][0-9][0-9][0-9][0-9]"
-
-
- Trigger
-
-
- deltitle
-
- create trigger deltitle
- on titles
- for delete
- as
- if (select count(*) from deleted, sales
- where sales.title_id = deleted.title_id) > 0
- begin
- rollback transaction
- print "You can't delete a title with sales."
- end
-
-
- Stored Procedure
-
-
- byroyalty
-
- create procedure byroyalty percentage int
- as
- select au_id from titleauthor
- where titleauthor.royaltyper = percentage
-
-
- View
-
-
- titleview
-
- create view titleview
- as
- select title, au_ord, au_lname, price, ytd_sales, pub_id
- from authors, titles, titleauthor
- where authors.au_id = titleauthor.au_id
- and titles.title_id = titleauthor.title_id
-
-
- Defaults
-
-
- datedflt
-
- create default datedflt
- as getdate( )
-
-
- phonedflt
-
- create default phonedflt
- as "UNKNOWN"
-
-
- typedflt
-
- create default typedflt as "UNDECIDED"
-
- Figure A.1 shows the structure of the pubs sample database.
-
- (This figure may be found in the printed book.)
-
-
-
-
-
-
- Appendix B System Tables
- ────────────────────────────────────────────────────────────────────────────
-
- System tables define the structure of the database. All system tables are
- found in the master database. Some system tables are found in all databases;
- they are automatically created when the CREATE DATABASE statement is
- executed.
-
- The following system tables exist in all databases:
-
- ────────────────────────────────────────────────────────────────────────────
- sysalternates
- One row for each SQL Server user mapped to a database user
-
- syscolumns
- One row for each column in a table or view, and for each parameter in a
- stored procedure
-
- syscomments
- One or more rows for each view, rule, default, trigger, and stored
- procedure, giving an SQL definition statement
-
- sysdepends
- One row for each procedure, view, or table that is referenced by a
- procedure, view, or trigger
-
- sysindexes
- One row for each clustered index, nonclustered index, and table with no
- indexes
-
- syskeys
- One row for each foreign or primary key; set by user (not maintained by
- SQL Server)
-
- syslogs
- The transaction log
-
- sysobjects
- One row for each table, view, stored procedure, rule, trigger default,
- log, and (in tempdb only) temporary object
-
- sysprocedures
- One row for each view, rule, default, trigger, and stored procedure,
- giving an internal definition
-
- sysprotects
- User permissions information
-
- syssegments
- One row for each segment (named collection of disk pieces)
-
- systypes
- One row for each system-supplied and user-defined datatype
-
- sysusers
- One row for each user allowed in the database
-
- ────────────────────────────────────────────────────────────────────────────
- The following system tables exist in the master database only:
-
- ────────────────────────────────────────────────────────────────────────────
- sysconfigures
- One row for each user-settable configuration option
-
- syscurconfigs
- Information about configuration options currently being used by SQL Server
-
- sysdatabases
- One row for each database on SQL Server
-
- sysdevices
- One row for each disk dump device, disk for database device, and disk
- partition for databases
-
- syslocks
- Information about active locks
-
- syslogins
- One row for each valid SQL Server user account
-
- sysmessages
- One row for each system error or warning
-
- sysprocesses
- Information about server processes
-
- sysusages
- One row for each disk piece allocated to a database
-
- ────────────────────────────────────────────────────────────────────────────
- In the pages that follow, each system table is described in more detail.
- Each table's columns are listed and described, and their datatypes are
- given. Finally, each table's indexes and the system procedures that
- reference it are listed.
-
- The word reserved in the column description means that the column is not
- currently used by SQL Server.
-
- Permissions for use of the system tables can be controlled by the Database
- Owner, just like permissions on any other tables.
-
- The SQL Server setup program sets up permissions so that all users can read
- the system tables, except for a few fields, like syslogins.passwd.
-
- All direct updates on system tables are disallowed by default, however, even
- for the Database Owner, because SQL Server has supplied system procedures to
- make any updates and additions to system tables that are normally needed.
-
- You can change the default and allow direct updates to the system tables if
- for some reason it becomes necessary to modify them in a way that has not
- been anticipated by SQL Server (and that therefore cannot be accomplished
- with a system procedure). This is accomplished by resetting the
- configuration option called allow updates with the sp_configure system
- procedure and the RECONFIGURE statement. For information on sp_configure,
- see the SQL Server Language Reference.
-
- ────────────────────────────────────────────────────────────────────────────
- WARNING
-
- Some entries in some master database tables should not be altered by any
- user under any circumstances. For example, do not access syslogs in any way.
- Doing so may make it impossible for SQL Server to recover correctly in case
- of a system failure. In addition, an attempt to delete all rows from syslogs
- puts SQL Server into an infinite loop that eventually fills up the entire
- database.
- ────────────────────────────────────────────────────────────────────────────
-
-
- sysalternates (all databases)
-
-
- Description
-
- Contains one row for each SQL Server user mapped (or with an alias) to a
- user of the current database. When a user tries to access a database, SQL
- Server looks for a valid uid entry in sysusers. If none is found, it looks
- in sysalternates.suid. If the user's suid is found there, he or she is
- treated as the database user whose suid is listed in sysalternates.altsuid.
-
-
- When SQL Server is installed, there are no entries in sysalternates.
-
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- suid smallint Server user ID of user being mapped
- altsuid smallint Server user ID of user to whom another user is mapped
- ────────────────────────────────────────────────────────────────────────────
-
-
- Indexes
-
- Unique clustered index on suid
-
-
- Referenced by System Procedures
-
- sp_addalias, sp_adduser, sp_changedbowner, sp_dropalias, sp_dropuser,
- sp_helpuser
-
-
- syscolumns (all databases)
-
-
- Description
-
- Contains one row for every column in every table and view, and a row for
- each parameter in a stored procedure.
-
- ╓┌─────────┌─────────────┌───────────────────────────────────────────────────╖
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- id int ID of the table to which this column belongs or of
- the stored procedure with which this parameter is
- associated
-
- number smallint Subprocedure number when the procedure is grouped
- (0 for nonprocedure entries)
-
- colid tinyint Column ID
-
- status tinyint Indicates the unique position for bit columns and
- whether null values are legal in this column
-
- type tinyint Physical storage type; copied from systypes
-
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- length tinyint Physical length of data; copied from systypes or
- supplied by user
-
- offset smallint Offset into the row where this column appears; if
- negative, variable-length column
-
- usertype smallint User type ID; copied from systypes
-
- cdefault int ID of the stored procedure that generates default
- value for this column
-
- domain int ID of the stored procedure that contains the rule
- for this column
-
- name sysname Column name
-
- printfmt varchar(255) reserved
-
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- ────────────────────────────────────────────────────────────────────────────
-
-
-
-
- Indexes
-
- Unique clustered index on id, number, and colid
-
-
- Referenced by System Procedures
-
- sp_bindefault, sp_bindrule, sp_commonkey, sp_droptype, sp_foreignkey,
- sp_help, sp_helpjoins, sp_helprotect, sp_primarykey, sp_rename,
- sp_unbindefault, sp_unbindrule
-
-
- syscomments (all databases)
-
-
- Description
-
- Contains entries for each view, rule, default, trigger, and stored
- procedure. The text field contains the original SQL definition statements.
- Since text is often longer than 255 characters, entries often span rows.
- Each object can occupy up to 255 rows.
-
- ╓┌─────────┌─────────────┌───────────────────────────────────────────────────╖
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- id int Object ID to which this text applies
-
- number smallint Grouped (0 for nonprocedure entries)
-
- colid tinyint Column ID if this entry is a column; 0 otherwise
-
- texttype smallint 0 System-supplied comment (for views, rules,
- defaults, triggers, and stored procedures)
- 1 User-supplied comment (users can add entries
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- 1 User-supplied comment (users can add entries
- that describe an object or column)
-
- language smallint reserved
-
- text varchar(255) Actual text of SQL definition statement
-
- ────────────────────────────────────────────────────────────────────────────
-
-
-
-
- Indexes
-
- Unique clustered index on id, number, colid, and texttype
-
-
- Referenced by System Procedures
-
- sp_helptext
-
-
- sysconfigures (master database only)
-
-
- Description
-
- Contains one row for each user-settable configuration option. It contains
- the configuration options that were defined before the latest SQL Server
- startup plus any dynamic configuration options that were set since the
- latest SQL Server startup.
-
- The contents of sysconfigures is as follows:
-
- ╓┌───────┌───────────┌───────┌────────────────────────────┌──────────────────╖
- ────────────────────────────────────────────────────────────────────────────
- config value comment status
-
- 101 5 Maximum recovery interval 1
- in minutes
- ────────────────────────────────────────────────────────────────────────────
- in minutes
-
- 102 0 Allow updates to system 1
- tables
-
- 103 10 Number of user connections 0
- allowed
-
- 104 1518 Size of available physical 0
- memory in 2k pages
-
- 105 10 Number of open databases 0
- allowed among all users
-
- 106 5000 Number of locks for all 0
- users
-
- 107 500 Number of open database 0
- objects
-
- ────────────────────────────────────────────────────────────────────────────
- 108 20 Percent of remaining memory 0
- used for procedure cache
-
- 109 0 Default fill factor 0
- percentage
-
- 110 100 Average time slice per 0
- process in milliseconds
-
- 111 2 Default database size in 0
- megabytes
-
- 112 0 Media retention period in 0
- days
-
- 113 0 Recovery flags 0
-
- 114 0 Serial Number 0
-
- ────────────────────────────────────────────────────────────────────────────
-
- (14 rows
- affected)
-
-
-
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- config smallint Configuration variable number
-
- value int User-modifiable value for the variable (being used
- by SQL Server only if RECONFIGURE has been executed)
-
- comment varchar(255) Explanation of the configuration option
-
- status varchar(2) 1 dynamic, the variable takes effect when
- RECONFIGURE is executed
- 0 The variable takes effect when SQL Server is
- restarted
-
- ────────────────────────────────────────────────────────────────────────────
-
-
- ────────────────────────────────────────────────────────────────────────────
- NOTE
-
- The values shown above are created when you install SQL Server with the
- setup program. If you install SQL Server with the bldmastr utility program,
- the values column will be different. bldmastr creates a 0 in the values
- column to indicate that the default value is in effect.
- ────────────────────────────────────────────────────────────────────────────
-
-
- Indexes
-
- Unique clustered index on config
-
-
- Referenced by System Procedures
-
- sp_configure
-
-
- syscurconfigs (master database only)
-
-
- Description
-
- Is built dynamically when queried. It contains an entry for each of the
- configuration options, as does sysconfigures, but with the current values.
- In addition, it contains four entries that describe the configuration
- structure.
-
- The contents of syscurconfigs is as follows:
-
- ╓┌───────┌───────────┌───────┌────────────────────────────┌──────────────────╖
- ────────────────────────────────────────────────────────────────────────────
- config value comment status
-
- 1 1 Major revision number of 0
- config data
- ────────────────────────────────────────────────────────────────────────────
- config data
-
- 2 0 Minor revision number of 0
- config data
-
- 3 1 Reconfigure revision number 0
- of config data
-
- 4 2 Configuration boot source 0
-
- 101 5 Maximum recovery interval
- in minutes 1
-
- 102 0 Allow updates to system 1
- tables
-
- 103 10 Number of user connections 0
- allowed
-
- 104 1518 Size of available physical 0
- ────────────────────────────────────────────────────────────────────────────
- 104 1518 Size of available physical 0
- memory in 2k pages
-
- 105 10 Number of open databases 0
- allowed among all users
-
- 106 5000 Number of locks for all 0
- users
-
- 107 500 Number of open database 0
- objects
-
- 108 20 Percent of remaining memory 0
- used for procedure cache
-
- 109 0 Default fill factor 0
- percentage
-
- 110 100 Average time slice per 0
- process in milliseconds
- ────────────────────────────────────────────────────────────────────────────
- process in milliseconds
-
- 111 2 Default database size in 0
- megabytes
-
- 112 0 Media retention period in 0
- days
-
- 113 0 Recovery flags 0
-
- 114 666666 Serial Number 0
-
-
- (18 rows
- affected)
-
-
-
-
- Referenced by System Procedures
-
- sp_configure
-
-
- sysdatabases (master database only)
-
-
- Description
-
- Contains one row for each database on SQL Server. When SQL Server is
- installed, sysdatabases contains entries for the master database, the model
- database, and the tempdb temporary database.
-
- ╓┌────────┌─────────┌────────────────────────────────────────────────────────╖
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- name sysname Name of the database
-
- dbid smallint Database ID
-
- suid smallint Server user ID of database creator
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- suid smallint Server user ID of database creator
-
- mode smallint Used internally for locking a database while it is
- being created
-
- status smallint Control bits, some of which can be set by the user with
- sp_dboption (read only, dbo only, single user, and so
- on):
- 0x40 select into/bulkcopy; set with sp_dboption
- 0x08 truncate log on chkpt; set with sp_dboption
- 0x10 no chkpt on recovery; set with sp_dboption
- 0x20 Crashed while database was being loaded;
- instructs recovery not to proceed
- 0x100 Database is suspect; cannot be opened or used in
- its present state and can be dropped only with
- DBCC DBREPAIR
- 0x400 Read only; set with sp_dboption
- 0x800 dbo use only; set with sp_dboption
- 0x1000 Single user; set with sp_dboption
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- 0x1000 Single user; set with sp_dboption
- 0x4000 dbname has changed
-
- version smallint Version of SQL Server code under which database was
- created
-
- crdate datetime Creation date
-
- ────────────────────────────────────────────────────────────────────────────
-
-
-
-
- Indexes
-
- Unique clustered index on name Unique nonclustered index on dbid
-
-
- Referenced by System Procedures
-
- sp_addlogin, sp_changedbowner, sp_dboption, sp_defaultdb, sp_depends,
- sp_helpdb, sp_logdevice, sp_renamedb
-
-
- sysdepends (all databases)
-
-
- Description
-
- Contains one row for each procedure, view, or table that is referenced by a
- procedure, view, or trigger.
-
- ╓┌──────────┌─────────┌──────────────────────────────────────────────────────╖
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- id int Object ID
- number smallint Procedure number
- depid int Dependent object ID
- depnumber smallint Dependent procedure number
- depdbid Reserved for future use
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- depdbid Reserved for future use
- depsiteid Reserved for future use
- status smallint Internal status information
- selall bit On if object is used in SELECT * statement
- resultobj bit On if object is being updated
- readobj bit On if object is being read
- ────────────────────────────────────────────────────────────────────────────
-
-
-
- Indexes
-
- Clustered index on id, number, depid, depnumber, dpedbid, and depsiteid
-
-
- Referenced by System Procedures
-
- sp_depends
-
-
- sysdevices (master database only)
-
-
- Description
-
- Contains one row for each disk dump device, diskette dump device, and
- database device. When SQL Server is installed, there are four entries in
- sysdevices: one for the master database device (for databases), one for a
- disk dump device, and two for diskette dump devices.
-
- ╓┌──────────┌─────────────┌──────────────────────────────────────────────────╖
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- low int First virtual page number on database device (not
- used for dump devices)
-
- high int Last virtual page number on database device (not
- used for dump devices)
-
- status smallint Indicates whether it is to be used as a default:
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- status smallint Indicates whether it is to be used as a default:
- 2 Physical database device for database storage
- 3 Physical database device for default database
- storage
- 16 Dump device (either disk or diskette)
- 24 Dump device (either disk or diskette);
- skip ANSI labels
-
- cntrltype smallint Controller type (0 if database device, 2 if hard
- disk dump device, 3-4 if diskette dump device)
-
- name sysname Logical name of dump device or database device
-
- phyname varchar(127) Name of physical database device or dump device
-
- ────────────────────────────────────────────────────────────────────────────
-
-
-
-
- Indexes
-
- Unique clustered index on name
-
-
- Referenced by System Procedures
-
- sp_addumpdevice, sp_diskdefault, sp_dropdumpdevice, sp_helpdevice,
- sp_logdevice
-
-
- sysindexes (all databases)
-
-
- Description
-
- Contains one row for each clustered index, one row for each nonclustered
- index, and one row for each table that has no clustered index.
-
- The columns dpages, reserved, used, and rows are maintained only if the row
- describes a table or clustered index.
-
- ╓┌─────────────┌───────────────┌─────────────────────────────────────────────╖
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- name sysname Index or table name
-
- id int ID of table or ID of table to which index
- belongs
-
- indid smallint 0 if table, 1 if clustered index, >1 if
- nonclustered
-
- dpages int Number of data pages used (if entry is a
- table or clustered index)
-
- reserved int Number of pages allocated (if entry is a
- table or clustered index)
-
- used int Number of data and index pages (if entry is
- a clustered index)
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- a clustered index)
-
- rows int Number of rows (if entry is a table or
- clustered index)
-
- first int Pointer to first data or leaf page
-
- root int Pointer to root page if entry is an index;
- pointer to last page if entry is a table
-
- distribution int Pointer to distribution page (if entry is an
- index)
-
- usagecnt int reserved
-
- segment smallint Number of segment in which this object
- resides
-
- status smallint Internal system status information:
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- status smallint Internal system status information:
- 0x1 Abort command if attempt to insert
- duplicate key
- 0x2 Unique index
- 0x4 Abort command if attempt to insert
- duplicate row
- 0x10 Clustered index
- 0x40 Index allows duplicate rows
-
- rowpage smallint Maximum number of rows per page
-
- minlen smallint Minimum size of a row
-
- maxlen smallint Maximum size of a row
-
- maxirow smallint Maximum size of a nonleaf index row
-
- keycnt smallint Number of keys
-
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- keys1 varbinary(255) Description of key columns (if entry is an
- index)
-
- keys2 varbinary(255) Description of key columns (if entry is an
- index)
-
- ────────────────────────────────────────────────────────────────────────────
-
-
-
-
- Indexes
-
- Unique clustered index on id and indid
-
-
- Referenced by System Procedures
-
- sp_helpindex, sp_spaceused
-
-
- syskeys (all databases)
-
-
- Description
-
- Contains one row for each foreign or primary key.
-
- ╓┌────────┌─────────┌────────────────────────────────────────────────────────╖
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- id int int null
- type smallint Record type
- depid int null Dependent object ID
- keycnt int Number of non-null keys
- size int null reserved
- key1 int null Column ID
- key2 int null Column ID
- key3 int null Column ID
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- key3 int null Column ID
- key4 int null Column ID
- key5 int null Column ID
- key6 int null Column ID
- key7 int null Column ID
- key8 int null Column ID
- depkey1 int null Column ID
- depkey2 int null Column ID
- depkey3 int null Column ID
- depkey4 int null Column ID
- depkey5 int null Column ID
- depkey6 int null Column ID
- depkey7 int null Column ID
- depkey8 int null Column ID
- ────────────────────────────────────────────────────────────────────────────
-
-
-
- Indexes
-
- Clustered index on id
-
-
- Referenced by System Procedures
-
- sp_commonkey, sp_dropkey, sp_foreignkey, sp_helpkey, sp_helpjoins,
- sp_primarykey
-
-
- syslocks (master database only)
-
-
- Description
-
- Contains information about active locks. The syslocks system table is not a
- standard table. Rather, it is built dynamically when queried by a user. No
- updates to syslocks are allowed.
-
- ╓┌───────┌─────────┌─────────────────────────────────────────────────────────╖
- Column Datatype Description
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- id int Table ID
-
- dbid smallint Database ID
-
- page int Page number
-
- type smallint Type of lock:
- 1 Exclusive table lock
- 2 Shared table lock
- 3 Exclusive intent lock (will do page locking on
- indicated pages)
- 4 Shared intent lock
- 5 Exclusive page lock
- 6 Shared page lock
- 7 Update page lock (changes to exclusive if page is
- actually modified)
- 8 Exclusive extent lock
- 9 Shared extent lock
- 0x100 Lock is blocking another process
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- 0x100 Lock is blocking another process
- 0x200 Demand lock
-
- spid smallint ID of process that holds the lock
-
- ────────────────────────────────────────────────────────────────────────────
-
-
-
-
- Indexes
-
- None
-
-
- Referenced by System Procedures
-
- sp_lock
-
-
- syslogins (master database only)
-
-
- Description
-
- Contains one row for each valid SQL Server user account. When SQL Server is
- installed, syslogins contains one entry, in which the name is sa, the suid
- is 1, and the password is null.
-
- ╓┌────────────┌─────────────┌────────────────────────────────────────────────╖
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- suid smallint Server user ID
-
- status smallint reserved
-
- accdate datetime reserved
-
- totcpu int reserved
-
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- totio int reserved
-
- spacelimit int reserved
-
- timelimit int reserved
-
- resultlimit int reserved
-
- dbname sysname Name of database to put user into when
- connection is established
-
- name sysname Login ID of user
-
- password sysname null Password of user (may be null)
-
- ────────────────────────────────────────────────────────────────────────────
-
-
-
-
- Indexes
-
- Unique clustered index on suid Unique nonclustered index on name
-
-
- Referenced by System Procedures
-
- sp_addalias, sp_addlogin, sp_adduser, sp_changedbowner, sp_defaultdb,
- sp_defdb, sp_droplogin, sp_helpdb, sp_helpuser, sp_password
-
-
- syslogs (all databases)
-
-
- Description
-
- Contains the transaction log. It is used by SQL Server for recovery and
- roll-forward; it is not used by system users.
-
- You cannot delete from, insert into, or update syslogs. Every data
- modification operation is logged, so before you can change syslogs, the
- change must be logged. This means that a change operation on syslogs adds a
- row to syslogs, which then must be logged, adding another row to syslogs,
- and so on, producing an infinite loop. The loop continues until the database
- becomes full.
-
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- xactid binary(6) Transaction ID
- op tinyint Update operation number
- ────────────────────────────────────────────────────────────────────────────
-
-
- Indexes
-
- None
-
-
- sysmessages (master database only)
-
-
- Description
-
- Contains one row for each system error or warning that can be returned by
- SQL Server. SQL Server displays the error description on the user's screen.
-
-
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- error int Unique error number
-
- severity smallint Severity level of error
-
- dlevel smallint Reserved for number of descriptive level of
- this message: terse, short, or long
-
- description varchar(255) Explanation of error with place holders for
- parameters
-
- ────────────────────────────────────────────────────────────────────────────
-
-
-
- Indexes
-
- Unique clustered index on error and dlevel
-
-
- sysobjects (all databases)
-
-
- Description
-
- Contains one row for each table, view, stored procedure, log, rule, default,
- trigger, and (in tempdb only) temporary object.
-
- ╓┌─────────┌─────────┌───────────────────────────────────────────────────────╖
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- name sysname Object name
-
- id int Object ID
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- id int Object ID
-
- uid smallint User ID of owner object
-
- type char One of the following object types:
- S System table
- U User table
- V View
- L Log
- P Stored procedure
- R Rule
- D Default
- TR Trigger
-
- userstat smallint Application-dependent type information
-
- sysstat smallint Internal status information
-
- indexdel smallint Index delete count (incremented if an index is deleted)
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- indexdel smallint Index delete count (incremented if an index is deleted)
-
- schema smallint Count of changes in schema of a given object
- (incremented if a rule or default is added)
-
- refdate datetime reserved
-
- crdate datetime Date object was created
-
- expdate datetime reserved
-
- deltrig int Stored procedure ID of a delete trigger
-
- instrig int Stored procedure ID of an insert trigger
-
- updtrig int Stored procedure ID of an update trigger
-
- seltrig int reserved
-
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- category int reserved
-
- cache smallint reserved
-
- ────────────────────────────────────────────────────────────────────────────
-
-
-
-
- Indexes
-
- Unique clustered index on id Unique nonclustered index on name and uid
-
-
- Referenced by System Procedures
-
- sp_bindefault, sp_bindrule, sp_commonkey, sp_depends, sp_dropgroup,
- sp_dropkey, sp_droptype, sp_dropuser, sp_foreignkey, sp_help, sp_helpjoins,
- sp_helprotect, sp_primarykey, sp_rename, sp_unbindefault, sp_unbindrule
-
-
- sysprocedures (all databases)
-
-
- Description
-
- Contains entries for each view, default, rule, trigger, and stored
- procedure. The plan or sequence tree for each object is stored in binary
- form. If the sequence tree doesn't fit in one entry, it is broken into more
- than one row. The sequence field identifies the sub-rows.
-
- ╓┌─────────┌─────────┌───────────────────────────────────────────────────────╖
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- type smallint Object type:
- 0x1 Entry describes a plan (reserved)
- 0x2 Entry describes a tree
-
- id int Object ID
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- id int Object ID
-
- sequence smallint Sequence number if more than one row is used to
- describe this object
-
- status smallint Internal system status
-
- number smallint Subprocedure number when the procedure is grouped (0
- for nonprocedure entries)
-
- ────────────────────────────────────────────────────────────────────────────
-
-
-
-
- Indexes
-
- Unique clustered index on id, number, type, and sequence
-
-
- sysprocesses (master database only)
-
-
- Description
-
- Contains information about SQL Server processes. The sysprocesses system
- table is not a standard table. Rather, it is built dynamically when queried
- by a user. No updates to sysprocesses are allowed. Use the KILL statement to
- kill a process.
-
- ╓┌─────────────┌─────────┌───────────────────────────────────────────────────╖
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- spid smallint Process ID
-
- kpid smallint Kernel process ID
-
- status char(10) Process ID status (for example, runnable, sleeping,
- and so on)
-
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- suid smallint Server user ID of user who executed command
-
- hostname char(10) Name of workstation
-
- program_name char(16) Name of application program
-
- hostprocess char(8) Workstation process ID number
-
- cmd char(16) Command currently being executed
-
- cpu int Cumulative CPU time for process
-
- physical_io int Number of disk reads and writes for current
- command
-
- memusage int Amount of memory allocated to process
-
- blocked smallint Process ID of blocking process, if any
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- blocked smallint Process ID of blocking process, if any
-
- dbid smallint Database ID
-
- uid smallint ID of user who executed command
-
- gid smallint Group ID of user who executed command
-
- ────────────────────────────────────────────────────────────────────────────
-
-
-
-
- Indexes
-
- None
-
-
- Referenced by System Procedures
-
- sp_who
-
-
- sysprotects (all databases)
-
-
- Description
-
- Contains user permissions information─entries for each GRANT and REVOKE
- statement that has been executed.
-
- ╓┌────────────┌──────────────┌───────────────────────────────────────────────╖
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- id int ID of object to which this permission applies
-
- uid smallint ID of user or group to which this permission
- applies
-
- action tinyint One of the following permissions:
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- action tinyint One of the following permissions:
- SELECT = 193
- INSERT = 195
- DELETE = 196
- UPDATE = 197
- EXECUTE = 224
- CREATE DATABASE = 203
- CREATE DEFAULT = 233
- CREATE PROCEDURE = 222
- CREATE RULE = 236
- CREATE TABLE = 198
- CREATE VIEW = 207
- DUMP DATABASE = 228
- DUMP TRANSACTION = 235
-
- protecttype tinyint Either 205 (grant) or 206 (revoke)
-
- columns varbinary(32) Bit map of columns to which this SELECT or
- UPDATE permission applies. Bit 0 indicates all
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- UPDATE permission applies. Bit 0 indicates all
- columns; bit 1 means permission applies to
- that column; NULL means no information.
-
- ────────────────────────────────────────────────────────────────────────────
-
-
-
-
- Indexes
-
- Clustered index on id, uid, and action
-
-
- Referenced by System Procedures
-
- sp_helprotect
-
-
- syssegments (all databases)
-
-
- Description
-
- Contains one row for each segment (named collection of disk pieces). When
- SQL Server is installed, this table contains two entries: segment 0 (system)
- for system tables and segment 1 (default) for other objects. All entries in
- sysusages contain both these segments in their maps.
-
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- segment smallint Segment number
- name sysname Segment name, used internally
- status int null Indicates which is the default segment
- ────────────────────────────────────────────────────────────────────────────
-
-
- Indexes
-
- None
-
-
- systypes (all databases)
-
-
- Description
-
- Contains one row for each system-supplied and each user-defined datatype.
- Domains (defined by rules) and defaults are given if they exist. The rows
- that describe system-supplied datatypes cannot be altered. The
- system-supplied datatypes and their ID numbers (the contents of the name and
- type fields, respectively) are as follows:
-
- ╓┌───────────────────────────────┌───────────────────────────────────────────╖
- System Datatype ID Number
- ────────────────────────────────────────────────────────────────────────────
- binary 45
- bit 50
- char 4
- datetime 61
- datetimn 111
- System Datatype ID Number
- ────────────────────────────────────────────────────────────────────────────
- datetimn 111
- float 62
- floatn 109
- image 46
- int 56
- intn 38
- money 60
- moneyn 110
- smallint 52
- sysname 39
- text 35
- timestamp 37
- tinyint 48
- varbinary 37
- varchar 39
- ────────────────────────────────────────────────────────────────────────────
-
-
- The following table shows the datatype and description for each column in
- the systypes table.
-
- ╓┌───────────┌─────────────┌─────────────────────────────────────────────────╖
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- uid smallint User ID of datatype creator
-
- usertype smallint User type ID
-
- variable bit 1 if datatype is variable length; 0 otherwise
-
- allownulls bit Indicates whether NULLs are allowed for this
- datatype
-
- type tinyint Physical storage datatype
-
- length tinyint Physical length of datatype
-
- tdefault int ID of stored procedure that generates default
- for this datatype
-
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- domain int ID of stored procedure that contains integrity
- checks for this datatype
-
- name sysname Datatype name
-
- printfmt varchar(255) reserved
-
- ────────────────────────────────────────────────────────────────────────────
-
-
-
-
- Indexes
-
- Unique clustered index on name Unique nonclustered index on usertype
-
-
- Referenced by System Procedures
-
- sp_addtype, sp_bindefault, sp_bindrule, sp_droptype, sp_dropuser, sp_help,
- sp_rename, sp_unbindefault, sp_unbindrule
-
-
- sysusages (master database only)
-
-
- Description
-
- Contains one row for each disk allocation piece assigned to a database. Each
- database contains a specified number of database (logical) page numbers.
- Each disk piece includes segments 0 and 1.
-
- When the CREATE DATABASE statement is executed, SQL Server scans the disk(s)
- to find available disk allocation pieces. One or more contiguous disk
- allocation pieces is assigned to the database, and the mapping is recorded
- in sysusages.
-
- ╓┌───────┌─────────┌─────────────────────────────────────────────────────────╖
- Column Datatype Description
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- dbid smallint Database ID
- segmap int Bit map of possible segment assignments
- lstart int First database (logical) page number
- size int Number of contiguous database (logical) pages
- vstart int Starting virtual page number
- ────────────────────────────────────────────────────────────────────────────
-
-
-
- Indexes
-
- Unique clustered index on dbid and lstart Unique nonclustered index on
- vstart
-
-
- Referenced by System Procedures
-
- sp_logdevice
-
-
- sysusers (all databases)
-
-
- Description
-
- Contains one row for each user allowed in the database and one row for each
- group.
-
- On the SQL Server distribution diskette, master..sysusers contains three
- entries: dbo, whose suid is 1 and uid is 1; guest, whose suid is -1 and uid
- is 2; and public, whose suid is -2 and uid is 0. The sysusers table in the
- model database (and thus in all user databases) initially contains two
- entries: dbo and public.
-
- The user guest provides a mechanism for giving access to the database to
- users not explicitly listed in sysusers, with a restricted set of
- permissions. The guest entry in master means that any user with an account
- on SQL Server (that is, with an entry in syslogins) can access master.
-
- The user public refers to all users. The keyword PUBLIC is used with the
- GRANT and REVOKE statements to signify that the permission is being given to
- or taken away from all users.
-
- ╓┌────────┌─────────────┌────────────────────────────────────────────────────╖
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- uid smallint Server user ID, copied from syslogins. suid 1 is
- the System Administrator; -1 is a guest account.
-
- uid smallint User ID, unique in this database, used for granting
- and revoking permissions. uid 1 is the dbo.
-
- gid smallint Group ID to which this user belongs. If uid = gid,
- this entry defines a group, and suid for this entry
- is 0.
-
- name sysname Username or groupname, unique in this database.
-
- environ varchar(255) reserved
-
- ────────────────────────────────────────────────────────────────────────────
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- ────────────────────────────────────────────────────────────────────────────
-
-
-
-
- Indexes
-
- Unique clustered index on suid Unique nonclustered index on name Unique
- nonclustered index on uid
-
-
- Referenced by System Procedures
-
- sp_addalias, sp_adduser, sp_addgroup, sp_changedbowner, sp_changegroup,
- sp_dropgroup, sp_droplogin, sp_droptype, sp_dropuser, sp_helpgroup,
- sp_helprotect, sp_helpuser
-
- Figure B.1: System Tables Relationship Chart -
-
- (This figure may be found in the printed book.)
-
-
-
-
-
-
- Appendix C Special Keys
- ────────────────────────────────────────────────────────────────────────────
-
- The following keys and key combinations have special functions when using
- the SAF:
-
-
- Editing Keys (Dialog Boxes)
-
- Function Key
- ────────────────────────────────────────────────────────────────────────────
- Cancel current selection ESC
- Move cursor to next field TAB
- Move cursor to previous field SHIFT+TAB
- ────────────────────────────────────────────────────────────────────────────
-
-
- Editing Keys (SQL Windows)
-
- ╓┌──────────────────────────────────────────┌────────────────────────────────╖
- Function Key
- ────────────────────────────────────────────────────────────────────────────
- Delete character above cursor DEL
- Delete character to left of cursor BACKSPACE
- Delete line at cursor CTRL+D
- Move cursor to beginning of line HOME
- Move cursor to end of line END
- Move cursor to top of screen CTRL+HOME
- Move cursor to bottom of screen CTRL+END
- Move down one line DOWN
- Move down one page PG DN
- Move left one character LEFT
- Move right one character RIGHT
- Move up one line UP
- Move up one page PG UP
- Function Key
- ────────────────────────────────────────────────────────────────────────────
- Move up one page PG UP
- Select character to left of cursor SHIFT+LEFT
- Select character to right of cursor SHIFT+RIGHT
- Select next line SHIFT+DOWN
- Select previous line SHIFT+UP
- Select word to left of cursor SHIFT+CTRL+LEFT
- Select word to right of cursor SHIFT+CTRL+RIGHT
- Switch between insert and overtype CTRL+O
- Exit SAF F3
- Get Help F1
- ────────────────────────────────────────────────────────────────────────────
-
-
-
- Menu Keys
-
- ╓┌────────────────────────────────────────────┌──────────────────────────────╖
- Function Key
- ────────────────────────────────────────────────────────────────────────────
- Function Key
- ────────────────────────────────────────────────────────────────────────────
- Access Admin menu ALT+A
- Access Config menu ALT+C
- Access File menu ALT+F
- Access Query menu ALT+Q
- Access Window menu ALT+W
- Cancel current operation ESC
- Choose highlighted command button ENTER
- Highlight first letter of menus ALT
- ────────────────────────────────────────────────────────────────────────────
-
-
-
- Query Keys
-
- ╓┌────────────────────────────────────────────────┌──────────────────────────╖
- Function Key
- ────────────────────────────────────────────────────────────────────────────
- Clear window CTRL+N
- Execute query CTRL+E
- Function Key
- ────────────────────────────────────────────────────────────────────────────
- Execute query CTRL+E
- SQL Query Window CTRL+Q
- SQL Results Window CTRL+R
- SQL Results Full Window CTRL+F
- Switch from one window to another F6
- Switch between Query and Results windows CTRL+W
- ────────────────────────────────────────────────────────────────────────────
-
-
-
-
-
- INDEX
- ──────────────────────────────────────────────────────────────────────────
-
-
-
-
- A
- Accelerator keys
- Access to database
- restrict using stored procedure
- restrict using view
- Add a Groupname dialog box
- Add a Login ID dialog box
- Add a Username dialog box
- Add alias
- Admin menu
- SQL Query Window
- Add group
- Admin menu
- SQL Query Window
- Add login ID
- Admin menu
- Add password
- Admin menu
- SQL Query Window
- Add username
- Admin menu
- SQL Query Window
- Admin menu
- add group
- add login ID
- add password
- add username
- assign default database
- change Database Owner
- change group
- change password
- create alias
- delete group
- delete login ID
- delete username
- display current users
- dump database
- dump transaction log
- load database
- load transaction log
- manage aliases
- manage groups
- manage login IDs
- manage usernames
- remove alias
- truncate transaction log
- Alias
- create using Admin menu
- create using SQL Query Window
- defined
- display information on
- manage
- remove using Admin menu
- remove using SQL Query Window
- Allocate space for database
- Allocation page
- Allow updates configuration option
- ALT key
- ALT+A key
- ALT+C key
- ALT+F key
- ALT+Q key
- ALT+W key
- ALTER DATABASE statement
- ASCII format for data transfer
- Assign default database
- Admin menu
- Associated username list box
- authors table
-
- B
- BACKSPACE key
- Backup (Dump) Database dialog box
- Backup menu item
- Backup
- database
- files for
- master database
- permissions
- transaction log
- Batch file
- bcp utility program
- change defaults interactively
- option, character
- option, native
- syntax
- Binary format for data transfer
- bldmastr utility program
- Box
- dialog
- list
- text
- Bulk copy utility
- transfer data using
- Button
- command
- option
-
- C
- Cache
- data
- procedure
- Cancel command button
- Chain, ownership
- Change Database Owner dialog box
- Change database owner menu item
- Change Database Owner
- Admin menu
- SQL Query Window
- Change default database
- SQL Query Window
- Change Group dialog box
- Change group
- Admin menu
- SQL Query Window
- Change password
- Admin menu
- SQL Query Window
- Change User Password dialog box
- Character
- bcp option
- data format
- CHECKALLOC option of DBCC
- CHECKCATALOG option of DBCC
- CHECKDB option of DBCC
- CHECKPOINT statement
- with rollback transaction
- Checkpoint
- CHECKTABLE option of DBCC
- Clauses
- GROUP BY
- ORDER BY
- Column, separator
- Command button
- Cancel
- OK
- select with mouse
- select
- Common key
- Config menu
- change configuration options
- display configuration option settings
- shut down SQL Server
- Configuration options
- allow updates
- change using Config menu
- change using SQL Query Window
- database size
- display settings using Config menu
- display settings
- dynamic
- fill factor
- general
- locks
- media retention
- memory
- open databases
- open objects
- procedure cache
- recovery flags
- recovery interval
- serial number
- time slice
- user connections
- Connections
- required by system
- required by users
- console utility program
- Controller number
- Copy data
- for use by other programs
- from file to database table
- to file
- Create alias
- Admin menu
- SQL Query Window
- Create an Alias dialog box
- CREATE DATABASE statement
- CREATE PROCEDURE statement
- CREATE VIEW statement
- CTRL+D key
- CTRL+E key
- CTRL+END key
- CTRL+F key
- CTRL+HOME key
- CTRL+N key
- CTRL+O key
- CTRL+Q key
- CTRL+R key
- CTRL+W key
-
- D
- Data cache
- Data format for copying
- character
- native
- Data transfer (bcp program)
- compact storage
- copy for use by other programs
- copy from file to database table
- copy to file
- copy using bulk copy utility
- integrity when transferring
- modify data for transfer
- store
- Data transfer, indexes
- Database device
- add
- display information on
- drop
- logical name
- physical name
- remove
- set default
- Database name list box
- Database object owner
- defined
- login ID
- password
- permissions
- Database object
- default
- defined
- index
- rule
- stored procedure
- table
- temporary
- trigger
- view
- Database options
- change
- dbo use only
- display information
- no chkpt on recovery
- read only
- select into/bulkcopy
- set
- single user
- trunc. log on chkpt.
- Database Owner
- change using Admin menu
- change using SQL Query Window
- defined
- display information on
- login ID
- password
- permissions
- System Administrator as
- Database size configuration
- Database, sample
- Database
- allocate space
- alter size
- assign default using Admin menu
- back up
- build master
- change default using SQL Query Window
- changes to master
- context-sensitive permissions
- default
- delete
- display information on storage
- drop
- dump master
- dump using Admin menu
- dump using SQL Query Window
- dump
- interaction with transaction log
- list box
- load using Admin menu
- load using SQL Query Window
- load
- location
- manage groups
- manage usernames
- master
- model
- monitor size
- move
- name
- permission to access
- pubs
- recover damaged master
- reload master
- restrict access using stored procedure
- restrict access using view
- sample
- size
- system
- temporary
- what to do if out of space
- when to dump
- DB-LIBRARY
- function
- two-phase commit service
- DBCC CHECKALLOC statement
- DBCC options
- CHECKALLOC
- CHECKCATALOG
- CHECKDB
- CHECKTABLE
- DBREPAIR
- DBCC statement
- dbo use only database option
- dbo username
- DBREPAIR option of DBCC
- Deadlock
- Default database text box
- defncopy utility program
- DEL key
- Delete alias
- Admin menu
- SQL Query Window
- Delete group
- Admin menu
- SQL Query Window
- Delete login ID
- Admin menu
- SQL Query Window
- Delete username
- Admin menu
- SQL Query Window
- Demand lock
- Descriptor, file
- Device, dump
- Dialog box
- Add a Groupname
- Add a Login ID
- Add a Username
- areas in
- Backup (Dump) Database
- Change Database Owner
- Change Group
- Change User Password
- clear from screen
- Create an Alias
- Groupname
- Login to SQL Server
- Manage Groups
- Manage Login IDs
- Manage Usernames
- move cursor within
- Restore (Load) Database
- Start a Server
- Direction keys
- discounts table
- Disk dump device
- DISK INIT statement
- DISK REFIT statement
- DISK REINIT statement
- Diskette
- dump device
- storage capacity
- Display current users menu item
- Display field
- defined
- DOWN key
- DROP DATABASE statement
- Drop
- alias
- database device
- dump device
- DUMP DATABASE statement
- Dump database
- Admin menu
- interaction with transaction log
- SQL Query Window
- Dump device list box
- Dump device
- add
- controller number
- defined
- disk
- diskette
- display information on
- drop
- logical name
- null
- remove
- storage capacity
- Dump transaction log
- Admin menu
- advantage of
- interaction with database
- SQL Query Window
- DUMP TRANSACTION statement
- Dump
- database using SQL Query Window
- database
- master database
- transaction log using Admin menu
- transaction log using SQL Query Window
- transaction log
- when to perform
-
- E
- Editing keys
- END key
- ENTER key
- Error
- fatal
- file
- log
- message number
- message
- report
- severity level
- system
- user correctable
- user
- ESC key
- Exclusive lock
- Extent lock
-
- F
- F1 key
- F3 key
- F6 key
- Field terminator
- Field, display
- File menu
- File
- backup
- descriptor
- error
- storage type
- Fill factor configuration option
- Foreign key
- Function keys
- F3
- F6
-
- G
- Global variables
-
- @@MAX_CONNECTIONS
- @@NESTLEVEL
- @@PROCID
- @@ROWCOUNT
- @@TEXTSIZE
- @@TIMETICKS
- @@TRANCOUNT
- @@VERSION
- query
- GRANT statement
- combine permissions
- conflicting permissions
- Grant
- object permissions
- statement permissions
- GROUP BY clause
- Group
- add using Admin menu
- add using SQL Query Window
- change using Admin menu
- change using SQL Query Window
- defined
- delete using Admin menu
- delete using SQL Query Window
- display information on
- manage using Admin menu
- manage using SQL Query Window
- public
- set up
- Groupname text box
- Groupname
- assign
- dialog box
- public
- Guest
- account
- user permissions
- user
-
- H
- Help menu
- Hierarchy, permissions
- HOLDLOCK keyword
- HOME key
-
- I
- Index
- and data transfer
- database object
- INSERT statement
- Integrity, referential
- Intent lock
- isql utility program
-
- K
- Keys
- accelerator
- ALT
- ALT+A
- ALT+C
- ALT+F
- ALT+Q
- ALT+W
- BACKSPACE
- common
- CTRL+D
- CTRL+E
- CTRL+END
- CTRL+F
- CTRL+HOME
- CTRL+N
- CTRL+O
- CTRL+Q
- CTRL+R
- CTRL+W key
- CTRL+W
- DEL
- direction
- DOWN
- editing keys
- END
- ENTER
- ESC
- F1
- F3
- F6
- foreign
- HOME
- LEFT
- menu keys
- PG DN
- PG UP
- primary
- query keys
- RIGHT
- SHIFT+CTRL+LEFT
- SHIFT+CTRL+RIGHT
- SHIFT+DOWN
- SHIFT+LEFT
- SHIFT+RIGHT
- SHIFT+TAB
- SHIFT+UP
- special
- system tables
- TAB
- UP
- Keywords
- HOLDLOCK
- PUBLIC
- KILL statement
-
- L
- LEFT key
- Length, storage
- List box
- Associated username
- Database name
- Database
- definition
- Dump device
- Load device
- Login ID
- New database owner
- New usergroup
- select item with mouse
- select item
- Server names
- User login ID/alias username
- Livelock
- LOAD DATABASE statement
- Load database
- Admin menu
- SQL Query Window
- Load device list box
- Load transaction log
- Admin menu
- SQL Query Window
- LOAD TRANSACTION statement
- Location of database
- Lock
- deadlock
- demand
- display information on
- exclusive
- extent
- intent
- livelock
- shared
- Locks configuration option
- Log, error
- Log
- in to another server
- queries and results
- Logical name, dump device
- Login ID list box
- Login ID text box
- Login ID
- add using Admin menu
- assign
- Database object owner
- Database Owner
- delete using Admin menu
- delete using SQL Query Window
- display information on
- manage using Admin menu
- probe
- sa
- System Administrator
- visitor
- Login to SQL Server dialog box
-
- M
- Manage aliases menu item
- Manage Groups dialog box
- Manage Login IDs dialog box
- Manage login IDs menu item
- Manage Usernames dialog box
- Manage usernames menu item
- master database
- as default
- build
- changes
- dump
- recover damaged
- reload
- set permissions in
- System Administrator as owner
- when to dump
- Media failure
- recovery
- Media retention configuration option
- Memory configuration option
- Menu item
- Backup
- Change database owner
- choose
- Display current users
- Manage aliases
- Manage login IDs
- Manage usernames
- select with mouse
- Shutdown SQL Server
- Menu, Admin
- add group
- add login ID
- add password
- add username
- change Database Owner
- change group
- change password
- create alias
- delete group
- delete login ID
- delete username
- display current users
- dump database
- dump transaction log
- load database
- load transaction log
- manage aliases
- manage groups
- manage login IDs
- manage usernames
- remove alias
- truncate transaction log
- Menu, Config
- change configuration options
- display configuration option settings
- shut down SQL Server
- Menus
- Menus, SAF
- Menus
- Admin
- Config
- File
- Help
- permissions
- Query
- Window
- model database
- permissions
- Modify data for transfer
- Modify
- query
- results
- Mouse
- scroll with
- select command button with
- select option button with
- select text with
- using in list box
- Move
- data
- database
-
- N
- Name
- database
- logical for dump device
- logical
- physical
- Names for query and results files
- Native
- bcp option
- data format
- net command
- shut down SQL Server
- start SQL Server
- New database owner list box
- New usergroup list box
- no chkpt on recovery database option
- Notational conventions
- Null device
- Number
- controller
-
- O
- Object permissions
- grant
- revoke
- OK command button
- ON DEFAULT clause
- Open databases configuration option
- Open objects configuration option
- Option button
- select with mouse
- select
- Option
- change configuration using Config menu
- change configuration using SQL Query Window
- configuration
- database
- query
- SET statement
- ORDER BY clause
- Ownership chain
-
- P
- Password text box
- Password
- add using Admin menu
- add using SQL Query Window
- assign
- change using Admin menu
- change using SQL Query Window
- Database object owner
- Database Owner
- NULL
- System Administrator
- Permission
- for menu items
- Permissions
- access database
- ALTER DATABASE
- backup
- CHECKPOINT
- combine
- conflicting
- context-sensitive
- CREATE DATABASE
- database groups
- Database object owner
- Database Owner
- display information on
- guest
- hierarchy
- model database
- object
- public group
- RECONFIGURE
- SA
- select
- set in master database
- statement
- stored procedures
- summary table
- System Administrator
- system procedures
- system table
- to copy data from operating system file
- to copy data
- UPDATE STATISTICS
- use alias to assume
- views
- PG DN key
- PG UP key
- Primary key
- Print query and results
- probe login ID
- Procedure cache configuration option
- Process, stop
- Public group
- public groupname
- PUBLIC keyword
- publishers table
- pubs sample database
-
- Q
- Query keys
- Query
- create
- defined
- enter
- execute
- log to file
- log
- menu
- modify
- new
- print
- retrieve
- save
- set options
- system table
- view on separate screen
-
- R
- read only database option
- RECONFIGURE statement
- Record, query and results
- Recovery flags configuration option
- Recovery interval configuration option
- Referential integrity
- Remove alias
- Admin menu
- SQL Query Window
- Remove
- database device
- dump device
- Resources, allocate
- Restore (Load) Database dialog box
- Restore master database
- Results
- defined
- log to file
- modify
- print
- retrieve
- save
- view on separate screen
- REVOKE statement
- combine permissions
- conflicting permissions
- Revoke
- object permissions
- statement permissions
- RIGHT key
- ROLLBACK TRANSACTION statement
- with checkpoint
- roysched table
- Rule, database object
-
- S
- sa login ID
- SAF
- exit
- start
- use for queries and results
- sales table
- Sample database
- Sample database, pubs
- Save, query and results
- Scroll
- bar
- box
- with keys
- with mouse
- Security mechanism
- stored procedure as
- view as
- select into/bulkcopy database option
- SELECT statement
- Serial number configuration option
- Server names list box
- Server
- log in to
- SET statement
- inside trigger or stored procedure
- options
- setup program
- SETUSER statement
- Shared lock
- SHIFT+CTRL+LEFT key
- SHIFT+CTRL+RIGHT key
- SHIFT+DOWN key
- SHIFT+LEFT key
- SHIFT+RIGHT key
- SHIFT+TAB key
- SHIFT+UP key
- Shut down SQL Server
- Config menu
- net command
- SHUTDOWN statement
- Shutdown SQL Server menu item
- SHUTDOWN statement
- shut down SQL Server
- single user database option
- Single-user mode
- Space, database
- Special users
- sp_addalias
- sp_addgroup
- sp_addumpdevice
- sp_adduser
- sp_bindefault
- sp_changedbowner
- sp_changegroup
- sp_configure
- sp_dboption
- sp_defaultdb
- sp_diskdefault
- sp_dropalias
- sp_dropdevice
- sp_dropgroup
- sp_droplogin
- sp_dropuser
- sp_help
- sp_helpdb
- sp_helpdevice
- sp_helpgroup
- sp_helpindex
- sp_helpjoins
- sp_helpkey
- sp_helprotect
- sp_helpuser
- sp_lock
- sp_logdevice
- sp_monitor
- sp_password
- sp_spaceused
- sp_who
- SQL Query Window
- SQL Query window
- SQL Query Window
- add group
- add password
- add username
- change configuration options
- change Database Owner
- change default database
- change group
- change password
- create alias
- delete group
- delete login ID
- delete username
- display current users
- dump database
- dump transaction log
- load database
- manage groups
- remove alias
- truncate transaction log
- SQL Results Full window
- SQL Results window
- SQL Server Administration Facility (SAF)
- start SQL Server
- SQL Server
- database space
- default decisions
- monitor activity of
- shut down using Config menu
- shut down using net command
- shut down using SHUTDOWN statement
- start in single-user mode
- start using net command
- start using SAF
- tools for managing
- sqlservr utility program
- Start a Server dialog box
- Start SQL Server
- net command
- SAF
- Statement permissions
- grant
- revoke
- syntax
- Statements
- ALTER DATABASE
- CHECKPOINT
- CREATE DATABASE
- CREATE PROCEDURE
- CREATE VIEW
- DBCC CHECKALLOC
- DBCC
- DISK INIT
- DISK REFIT
- DISK REINIT
- DROP DATABASE
- DUMP DATABASE
- DUMP TRANSACTION
- GRANT
- KILL
- LOAD DATABASE
- LOAD TRANSACTION
- RECONFIGURE
- REVOKE
- SELECT
- SETUSER
- TRANSACT-SQL
- UPDATE STATISTICS
- USE
- Statistics, update
- Stop process
- Storage
- length
- manage
- Stored procedure
- as security mechanism
- database object
- permissions
- SET statement in
- trigger
- stores table
- Syntax
- ALTER DATABASE
- bcp
- CHECKPOINT
- CREATE DATABASE
- DBCC
- DISK INIT
- DROP DATABASE
- DUMP DATABASE
- DUMP TRANSACTION
- GRANT
- KILL
- LOAD DATABASE
- LOAD TRANSACTION
- object permissions
- REVOKE
- SET
- SETUSER
- sp_addalias
- sp_addgroup
- sp_addumpdevice
- sp_adduser
- sp_changedbowner
- sp_changegroup
- sp_configure
- sp_dboption
- sp_defaultdb
- sp_diskdefault
- sp_dropalias
- sp_dropdevice
- sp_dropgroup
- sp_droplogin
- sp_dropuser
- sp_helpgroup
- sp_helprotect
- sp_helpuser
- sp_logdevice
- sp_password
- statement permissions
- UPDATE STATISTICS
- sysalternates
- syscolumns
- syscomments
- sysconfigures
- syscurconfigs
- sysdatabases
- sysdepends
- sysdevices
- sysindexes
- syskeys
- syslocks
- syslogins
- syslogs
- sysmessages
- sysobjects
- sysprocedures
- sysprocesses system
- sysprocesses
- sysprotects
- syssegments
- System Administrator (SA)
- defined
- login ID
- password
- permissions
- responsibilities
- System database
- System function, user_id
- System problems, diagnose
- System procedures
- permissions
- sp_addalias
- sp_addgroup
- sp_addumpdevice
- sp_adduser
- sp_bindefault
- sp_changedbowner
- sp_changegroup
- sp_configure
- sp_dboption
- sp_defaultdb
- sp_diskdefault
- sp_dropalias
- sp_dropdevice
- sp_dropgroup
- sp_droplogin
- sp_dropuser
- sp_help
- sp_helpdb
- sp_helpdevice
- sp_helpgroup
- sp_helpindex
- sp_helpjoins
- sp_helpkey
- sp_helprotect
- sp_helpuser
- sp_lock
- sp_logdevice
- sp_monitor
- sp_password
- sp_spaceused
- sp_who
- System tables
- keys in
- list
- permissions
- query
- relationship chart
- syscolumns
- syscomments
- sysconfigures
- syscurconfigs
- sysdatabases
- sysdepends
- sysdevices
- sysindexes
- syskeys
- syslaternates
- syslocks
- syslogins
- syslogs
- sysmessages
- sysobjects
- sysprocedures
- sysprocesses
- sysprotects
- syssegments
- systypes
- sysusages
- sysusers
- systypes
- sysusages system table
- sysusages
- sysusers system table
- sysusers
-
- T
- TAB key
- Table
- copy data into
- database object
- structure
- temporary
- tempdb database
- Temporary database object
- Temporary database
- Temporary table
- Terminator
- change for character data format
- field
- Text box
- change information in
- Default database
- defined
- enter information in
- Groupname
- Login ID
- move cursor to
- Password
- use a mouse in
- use keys to move cursor
- Username in database
- Text
- delete
- scroll
- select with mouse
- select
- Time slice configuration options
- titleauthor table
- titles table
- TRANSACT-SQL
- statements
- Transaction log
- advantage of dumping separately
- back up
- defined
- dump using Admin menu
- dump using SQL Query Window
- dump
- expand space for
- interaction with database
- keep small
- load using Admin menu
- load
- put on different database device
- truncate using Admin menu
- truncate using SQL Query Window
- truncate
- Transfer data (bcp)
- for use by other programs
- in ASCII format
- in binary format
- information required
- using bulk copy utility
- with indexes
- Trigger
- database object
- SET statement in
- trunc. log on chkpt. database option
- Truncate transaction log
- Admin menu
- SQL Query Window
- Two-phase commit service
-
- U
- Up key
- UP key
- UPDATE statement
- UPDATE STATISTICS statement
- USE statement
- User connections configuration option
- User login ID/alias username list box
- User
- guest
- impersonate another
- special
- Username in database text box
- Username
- add using Admin menu
- add using SQL Query Window
- dbo
- delete using Admin menu
- delete using SQL Query Window
- display information on
- manage database
- manage using Admin menu
- Users, display current
- Admin menu
- SQL Query Window
- Utility programs
- bcp
- bldmastr
- console
- defncopy
- isql
- sqlservr
-
- V
- View
- as security mechanism
- database object
- permissions
- use to restrict access to data
- visitor login ID
-
- W
- Window menu
- Window, SQL Query
- add group
- add password
- add usernames
- change configuration options
- change Database Owner
- change default database
- change group
- change password
- create alias
- delete group
- delete login ID
- delete username
- display current users
- dump database
- dump transaction log
- load database
- manage groups
- remove alias
- truncate transaction log
- Windows
- alternate between
- clear
- SQL Query
- SQL Results Full
- SQL Results
-
-
-