home *** CD-ROM | disk | FTP | other *** search
Text File | 2013-11-08 | 674.8 KB | 21,330 lines |
- Microsoft SQL Server - Language Reference
-
-
-
-
-
-
-
-
- ────────────────────────────────────────────────────────────────────────────
- Microsoft (R) SQL Server - Language Reference
-
- 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, MS-DOS, 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: SY10231-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 TRANSACT-SQL Statements
-
- Aggregate Functions
- ALTER DATABASE
- ALTER TABLE
- Batch Queries
- BEGIN...END
- BEGIN TRANSACTION
- BREAK
- Browse Mode
- CHECKPOINT
- Comments
- COMMIT TRANSACTION
- COMPUTE Clause
- CONTINUE
- Control-of-Flow Language
- Conversion Function
- CREATE DATABASE
- CREATE DEFAULT
- CREATE INDEX
- CREATE PROCEDURE
- CREATE RULE
- CREATE TABLE
- CREATE TRIGGER
- CREATE VIEW
- Datatypes
- Date Functions
- DBCC
- DECLARE
- DELETE
- DISK INIT
- DISK REFIT
- DISK REINIT
- DROP DATABASE
- DROP DEFAULT
- DROP INDEX
- DROP PROCEDURE
- DROP RULE
- DROP TABLE
- DROP TRIGGER
- DROP VIEW
- DUMP DATABASE
- DUMP TRANSACTION
- EXECUTE
- Expressions
- Functions
- GOTO
- GRANT
- GROUP BY and HAVING Clauses
- Identifiers
- IF...ELSE
- INSERT
- Joins
- KILL
- LOAD DATABASE
- LOAD TRANSACTION
- Mathematical Functions
- Null Values
- ORDER BY Clause
- Parameters
- PRINT
- RAISERROR
- READTEXT
- RECONFIGURE
- RETURN
- REVOKE
- ROLLBACK TRANSACTION
- Row Aggregate Functions
- SAVE TRANSACTION
- Search Conditions
- SELECT
- SET
- SETUSER
- SHUTDOWN
- String Functions
- Subqueries
- System Functions
- System Procedures
- Text/Image Datatypes
- Text/Image Functions
- TRUNCATE TABLE
- UPDATE
- UPDATE STATISTICS
- USE
- Variables (Local and Global)
- Views
- WAITFOR
- WHERE Clause
- WHILE
- Wildcard Characters
- WRITETEXT
-
- Chapter 2 System Procedures
-
- sp_addalias
- sp_addgroup
- sp_addlogin
- sp_addtype
- sp_addumpdevice
- sp_adduser
- sp_bindefault
- sp_bindrule
- sp_changedbowner
- sp_changegroup
- sp_commonkey
- sp_configure
- sp_dboption
- sp_defaultdb
- sp_depends
- sp_diskdefault
- sp_dropalias
- sp_dropdevice
- sp_dropgroup
- sp_dropkey
- sp_droplogin
- sp_droptype
- sp_dropuser
- sp_foreignkey
- sp_help
- sp_helpdb
- sp_helpdevice
- sp_helpgroup
- sp_helpindex
- sp_helpjoins
- sp_helpkey
- sp_helprotect
- sp_helpsql
- sp_helptext
- sp_helpuser
- sp_lock
- sp_logdevice
- sp_monitor
- sp_password
- sp_primarykey
- sp_rename
- sp_renamedb
- sp_spaceused
- sp_unbindefault
- sp_unbindrule
- sp_who
-
- Chapter 3 Utility Programs
-
- bcp
- bldmastr
- console
- defncopy
- isql
- sqlservr
-
- Appendix A 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 B The pubs Sample Database
-
- B.1.1
- Rules
- Trigger
- Stored Procedure
- View
- Defaults
-
- Appendix C TRANSACT-SQL Keywords
-
-
- Index
-
-
-
-
- Before You Begin
- ────────────────────────────────────────────────────────────────────────────
-
-
- Manual Overview
-
- This reference manual describes each statement and command of
- TRANSACT-SQL(tm), an enhanced version of the SQL relational database
- language. It also describes SQL Server system procedures and utility
- programs.
-
- Before using this manual, you should have read SQL Server Administrator's
- Guide for information on using the SQL Server Administration Facility (SAF).
- You should also be familiar with TRANSACT-SQL or another version of SQL. To
- learn TRANSACT-SQL, see SQL Server Learning TRANSACT-SQL.
-
-
- How to Use This Guide
-
- Topics in each chapter are listed in alphabetical order. The topics include
- each statement, or command, with complete syntax as well as general topics.
- For example, to find the complete syntax of the SELECT statement, look under
- "SELECT" in Chapter 1. To read about identifiers, look under "Identifiers"
- in Chapter 1. This manual covers the following topics:
-
- ────────────────────────────────────────────────────────────────────────────
- Chapter 1
- TRANSACT-SQL, SQL Server's enhanced version of the SQL database language
-
- Chapter 2
- SQL Server system procedures, which are procedures supplied with SQL
- Server and executed from the SQL Server Administration Facility (SAF) or
- isql
-
- Chapter 3
- SQL Server utility programs, which are supplied with SQL Server and
- executed directly from the operating system
-
- Appendix A
- SQL Server system tables, which are supplied with SQL Server or created
- when the CREATE DATABASE statement is executed
-
- Appendix B
- The sample database, pubs (used in examples throughout the manual)
-
- Appendix C
- TRANSACT-SQL keywords
-
- ────────────────────────────────────────────────────────────────────────────
- The SQL Server Language Reference is part of the SQL Server documentation
- set. Several manuals in this set are fully illustrated with examples from
- the online sample database, pubs. (See Appendix B, "The pubs Sample
- Database.") Ask your System Administrator how to get a clean copy of the
- pubs database for use in learning TRANSACT-SQL and the system procedures.
-
-
- 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.
-
- MIXEDcase Shows abbreviations for keywords in
- syntax. The uppercase letters show the
- required portion of the keyword; the
- lowercase letters show the optional
- Convention Purpose
- ────────────────────────────────────────────────────────────────────────────
- lowercase letters show the optional
- portion.
-
- 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,
- 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
- Convention Purpose
- ────────────────────────────────────────────────────────────────────────────
- 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.
-
- ... (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
- Convention Purpose
- ────────────────────────────────────────────────────────────────────────────
- SQL statements are executed with the go
- command.)
-
-
-
-
- Finding Further Information
-
- The following manuals describe SQL Server and are included as part of 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 System Administrator's Guide
- A guide for SQL Server System Administrators and for using the SQL Server
- Administration Facility for database queries
-
- 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 TRANSACT-SQL Statements
- ────────────────────────────────────────────────────────────────────────────
-
- This chapter consists of alphabetized reference pages, one for each
- TRANSACT-SQL statement plus special topics such as datatypes, identifiers,
- and functions.
-
- Some SQL statements that are particularly complex (such as SELECT) are
- broken down into individual subsections. For example, there are separate
- reference pages on the COMPUTE, GROUP BY, and HAVING clauses of the SELECT
- statement.
-
- The following statements, commands, and topics are covered in this chapter:
-
-
- ────────────────────────────────────────────────────────────────────────────
- Aggregate Functions
- Return summary values.
-
- ALTER DATABASE
- Increases the amount of disk space allocated to a database.
-
- ALTER TABLE
- Adds new columns to an existing table.
-
- Batch Queries
- A set of SQL statements submitted together and executed as a group, one
- after the other.
-
- BEGIN...END
- Encloses a series of SQL statements so that control-of-flow language, such
- as IF...ELSE, affects the performance of the whole group.
-
- BEGIN TRANSACTION
- Marks the starting point of a user-specified transaction.
-
- BREAK
- Controls operation of statements in a WHILE loop.
-
- Browse Mode
- Supports the ability to perform updates while viewing data.
-
- CHECKPOINT
- Forces all dirty pages in the current database to be written to the disk.
-
- Comments
- Provide information about SQL statements, statement blocks, and stored
- procedures.
-
- COMMIT TRANSACTION
- Marks the ending point of a user-defined transaction.
-
- COMPUTE Clause
- Generates summary values in a SELECT statement with row aggregate
- functions.
-
- CONTINUE
- Controls operation of statements in a WHILE loop.
-
- Control-of-Flow Language
- Controls the flow of execution of SQL statements, statement blocks, and
- stored procedures.
-
- Conversion Function
- Converts expressions of one datatype to another datatype.
-
- CREATE DATABASE
- Creates a new database.
-
- CREATE DEFAULT
- Specifies a value that will be inserted in a column if no value is
- explicitly supplied at insert time.
-
- CREATE INDEX
- Creates indexes.
-
- CREATE PROCEDURE
- Creates a stored procedure that can take one or more user-supplied
- parameters.
-
- CREATE RULE
- Specifies the domain of acceptable values for a particular column or for
- any column of a specified user datatype.
-
- CREATE TABLE
- Creates new tables.
-
- CREATE TRIGGER
- Creates a trigger, which is a special kind of stored procedure often used
- for enforcing integrity constraints.
-
- CREATE VIEW
- Creates views.
-
- Datatypes
- Specify data characteristics of columns, stored procedure parameters, and
- local variables.
-
- Date Functions
- Manipulate datetime values.
-
- DBCC
- Checks the logical and physical consistency of a database.
-
- DECLARE
- Declares the name and type of local variables for a batch or procedure.
-
- DELETE
- Removes rows from a table.
-
- DISK INIT
- Reserves and formats physical storage for database devices.
-
- DISK REFIT
- Restores a damaged master database.
-
- DISK REINIT
- Part of the procedure that restores a damaged master database.
-
- DROP DATABASE
- Removes one or more databases from SQL Server.
-
- DROP DEFAULT
- Removes a user-specified default.
-
- DROP INDEX
- Removes an index from the database.
-
- DROP PROCEDURE
- Removes user-created stored procedures from the current database.
-
- DROP RULE
- Removes a user-specified rule.
-
- DROP TABLE
- Removes a table definition and all data, indexes, triggers, and permission
- specifications for a table from the database.
-
- DROP TRIGGER
- Removes a trigger.
-
- DROP VIEW
- Removes views from the database.
-
- DUMP DATABASE
- Makes a backup copy of the database and the transaction log.
-
- DUMP TRANSACTION
- Removes the inactive part of the transaction log and makes a backup copy
- of it.
-
- EXECUTE
- Runs a system procedure or a user-defined stored procedure.
-
- Expressions
- Used as variables and constants in many SQL statements.
-
- Functions
- Return special information from the database.
-
- GOTO
- Causes an unconditional branching to a user-defined label.
-
- GRANT
- Assigns permissions to users.
-
- GROUP BY and HAVING Clauses
- Divide a table into groups.
-
- Identifiers
- Name database objects─databases, tables, views, columns, indexes,
- triggers, procedures, defaults, rules, and so on.
-
- IF...ELSE
- Impose conditions on the execution of an SQL statement.
-
- INSERT
- Adds new rows to a table or view.
-
- Joins
- Compare two or more tables (or views).
-
- KILL
- Kills a process.
-
- LOAD DATABASE
- Loads a backup copy of a user database and its transaction log that was
- created with DUMP DATABASE.
-
- LOAD TRANSACTION
- Loads a backup copy of the transaction log.
-
- Mathematical Functions
- Return values commonly needed for operations on mathematical data.
-
- Null Values
- Mark columns having an unknown value.
-
- ORDER BY Clause
- Returns query results in the specified column(s) in sorted order.
-
- Parameters
- Values supplied to a stored procedure.
-
- PRINT
- Prints a user-defined message on the user's screen.
-
- RAISERROR
- Prints a user-defined error message on the user's screen and sets a system
- flag to record that an error has occurred.
-
- READTEXT
- Reads text and image values, starting from a specified offset and reading
- a specified number of bytes.
-
- RECONFIGURE
- Part of the procedure that sets configuration options, which control
- various aspects of SQL Server's memory allocation and performance.
-
- RETURN
- Exits unconditionally from a query or procedure.
-
- REVOKE
- Revokes permissions from users.
-
- ROLLBACK TRANSACTION
- Rolls back a user-specified transaction to the last savepoint inside a
- transaction or to the beginning of a transaction.
-
- Row Aggregate Functions
- Generate summary values that appear as additional rows in the query
- results.
-
- SAVE TRANSACTION
- Sets a savepoint within a transaction.
-
- Search Conditions
- Set the conditions in a WHERE or HAVING clause.
-
- SELECT
- Retrieves rows from the database.
-
- SET
- Sets SQL Server query-processing options for the duration of the user's
- work session, or inside a trigger or stored procedure.
-
- SETUSER
- Impersonates another user.
-
- SHUTDOWN
- Brings the system to a halt.
-
- String Functions
- Perform various operations on binary data, character strings, or
- expressions, including concatenation.
-
- Subqueries
- Nest a SELECT statement inside a SELECT, INSERT, UPDATE, or DELETE
- statement, another subquery, or anywhere an expression is allowed (if it
- returns a single value).
-
- System Functions
- Return special information from the database.
-
- System Procedures
- Stored procedures that SQL Server supplies to update and report from the
- system tables.
-
- Text/Image Datatypes
- The text datatype stores extremely long (up to 231) byte strings of
- printable characters.
-
- The image datatype stores extremely long (up to 231) bytes of
- hexadecimal-encoded binary data.
-
- Text/Image Functions
- Return values commonly needed for operations on text and image data.
-
- TRUNCATE TABLE
- Removes all rows in a table as quickly as possible.
-
- UPDATE
- Changes data in existing rows, either by adding new data or modifying
- existing data.
-
- UPDATE STATISTICS
- Updates information about the distribution of key values in specified
- indexes.
-
- USE
- Changes the current database.
-
- Variables (Local and Global)
- Defined entities that are assigned values.
-
- Views
- Provide an alternate way of looking at data in one or more tables.
-
- WAITFOR
- Specifies a specific time, a time interval, or an event for the execution
- of a statement block, stored procedure, or transaction.
-
- WHERE Clause
- Sets the conditions in a WHERE clause.
-
- WHILE
- Sets a condition for the repeated execution of a statement or statement
- block.
-
- Wildcard Characters
- Used with the LIKE keyword to represent any character in a string when
- searching for a char, varchar, or datetime value.
-
- WRITETEXT
- Permits nonlogged, interactive updating of an existing text field.
-
- ────────────────────────────────────────────────────────────────────────────
-
-
-
- Aggregate Functions
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Returns summary values. Aggregate functions are SUM, AVG, COUNT, COUNT(*),
- MAX, and MIN. They can be used in the select list or the HAVING clause of a
- SELECT statement or subquery, and often appear in a statement that includes
- a GROUP BY clause. (A similar type of aggregate function, called a row
- aggregate function, is used in the COMPUTE clause.)
-
-
-
- Syntax
-
- Aggregate functions have the following syntax:
-
- aggregate_function ([DISTINCT] expression)
-
- Aggregate functions, their individual syntax, and the results they produce
- are shown in the following table. Note that expression is usually a column
- name. DISTINCT is optional for SUM, AVG, and COUNT but must not be used with
- COUNT(*). COUNT(*) takes no parameters. The numeric datatypes are int,
- smallint, tinyint, float, and money.
-
- ╓┌───────────────────┌────────────────────────┌──────────────────────────────╖
- Aggregate Function Parameters Result
- ────────────────────────────────────────────────────────────────────────────
- AVG ([DISTINCT] expression) The average of the [distinct]
- values in the numeric column
-
- COUNT ([DISTINCT] expression) The number of [distinct]
- non-null values in the column
-
- COUNT (*) The number of selected rows
-
- MAX (expression) The highest value in the
- expression
-
- MIN (expression) The lowest value in the
- expression
-
- Aggregate Function Parameters Result
- ────────────────────────────────────────────────────────────────────────────
- AVG ([DISTINCT] expression) The average of the [distinct]
- SUM ([DISTINCT]expression) The total of the [distinct]
- values in the numeric column
-
- ────────────────────────────────────────────────────────────────────────────
-
-
-
-
- Examples
-
- A. select avg(advance), sum(ytd_sales)
- from titles
- where type = "business"
-
- Example A calculates the average advance and the sum of year-to-date sales
- for all business books. Each of these aggregate functions produces a single
- summary value for all of the retrieved rows.
-
- B. select type, avg(advance), sum(ytd_sales)
- from titles
- group by type
-
- When used with a GROUP BY clause, aggregate functions produce single values
- for each group, rather than for the whole table. The statement in example B
- produces summary values for each type of book.
-
- C. select count(distinct city)
- from authors
-
- Example C finds the number of different cities in which authors live.
-
- D. select type
- from titles
- group by type
- having count(*) > 1
-
- Example D lists the types in the titles table but eliminates the types that
- include only one book or none.
-
- E. select pub_id, sum(advance), avg(price)
- from titles
- group by pub_id
- having sum(advance) > $25000 and avg(price) > $15
-
- Example E groups the titles table by publisher, and includes only those
- groups of publishers who have paid more than $25,000 in total advances and
- whose books average more than $15 in price.
-
-
- Options
-
- DISTINCT
- Eliminates duplicate values before an aggregate function is applied.
- DISTINCT is optional with SUM, AVG, and COUNT.
-
- column_name
- The name of a column.
-
- expression
- A column name, a constant, a function, any combination of column names,
- constants, and functions connected by arithmetic or bitwise operators, or
- a subquery. In the context of the aggregate functions, an expression is
- usually a column name. (See "Expressions" for more information.)
-
- SUM
- Finds the sum of all values in the column. SUM can be used with numeric
- columns only. Null values are ignored.
-
- AVG
- Finds the average of the values in the column. AVG can be used with
- numeric columns only. Null values are ignored.
-
- COUNT
- Finds the number of non-null values in the column. When DISTINCT is
- specified, COUNT finds the number of unique non-null values. COUNT can be
- used with both numeric and character columns. Null values are ignored.
-
- COUNT(*)
- Finds the number of rows. COUNT(*) does not take any parameters and cannot
- be used with DISTINCT. All rows are counted, regardless of the presence of
- null values.
-
- MAX
- Finds the maximum value in the column. MAX can be used with numeric,
- character, and datetime columns. With character columns, MAX finds the
- value that is highest in the collating sequence. MAX ignores any null
- values. MAX cannot be used with bit columns. DISTINCT is not available
- since it is not meaningful with MAX.
-
- MIN
- Finds the minimum value in the column. MIN can be used with numeric,
- character, and datetime columns. With character columns, MIN finds the
- value that is lowest in the sort sequence. MIN ignores any null values.
- MIN cannot be used with bit columns. DISTINCT is not available since it is
- not meaningful with MIN.
-
-
- Comments
-
- Aggregate functions can be used in the select list or in the HAVING clause
- of a SELECT statement. They cannot be used in a WHERE clause.
-
- Aggregate functions, which calculate summary values from the non-null values
- in a particular column, can be applied to all rows in a table, in which case
- they produce a single value, called a scalar aggregate function.
- Alternatively, they can be applied to all rows that have the same value in a
- specified column or expression (with the GROUP BY and, optionally, the
- HAVING clause), in which case they produce a value for each group, called a
- vector aggregate function. The results of the aggregate functions are shown
- as new columns.
-
- You can nest a vector aggregate function inside a scalar aggregate function.
- For example:
-
- ╓┌─┌─────────────────────────────────────────┌─────────────┌─────────────────╖
- ────────────────────────────────────────────────────────────────────────────
- select type, avg(price), avg(avg(price))
- from titles
- group by type
-
- type
- ------------ ------------ ------------
- ────────────────────────────────────────────────────────────────────────────
- ------------ ------------ ------------
- UNDECIDED NULL NULL
- business 13.73 15.23
- mod_cook 11.49 15.23
- popular_comp 21.48 15.23
- psychology 13.50 15.23
- trad_cook 15.96 15.23
-
- (6 rows affected)
-
-
- The GROUP BY clause applies to the vector aggregate function─in this case,
- AVG(price).
-
- The scalar aggregate function, AVG(AVG(price)), returns the average price of
- all books in the titles table.
-
- In standard SQL, all the columns in a select list that includes an aggregate
- function must either have aggregate functions applied to them or be in the
- GROUP BY list. TRANSACT-SQL has no such restrictions.
-
- Example A shows a SELECT statement with the standard restrictions; example B
- shows the same statement with another item (title_id) added to the select
- list to illustrate the difference in displays. These extra columns can also
- be referenced in a HAVING clause.
-
- A. select type, avg(price), avg(advance)
- from titles
-
- group by type
-
- ╓┌─┌──────────────────┌─────────────┌────────────────────────────────────────╖
- ────────────────────────────────────────────────────────────────────────────
- type
- ------------ ------------ ------------
- UNDECIDED NULL NULL
- business 13.73 6,281.25
- mod_cook 11.49 7,500.00
- popular_comp 21.48 7,500.00
- psychology 13.50 4,255.00
- trad_cook 15.96 6,333.33
- ────────────────────────────────────────────────────────────────────────────
- trad_cook 15.96 6,333.33
- (6 rows affected)
-
-
- B. select type, title_id, avg(price), avg(advance)
- from titles
- group by type
- order by type
-
- ╓┌─┌───────────────────┌───────────┌───────────┌─────────────────────────────╖
- ────────────────────────────────────────────────────────────────────────────
- type title_id
- ------------ ---------- ---------- -----------
- UNDECIDED MC3026 NULL NULL
- business BU1032 13.73 6,281.25
- business BU1111 13.73 6,281.25
- business BU2075 13.73 6,281.25
- business BU7832 13.73 6,281.25
- mod_cook MC2222 11.49 7,500.00
- mod_cook MC3021 11.49 7,500.00
- ────────────────────────────────────────────────────────────────────────────
- mod_cook MC3021 11.49 7,500.00
- popular_comp PC1035 21.48 7,500.00
- popular_comp PC8888 21.48 7,500.00
- popular_comp PC9999 21.48 7,500.00
- psychology PS1372 13.50 4,255.00
- psychology PS2091 13.50 4,255.00
- psychology PS2106 13.50 4,255.00
- psychology PS3333 13.50 4,255.00
- psychology PS7777 13.50 4,255.00
- trad_cook TC3218 15.96 6,333.33
- trad_cook TC4203 15.96 6,333.33
- trad_cook TC7777 15.96 6,333.33
-
- (18 rows affected)
-
-
- You can use either a column name or any other expression (except a column
- heading or alias) after GROUP BY.
-
- Null values in the GROUP BY column are put into a single group.
-
- The COMPUTE clause in a SELECT statement uses row aggregate functions to
- produce summary values. The row aggregate functions make it possible to
- retrieve detail and summary rows with one statement. The following example
- illustrates this feature:
-
- select type, title_id, price, advance
- from titles
- where type = "psychology"
- order by type
- compute sum(price), sum(advance) by type
-
- ╓┌───────┌───────────────────┌─────────────┌───────────────────┌─────────────
- ─────────────────────────────────────────────────────────────────────────────
- type title_id price advance
-
- ------------ ------------ ---------- -----------
-
- psychology PS1372 21.59 7,000.00
-
- psychology PS2091 10.95 2,275.00
- ─────────────────────────────────────────────────────────────────────────────
- psychology PS2091 10.95 2,275.00
-
- psychology PS2106 7.00 6,000.00
-
- psychology PS3333 19.99 2,000.00
-
- psychology PS7777 7.99 4,000.00
-
- sum sum
-
- -----------67.52 -------------21
-
-
-
- (6 rows affected)
-
-
-
- Note the difference in display between this example and the earlier examples
- without COMPUTE.
-
- You can use a HAVING clause without a GROUP BY clause.
-
- Because each aggregate function in a query requires its own work table, a
- query using aggregate functions can exceed the maximum number of tables
- allowed in a query (16).
-
- If there are columns in the select list that neither have aggregate
- functions applied to them nor are included in the query's GROUP BY clause
- (illegal in standard SQL), the meanings of HAVING and WHERE are somewhat
- different. In this situation, a WHERE clause restricts the rows included in
- the calculation of the aggregate function but does not restrict the rows
- returned by the query. Conversely, a HAVING clause restricts the rows
- returned by the query but does not affect the calculation of the aggregate
- function. See "GROUP BY and HAVING Clauses" for examples.
-
- When you sum or average integer data, TRANSACT-SQL treats the result as an
- int value, even if the datatype of the column is smallint or tinyint. To
- avoid overflow errors in DB-LIBRARY programs, declare all variables for
- results of averages or sums as type int.
-
-
- See Also
-
- COMPUTE Clause, Functions, GROUP BY and HAVING Clauses, Row Aggregate
- Functions, Search Conditions, SELECT, WHERE Clause
-
-
- ALTER DATABASE
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Increases the amount of disk space allocated to a database.
-
-
- Syntax
-
- ALTER DATABASE database_name
- [ON {DEFAULT | database_device} [=size] [, database_device
- [= size]]...]
-
-
- Examples
-
- A. alter database pubs
-
- B. alter database pubs
- on file1 = 3
-
-
- Options
-
- database_name
- The name of the database whose storage size is to be changed.
-
- ON
- Indicates a size and/or location for the database extension. The default
- extension size is 1 megabyte.
-
- DEFAULT
- Indicates that ALTER DATABASE can put the database extension on any
- default database device(s) (as shown in sysdevices.status). 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 on 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 value is 1 megabyte for a
- default database device and 2 megabytes for a nondefault database device.
- Legal values range from 1 to 215. If SQL Server can't allocate the
- requested size, it will do as much as it can in half-megabyte units with a
- minimum of 1 megabyte.
-
-
- Comments
-
- The Database Owner or System Administrator must be using the master database
- to execute the ALTER DATABASE statement.
-
- If you don't specify a location or size, the default location is any default
- database device indicated in sysdevices and the default size is 1 megabyte.
-
-
- If SQL Server can't handle your request, it allocates as much space as
- possible on each database device and prints a message telling how much space
- has been allocated on each database device.
-
- It is important to back up the master database with the DUMP DATABASE or
- DUMP TRANSACTION statement after each use of ALTER DATABASE. This makes
- recovery easier and safer if the master database is damaged. (If you use
- ALTER DATABASE and fail to back up the master database, you may subsequently
- be able to recover the changes with DISK REFIT.)
-
- To increase the amount of storage space allocated for the transaction log,
- give the name of the log's database device in the ON clause when you execute
- the ALTER DATABASE statement. Then execute sp_logdevice to make the newly
- allocated space available for the log.
-
- To rename a database, execute the sp_renamedb system procedure, which takes
- the old name of the database and its new name as parameters. For information
- on a database, execute sp_helpdb. To get a report on the amount of space
- used in a database, execute sp_spaceused.
-
-
- Permissions
-
- ALTER DATABASE permission defaults to the Database Owner if he or she has
- CREATE DATABASE permission. It cannot be transferred. This prevents
- unauthorized users from allocating too much disk space. The System
- Administrator can also alter databases.
-
-
- See Also
-
- CREATE DATABASE, DROP DATABASE, sp_diskdefault, sp_helpdb, sp_logdevice,
- sp_renamedb, sp_spaceused
-
-
- ALTER TABLE
- ────────────────────────────────────────────────────────────────────────────
-
- Function
-
- Adds new columns to an existing table.
-
-
- Syntax
-
- ALTER TABLE [[database.]owner.]table_name
- ADD column_name datatype NULL [, column_name datatype NULL...]
-
-
- Examples
-
- alter table publishers
- add manager_name varchar(40) null
-
-
- Options
-
- datatype
- Any of the system datatypes except bit and any user-defined datatype
- except those based on bit.
-
- NULL
- A required parameter because the initial values in the new column must be
- set to NULL in already existing rows.
-
-
- Comments
-
- Columns of type bit cannot be added to an existing table.
-
- The number of columns in a table cannot exceed 250.
-
- To rename a table, execute the sp_rename system procedure. For information
- on a table and its columns, use sp_help.
-
-
- Permissions
-
- ALTER TABLE permission defaults to the table owner. It cannot be
- transferred. The System Administrator can alter users' tables.
-
-
- See Also
-
- CREATE TABLE, DROP TABLE, sp_help, sp_rename
-
-
- Batch Queries
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- A batch or batch file is a set of SQL statements submitted together and
- executed as a group, one after the other. A batch is terminated by an
- end-of-batch signal. With the isql program, the signal is the go command on
- a line by itself. For details on the isql program, see Chapter 3, "Utility
- Programs."
-
-
- Examples
-
- A. select count(*) from titles
- select count(*) from authors
- go
-
- B. create table test
- (column1 char(10), column2 int)
- insert test
- values ("hello", 598)
- select * from test
- go
-
- C. use master
- go
- select count(*)
- from sysdatabases
- go
-
-
- Comments
-
- CREATE PROCEDURE, CREATE RULE, CREATE DEFAULT, CREATE TRIGGER, and CREATE
- VIEW statements cannot be combined with other statements in a batch. They
- must be submitted singularly. CREATE DATABASE, CREATE TABLE, and CREATE
- INDEX can be combined with other statements in a single batch.
-
- USE must be submitted in a batch before you can reference objects in that
- database.
-
- You cannot drop an object and then reference or re-create it in the same
- batch.
-
- 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.
-
- You can submit batches through the SQL Server Administration Facility or
- from a file with the isql program. A file submitted to isql can include more
- than one batch of SQL statements if each batch is terminated by the go
- command.
-
- If there is an error anywhere in a batch, none of its statements are
- executed. A batch is considered a transaction.
-
-
- See Also
-
- CREATE DEFAULT, CREATE PROCEDURE, CREATE RULE, CREATE TRIGGER, CREATE VIEW,
- SET, USE
-
-
- BEGIN...END
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Enclose a series of SQL statements so that control-of-flow language, such as
- IF...ELSE, affects the performance of the whole group.
-
-
- Syntax
-
- BEGIN
- statement_block
- END
-
-
- Examples
-
- A. if (select avg(price) from titles) < $15
- begin
- update titles
- set price = price * $2
- select title, price
- from titles
- where price > $28
- end
-
- Without BEGIN and END, the IF condition would cause execution of only one
- SQL statement.
-
- B. 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
- else
- print "Deletion successful─no sales for this title."
-
-
- Options
-
- statement_block
- A series of statements enclosed by BEGIN and END.
-
-
- Comments
-
- BEGIN...END blocks can be nested within other BEGIN...END blocks.
-
-
- See Also
-
- Control-of-Flow Language
-
-
- BEGIN TRANSACTION
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Marks the starting point of a user-specified transaction.
-
-
- Syntax
-
- BEGIN TRANsaction [transaction_name]
-
-
- Examples
-
- begin transaction royaltychange
- /* A user sets out to change the royalty split for the
- two authors of The Gourmet Microwave. Since the
- database would be inconsistent between the two updates,
- they must be grouped into a user-defined transaction. */
-
- update titleauthor
- set royaltyper = 65
- from titleauthor, titles
- where royaltyper = 75
- and titleauthor.title_id = titles.title_id
- and title = "The Gourmet Microwave"
-
- update titleauthor
- set royaltyper = 35
- from titleauthor, titles
- where royaltyper = 25
- and titleauthor.title_id = titles.title_id
- and title = "The Gourmet Microwave"
-
- save transaction percentchanged
- /* After having updated the royaltyper entries
- for the two authors, the user inserts the savepoint
- percentchanged and then determines how
- a 10% increase in the book's price would affect the
- authors' royalty earnings. */
-
- update titles
- set price = price * $1.1
- where title = "The Gourmet Microwave"
-
- select (price * royalty * ytd_sales) * royaltyper
- from titles, titleauthor
- where title = "The Gourmet Microwave"
- and titles.title_id = titleauthor.title_id
- /* The transaction is rolled back to the savepoint
- with the ROLLBACK TRANSACTION statement. */
-
- rollback transaction percentchanged
-
- commit transaction
-
- /* End of royaltychange. */
-
-
- Options
-
- transaction_name
- The name assigned to this transaction. It must conform to the rules for
- identifiers.
-
-
- Comments
-
- Define a transaction by enclosing SQL statements and/or stored procedures
- within the statements BEGIN TRANSACTION and COMMIT TRANSACTION.
-
- To cancel an entire transaction, use the statement ROLLBACK TRANSACTION
- transaction_name. All of the transaction's statements or procedures that
- have been completed are undone.
-
- To cancel part of a transaction, use the statement ROLLBACK TRANSACTION
- savepoint_name. (The savepoint was inserted inside the transaction earlier
- with a SAVE TRANSACTION statement.) All of the transaction's statements or
- procedures between the savepoint and the ROLLBACK TRANSACTION statement are
- undone.
-
- After a transaction is rolled back to a savepoint, it must proceed to
- completion (with more SQL statements if desired and a COMMIT TRANSACTION
- statement), or it must be canceled altogether (by rolling it back to its
- beginning).
-
- The ROLLBACK TRANSACTION statement must appear within a transaction: you
- can't rollback a transaction after COMMIT TRANSACTION has been entered.
-
- If no savepoint_name or transaction_name is given with the ROLLBACK
- TRANSACTION statement, the transaction is rolled back to the previous BEGIN
- TRANSACTION.
-
- The following statements cannot be used inside a user-defined transaction:
- CREATE DATABASE, CREATE TABLE, CREATE INDEX, all DROP statements, SELECT
- INTO (because it creates a table), GRANT, REVOKE, ALTER DATABASE, ALTER
- TABLE, TRUNCATE TABLE, RECONFIGURE, LOAD DATABASE, LOAD TRANSACTION, and
- DISK INIT. In addition, some of the system procedures cannot be used inside
- user-defined transactions because they create temporary tables.
-
- Transactions can be nested inside each other.
-
-
- Permissions
-
- BEGIN TRANSACTION permission defaults to all users. No permission is
- required to use it.
-
-
- See Also
-
- COMMIT TRANSACTION, ROLLBACK TRANSACTION, SAVE TRANSACTION
-
-
- BREAK
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Controls operation of statements in a WHILE loop. BREAK is often (but not
- always) activated by an IF test. BREAK causes an exit from the WHILE loop.
-
-
- Syntax
-
- WHILE
- boolean expression
- statement
- BREAK
- statement
- CONTINUE
-
-
- Examples
-
- while (select avg(price) from titles) < $30
- begin
- update titles
- set price = price * $2
- select max(price) from titles
- if (select max(price) from titles) > $50
- break
- else
- continue
- end
- begin
- print "Too much for the market to bear"
- end
-
- If the average price is less than $30, double the prices. Then select the
- maximum price. If it is less than or equal to $50, restart the WHILE loop
- and double the prices again. If the maximum price is more than $50, exit the
- WHILE loop and print a message.
-
-
- Comments
-
- BREAK causes an exit from the WHILE loop. Any statements that appear after
- the END keyword that marks the end of the loop are executed.
-
- If two or more WHILE loops are nested, the inner BREAK exits to the next
- outermost loop. First, all the statements after the end of the inner loop
- run, and then the next outermost loop restarts.
-
-
- See Also
-
- CONTINUE, Control-of-Flow Language, Expressions, WHILE
-
-
- Browse Mode
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Supports the ability to perform updates while viewing data. Browse mode is
- used in an application program using DB-LIBRARY. The FOR BROWSE clause is
- used in a SELECT statement.
-
-
- Syntax
-
- FOR BROWSE
-
-
- Examples
-
- See the SQL Server Programmer's Reference for an example of a DB-LIBRARY
- application that uses browse mode.
-
-
- Comments
-
- A table can be browsed in an application program if
-
-
- ■ Its rows have been timestamped by including a column named timestamp
- in the table definition or by adding the timestamp column with ALTER
- TABLE:
-
-
- CREATE TABLE browsetest (col1 int, timestamp, col3 char(7))
-
-
- or
-
- ALTER TABLE table_name
- ADD timestamp
-
- A column named timestamp automatically has the system datatype
- timestamp and is automatically updated.
-
- ■ It has a unique key.
-
- ■ The keywords FOR BROWSE are at the end of the SELECT statement sent to
- SQL Server.
-
-
- The use of the keyword HOLDLOCK is forbidden in a SELECT statement that
- includes the FOR BROWSE clause.
-
-
- See Also
-
- Datatypes, SELECT, sp_primarykey
-
-
-
-
-
- CHECKPOINT
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Forces all dirty pages (pages on which there have been updates since the
- last checkpoint) in the current database to be written to the disk.
- Checkpoints caused by the CHECKPOINT statement supplement automatic
- checkpoints, which occur at intervals calculated by SQL Server on the basis
- of the configurable value for maximum acceptable recovery time.
-
-
- Syntax
-
- CHECKPOINT
-
-
- Examples
-
- checkpoint
-
- All dirty pages in the current database are written to the disk, regardless
- of the system checkpoint schedule.
-
-
- Comments
-
- The CHECKPOINT statement saves work in recovery by identifying a point at
- which all completed transactions are guaranteed to have been written to the
- disk.
-
- A typical checkpoint takes one second, though this figure varies depending
- on the amount of activity on SQL Server.
-
- The automatic checkpoint interval is calculated by SQL Server on the basis
- of system activity and the recovery interval value in the system table
- syscurconfigs. The recovery interval determines checkpoint frequency by
- specifying the amount of time it should take the system to recover. Reset
- this value by executing the sp_configure system procedure and the
- RECONFIGURE statement. For more information, see the SQL Server System
- Administrator's Guide.
-
- Use the CHECKPOINT statement as a precautionary measure only in special
- circumstances. For example, if the automatic checkpoint is infrequent
- because the recovery interval is set high, you might want to use the
- CHECKPOINT statement after inserting rows with bulk copy.
-
- Use the CHECKPOINT statement after changing a database option with the
- sp_dboption system procedure.
-
- If you change a database option with sp_dboption inside a user-defined
- transaction and then roll back that transaction you must use another
- CHECKPOINT statement to make the rollback take effect on the option change.
- Here's an example:
-
- begin transaction
- use master
- <execute>
- sp_dboption 'pubs', 'single', 'true'
- <execute>
- use pubs
- <execute>
- checkpoint
- <execute>
- rollback transaction
- <execute>
- /*
- ** If the following checkpoint is not used, the
- ** "pubs" database remains single-user.
- */
- checkpoint
- <execute>
-
-
- Permissions
-
- Permission to use the CHECKPOINT statement defaults to the Database Owner.
- It cannot be transferred.
-
-
- See Also
-
- RECONFIGURE, sp_dboption
-
-
- Comments
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Provide information about SQL statements, statement blocks, and stored
- procedures.
-
-
- Syntax
-
- /* text of comment */
-
-
- Examples
-
- /* this procedure finds rules by user name */
- create procedure findmyrule @nm varchar(30) = null
- as
- if @nm is null
- begin
- print "You must give a user name"
- return
- print "I have returned"
- /* this statement follows RETURN,
- ** so won't be executed */
- end
- else /* print the rule names and IDs, and the user ID */
- select sysobjects.name, sysobjects.id, sysobjects.uid
- from sysobjects, master..syslogins
- where master..syslogins.name = @nm
- and sysobjects.uid = master..syslogins.suid
- and sysobjects.type = "R"
-
-
- Comments
-
- Comments can be inserted on a line by themselves or at the end of a command
- line. Multiple-line comments are allowed as long as they are surrounded by
- /* and */. A stylistic convention often used for multiple-line comments is
- to begin the first line with /* and subsequent lines with **. The comment is
- ended with */.
-
- There is no maximum length for comments.
-
- Comments can be nested.
-
- ────────────────────────────────────────────────────────────────────────────
- NOTE
- Do not include a go command within a comment because it will produce an
- error message.
- ────────────────────────────────────────────────────────────────────────────
-
-
- COMMIT TRANSACTION
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Marks the ending point of a user-defined transaction.
-
-
- Syntax
-
- COMMIT TRANsaction [transaction_name]
-
-
- Examples
-
- begin transaction royaltychange
- /* A user sets out to change the royalty split for the
- two authors of The Gourmet Microwave. Since the
- database would be inconsistent between the two updates,
- they must be grouped into a user-defined transaction. */
-
- update titleauthor
- set royaltyper = 65
- from titleauthor, titles
- where royaltyper = 75
- and titleauthor.title_id = titles.title_id
- and title = "The Gourmet Microwave"
-
- update titleauthor
- set royaltyper = 35
- from titleauthor, titles
- where royaltyper = 25
- and titleauthor.title_id = titles.title_id
- and title = "The Gourmet Microwave"
-
- save transaction percentchanged
- /* After having updated the royaltyper entries
- for the two authors, the user inserts the savepoint
- percentchanged and then experiments to see how
- a 10% increase in the book's price would affect the
- authors' royalty earnings. */
-
- update titles
- set price = price * $1.1
- where title = "The Gourmet Microwave"
-
- select (price * royalty * ytd_sales) * royaltyper
- from titles, titleauthor
- where title = "The Gourmet Microwave"
- and titles.title_id = titleauthor.title_id
- /* The transaction is rolled back to the savepoint
- with the ROLLBACK TRANSACTION statement. */
-
- rollback transaction percentchanged
-
- commit transaction
-
- /* End of royaltychange. */
-
-
- Options
-
- transaction_name
- The name assigned to the transaction. It must conform to the rules for
- identifiers. (See "Identifiers" for details.)
-
-
- Comments
-
- Define a transaction by enclosing SQL statements and/or stored procedures
- with the BEGIN TRANSACTION and COMMIT TRANSACTION statements.
-
- A savepoint is a marker set by the SAVE TRANSACTION savepoint_name statement
- within a transaction. You can cancel part of a transaction with the
- following statement:
-
- rollback tran savepoint_name
-
- All of the statements or procedures between the savepoint and ROLLBACK
- TRANSACTION are undone.
-
- To cancel an entire transaction, use the ROLLBACK TRANSACTION statement. All
- of the transaction's statements or procedures are undone.
-
- If no savepoint name or transaction name is given with the ROLLBACK
- TRANSACTION statement, the transaction is rolled back to the previous BEGIN
- TRANSACTION.
-
- The ROLLBACK TRANSACTION statement must appear within a transaction: you
- can't rollback a transaction after COMMIT TRANSACTION has been entered.
-
- After a transaction is rolled back to a savepoint, it must proceed to
- completion (with more SQL statements if desired and a COMMIT TRANSACTION
- statement), or it must be canceled altogether (by rolling it back to its
- beginning). Until you execute COMMIT TRANSACTION, SQL Server will consider
- all subsequent statements to be part of the transaction, until it encounters
- another BEGIN TRANSACTION statement. At that point, SQL Server rolls the
- original transaction back and displays an error message.
-
- You may want to insert a comment giving the name of the transaction being
- ended, as in the example.
-
-
- Permissions
-
- COMMIT TRANSACTION permission defaults to all users. No permission is
- required to use it.
-
-
- See Also
-
- BEGIN TRANSACTION, ROLLBACK TRANSACTION, SAVE TRANSACTION
-
-
- COMPUTE Clause
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Generates summary values in a SELECT statement with row aggregate functions
- (SUM, AVG, MIN, MAX, and COUNT). The summary values appear as additional
- rows in the query results (unlike the aggregate function results, which
- appear as new columns), which allows you to see the detail and summary rows
- in one set of results. You can calculate summary values for subgroups, and
- you can calculate more than one aggregate function for the same group.
-
-
- Syntax
-
- COMPUTE row_aggregate(column_name)
- [, row_aggregate(column_name)...]
- [BY column_name [, column_name]...]
-
-
- Examples
-
- A. select type, price
- from titles
- where price > $12
- and type like "%cook"
- order by type, price
- compute sum(price) by type
-
- ╓┌─┌──────────────────┌──────────────────────────────────────────────────────╖
- ────────────────────────────────────────────────────────────────────────────
- type price
- --------- ------------
- mod_cook 19.99
- sum
- ------------
- 19.99
- type price
- --------- ------------
- trad_cook 14.99
- trad_cook 20.95
- sum
- ------------
- ────────────────────────────────────────────────────────────────────────────
- ------------
- 35.94
-
- (5 rows affected)
-
-
- Example A calculates the sum of the prices of each type of cookbook that
- costs more than $12.
-
- B. select type, price, advance
- from titles titles
- where price > $12
- and type like "%cook"
- order by type, price
- compute sum(price), sum(advance) by type
-
- ╓┌─┌──────────────────┌──────────┌───────────────────────────────────────────╖
- ────────────────────────────────────────────────────────────────────────────
- type price advance
- --------- --------- ------------
- ────────────────────────────────────────────────────────────────────────────
- --------- --------- ------------
- mod_cook 19.99 0.00
- sum sum
- --------- ------------
- 19.99 0.00
- type price advance
- --------- --------- ------------
- trad_cook 14.99 8,000.00
- trad_cook 20.95 7,000.00
- sum sum
- --------- ------------
- 35.94 15,000.00
-
- (5 rows affected)
-
-
- Example B calculates the sum of the prices and advances for each type of
- cookbook that costs more than $12.
-
- C. select type, price, advance
- from titles
- where price > $12
- and type like "%cook"
- order by type, price
- compute sum(price), max(advance) by type
-
- ╓┌─┌──────────────────┌─────────────┌────────────────────────────────────────╖
- ────────────────────────────────────────────────────────────────────────────
- type price advance
- --------- ------------ ------------
- mod_cook 19.99 0.00
- sum
- ------------
- 19.99
- max
- ------------
- 0.00
- type price advance
- ---------- ------------ ------------
- trad_cook 14.99 8,000.00
- trad_cook 20.95 7,000.00
- ────────────────────────────────────────────────────────────────────────────
- trad_cook 20.95 7,000.00
- sum
- ------------
- 35.94
- max
- ------------
- 8,000.00
- (5 rows affected)
-
-
- Example C calculates the sum of the prices and maximum advance of each type
- of cookbook that costs more than $12.
-
- D. select type, pub_id, price
- from titles
- where price > $10
- and type = "psychology"
- order by type, pub_id, price
- compute sum(price) by type, pub_id
-
- ╓┌─┌──────────────────┌────────────┌─────────────────────────────────────────╖
- ────────────────────────────────────────────────────────────────────────────
- type pub_id price
- ------------ --------- ------------
- psychology 0736 10.95
- psychology 0736 19.99
- sum
- ------------
- 30.94
- type pub_id price
- ------------ ---------- ------------
- psychology 0877 21.59
- sum
- ------------
- 21.59
- (5 rows affected)
-
-
- Example D breaks on type and pub_id and calculates the sum of the prices of
- psychology books by type-publisher ID combination.
-
- E. select type, pub_id, price
- from titles
- where price > $10
- and type = "psychology"
- order by type, pub_id, price
- compute sum(price) by type, pub_id
- compute sum(price) by type
-
- ╓┌─┌──────────────────┌───────────┌──────────────────────────────────────────╖
- ────────────────────────────────────────────────────────────────────────────
- type pub_id price
- ----------- --------- ------------
- psychology 0736 10.95
- psychology 0736 19.99
- sum
- ------------
- 30.94
- type pub_id price
- ---------- --------- ------------
- psychology 0877 21.59
- sum
- ────────────────────────────────────────────────────────────────────────────
- sum
- ------------
- 21.59
- sum
- ------------
- 52.53
- (6 rows affected)
-
-
- Example E calculates the grand total of the prices of psychology books that
- cost more than $10, in addition to sums by type and pub_id.
-
- F. select type, price, advance
- from titles
- where price > $10
- and type like "%cook"
- compute sum(price), sum(advance)
-
- ╓┌─┌──────────────────┌─────────────┌────────────────────────────────────────╖
- ────────────────────────────────────────────────────────────────────────────
- ────────────────────────────────────────────────────────────────────────────
- type price advance
- --------- ----------- ------------
- mod_cook 19.99 0.00
- trad_cook 20.95 8,000.00
- trad_cook 11.95 4,000.00
- trad_cook 14.99 7,000.00
- sum sum
- ------------ -----------
- 67.88 19,000.00
- (5 rows affected)
-
-
- Example F calculates the grand totals of the prices and advances of cooking
- books that cost over $10.
-
-
- Options
-
- row_aggregate
- One of the following:
-
- ╓┌─────────────────────────────────┌─────────────────────────────────────────╖
- Function Definition
- ────────────────────────────────────────────────────────────────────────────
- SUM Total of values in the (numeric) column
-
- AVG Average of values in the (numeric)
- column
-
- MIN Lowest value in the column
-
- MAX Highest value in the column
-
- COUNT Number of values in the column
-
- column_name The name of a column, which must be
- enclosed in parentheses. Only numeric
- columns can be used with SUM and AVG.
- One COMPUTE clause can apply the same
- function to several columns. (See
- example B.) When using more than one
- Function Definition
- ────────────────────────────────────────────────────────────────────────────
- example B.) When using more than one
- function, use more than one COMPUTE
- clause. (See example E.)
-
- BY Indicates that row aggregate function
- values are to be calculated for
- subgroups. Whenever the value of the BY
- item changes, row aggregate function
- values are generated. If you use BY, you
- must use ORDER BY. Listing more than one
- item after BY breaks a group into
- subgroups and applies a function at each
- level of grouping.
-
- ────────────────────────────────────────────────────────────────────────────
-
-
-
-
- Comments
-
- Row aggregate functions make it possible to retrieve detail and summary rows
- with one statement. Aggregate functions, on the other hand, ordinarily
- produce a single value for all selected rows in the table or for each group,
- and these summary values are shown as new columns. The following examples
- illustrate the differences:
-
- A. select type, sum(price), sum(advance)
- from titles
- where type like "%cook"
- group by type
-
- ────────────────────────────────────────────────────────────────────────────
- type
- ------------ --------- ----------
- mod_cook 22.98 15,000.00
- trad_cook 47.89 19,000.00
- (2 rows affected)
-
- B. select type, price, advance
- from titles
- where type like "%cook"
- order by type
- compute sum(price), sum(advance) by type
-
- ╓┌─┌──────────────────┌─────────────┌────────────────────────────────────────╖
- ────────────────────────────────────────────────────────────────────────────
- type price advance
- --------- ------------ ------------
- mod_cook 2.99 15,000.00
- mod_cook 19.99 0.00
- sum sum
- ------------ ------------
- 22.98 15,000.00
- type price advance
- --------- ------------ ------------
- trad_cook 11.95 4,000.00
- trad_cook 14.99 8,000.00
- trad_cook 20.95 7,000.00
- sum sum
- ----------- ------------
- ────────────────────────────────────────────────────────────────────────────
- ----------- ------------
- 47.89 19,000.00
- (7 rows affected)
-
-
- The columns in the COMPUTE clause must appear in the select list.
-
- You can't use SELECT INTO in the same statement with a COMPUTE clause
- because statements that include COMPUTE do not generate normal tables.
-
- If you use COMPUTE BY, you must also use an ORDER BY clause. The columns
- listed after COMPUTE BY must be identical to or a subset of those listed
- after ORDER BY, and must be in the same left-to-right order, start with the
- same expression, and not skip any expressions. For example, if the ORDER BY
- clause is
-
- order by a, b, c
-
- the COMPUTE BY clause can be any of these:
-
- compute by a, b, c
- compute by a, b
- compute by a
-
- The COMPUTE keyword can be used without BY to generate grand totals, grand
- counts, and so on. ORDER BY is optional if you use the COMPUTE keyword
- without BY. See example F.
-
- In a SELECT statement with a COMPUTE clause, the order of columns in the
- select list overrides the order of the aggregate functions in the COMPUTE
- clause. DB-LIBRARY programmers must be aware of this to put the aggregate
- function results in the right place. See "Row Aggregate Functions" for an
- example.
-
-
- See Also
-
- Aggregate Functions, GROUP BY and HAVING Clauses, Row Aggregate Functions,
- SELECT
-
-
- CONTINUE
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Controls operation of statements in a WHILE loop. CONTINUE is often (but not
- always) activated by an IF test. CONTINUE causes the WHILE loop to restart.
-
-
-
- Syntax
-
- WHILE
- boolean expression
- statement
- BREAK
- statement
- CONTINUE
-
-
- Examples
-
- while (select avg(price) from titles) < $30
- begin
- update titles
- set price = price * $2
- select max(price) from titles
- if (select max(price) from titles) > $50
- break
- else
- continue
- end
- begin
- print "Too much for the market to bear"
- end
-
- If the average price is less than $30, double the prices. Then select the
- maximum price. If it is less than or equal to $50, restart the WHILE loop
- and double the prices again. If the maximum price is more than $50, exit the
- WHILE loop and print a message.
-
-
- Comments
-
- CONTINUE causes the WHILE loop to restart, skipping any statements after
- CONTINUE.
-
-
- See Also
-
- BREAK, Expressions, WHILE
-
-
- Control-of-Flow Language
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Controls the flow of execution of SQL statements, statement blocks, and
- stored procedures.
-
-
- Statements
-
- BEGIN
- Begins a statement block.
-
- ...END
- Ends a statement block.
-
- BREAK
- Exits the innermost WHILE loop.
-
- ...CONTINUE
- Restarts a WHILE loop.
-
- DECLARE
- Declares local variables.
-
- GOTO label:
- Goes to label:, a position in a statement block.
-
- IF
- Defines conditional execution.
-
- ...ELSE
- Defines alternate execution when a condition is false.
-
- PRINT
- Prints a user-defined message on the user's screen.
-
- RAISERROR
- Prints a user-defined message on the user's screen and sets a system flag
- (in the global variable @ERROR) to record the fact that an error condition
- has occurred.
-
- RETURN
- Exits unconditionally.
-
- WAITFOR
- Sets a delay for statement execution.
-
- WHILE
- Repeats statements while condition is true.
-
- /* comment */
- Inserts a comment anywhere in an SQL statement.
-
-
- Comments
-
- Control-of-flow language can be used with interactive SQL statements, in
- batches, and in stored procedures.
-
-
- See Also
-
- Batch Queries, BEGIN...END, BREAK, Comments, CONTINUE, CREATE PROCEDURE,
- CREATE TRIGGER, DECLARE, GOTO, IF...ELSE, Parameters, PRINT, RAISERROR,
- RETURN, Variables (Local and Global), WAITFOR, WHILE
-
-
- Conversion Function
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Converts expressions of one datatype to another datatype. Also obtains a
- variety of special date formats.
-
-
- Syntax
-
- CONVERT(datatype, expression [, style])
-
-
- Examples
-
- A. select title, convert(char(12), ytd_sales)
- from titles
-
- B. select title, ytd_sales
- from titles
- where convert(char(20), ytd_sales) like "1%"
-
- C. select convert(char(12), getdate(), 3)
-
- Example C converts the current date to style "3", dd/mm/yy.
-
-
- Options
-
- datatype
- Any system datatype (for example, char(10), varbinary(50), int) into which
- the expression is to be converted. User-defined datatypes cannot be used.
- If no length is specified when converting to char, varchar, binary, or
- varbinary datatypes, the data adapts to any size necessary. The maximum
- length you can specify when converting to these types is 255.
-
- expression
- The value to be converted.
-
- style
- The style of date representation you desire when converting to char or
- varchar from datetime data. Add 100 to a style value to get a four-place
- year that includes the century (yyyy).
-
- ╓┌───────────────────┌──────────────────┌──────────────────┌─────────────────
- Without With Standard Output
- Century Century
- (yy) (yyyy)
- ─────────────────────────────────────────────────────────────────────────────
- - 0 or 100 default mon dd yyyy
- hh:miAM (or PM)
-
- 1 101 USA mm/dd/yy
-
- 2 102 ANSI yy.mm.dd
-
- 3 103 British/French dd/mm/yy
-
- 4 104 German dd.mm.yy
-
- 5 105 Italian dd-mm-yy
-
- 6 106 - dd mon yy
- Without With Standard Output
- Century Century
- (yy) (yyyy)
- ─────────────────────────────────────────────────────────────────────────────
- 6 106 - dd mon yy
-
- 7 107 - mon dd yy
-
- 8 108 - hh:mi:ss
-
- - 9 or 109 default + mon dd, yyyy
- milliseconds hh:mi:sssAM (or
- PM)
-
- 10 110 USA mm-dd-yy
-
- 11 111 JAPAN yy/mm/dd
-
- 12 112 ISO yymmdd
-
- ─────────────────────────────────────────────────────────────────────────────
- Without With Standard Output
- Century Century
- (yy) (yyyy)
- ─────────────────────────────────────────────────────────────────────────────
- ─────────────────────────────────────────────────────────────────────────────
-
-
-
- The default values (style 0 or 100 and 9 or 109) always return the century
- (yyyy).
-
-
-
- Comments
-
- Table shows the possibilities for converting datatypes.
-
- Table 1.1 Datatype Conversion Chart
-
- ╓┌───────────────┌───────┌──────────┌──────────────┌───────────────┌─────────
- ─────────────────────────────────────────────────────────────────────────────
- ─────────────────────────────────────────────────────────────────────────────
- To: binary varbinary tinyint(INT1) smallint(INT2) int(INT4)
-
- From:
-
- binary - I I I I
-
- varbinary I - I I I
-
- tinyint(INT1) E I - I I
-
- smallint(INT2) E I I - I
-
- int(INT4) E E I I -
-
- float N N I I I
-
- char E E E E E
-
- varchar E E E E E
-
- ─────────────────────────────────────────────────────────────────────────────
- money I I I I I
-
- bit I I I I I
-
- datetime E E N N N
-
- text N N N N N
-
- image E E N N N
-
- ─────────────────────────────────────────────────────────────────────────────
-
-
-
- Key:
- I Implicit conversion
- E Explicit conversion, CONVERT function must be used
- N Conversion not allowed
- - Conversion of a datatype to itself; allowed but meaningless
-
-
- SQL Server automatically handles certain datatype conversions. For example,
- if you compare a char expression and a datetime expression, or a smallint
- expression and an int expression, or char expressions of different lengths,
- SQL Server makes the conversion automatically for the comparison. You need
- not use the CONVERT function.
-
- It is never wrong to use the CONVERT function, even when you are comparing
- two expressions of exactly the same datatype.
-
- Automatic conversion is not supported for the text and image datatypes. You
- can explicitly convert text data to char or varchar, and image data to
- binary or varbinary, but the maximum length you can specify is 255. If you
- attempt a conversion that is not possible (for example, if you try to
- convert a char expression that includes letters to an int), SQL Server
- generates an error message.
-
- If you do not specify a length for the char, varchar, binary, or varbinary
- datatype to which the expression is to be converted, the data adapts to any
- size necessary.
-
- When converting to datetime, SQL Server rejects all values it cannot
- recognize as dates (including dates earlier than January 1, 1753).
-
- Converting to bit changes any non-zero value to a 1.
-
- When converting to money from integer datatypes, units are assumed to be
- dollars. For example, the integer value of 4 would be converted to the money
- equivalent of 4 dollars.
-
- Expressions of type char or varchar being converted to an integer datatype
- must consist only of digits and an optional plus (+) or minus (-) sign.
- Leading blanks are ignored.
-
- Expressions of type char or varchar being converted to money can also
- include an optional decimal point and dollar sign ($).
-
- Expressions of type char or varchar being converted to float can also
- include optional exponential notation (a lowercase "e" or uppercase "E"
- followed by an optional + or - and then a number).
-
- When char or varchar expressions are converted to a character datatype of a
- different size, values too long for the new datatype are truncated.
-
- Converting to binary is used to display the internal representation of a
- value. If lengths differ, the binary value is padded with zeros on the
- right.
-
- You can convert int, smallint, and tinyint to binary or varbinary, but if
- you convert the binary value back to an integer value, it will be different.
- In addition, if the integer is longer than the specified binary length, it
- is truncated without notice.
-
- When converting between types with a different number of decimal points, the
- value is truncated. For example, the result of the following is "10":
-
- select convert(int, 10.672)
-
- You can convert any datatype to binary or varbinary, but if the binary field
- is too short and the value being converted is truncated, the data may be
- meaningless.
-
- The type conversion function can be used in the select list, in the WHERE
- clause, and anywhere an expression is allowed.
-
-
- See Also
-
- Datatypes, Date Functions, Functions, Mathematical Functions, String
- Functions, Text/Image Functions
-
-
- CREATE DATABASE
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Creates a new database. You must be in the master database to create a new
- database.
-
-
- Syntax
-
- CREATE DATABASE database_name
- [ON {DEFAULT | database_device} [= size] [, database_device
- [= size]]...]
-
-
- Examples
-
- A. create database pubs
-
- B. create database pubs
- on default = 4
-
- C. create database pubs
- on file1 = 3, file2 = 2
-
-
- Options
-
- database_name
- The name of the new database. It must conform to the rules for
- identifiers.
-
- ON
- Indicates that you want to specify a location and (optionally) a size for
- the database.
-
- DEFAULT
- Indicates that CREATE DATABASE can put the new database on any default
- database device(s) (as shown in sysdevices.status). To specify a size for
- the database without specifying a location, use "ON DEFAULT = size". 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 on which you want to locate the
- database. A database can occupy different amounts of space on each of
- several database devices. DISK INIT is used to allocate space for a
- database device.
-
- size
- The amount of space allocated to the database, in megabytes. The
- SQL-Server-supplied default size is 2 megabytes. The System Administrator
- can change the default size by editing the system table
- master..sysconfigures, executing the RECONFIGURE statement and restarting
- SQL Server. 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 215.
-
-
- Comments
-
- You must be using the master database to create a new user database.
-
- SQL Server can manage up to 32,767 databases.
-
- When the CREATE DATABASE statement is executed, SQL Server makes a copy of
- the model database, which initially contains the system tables. You can
- update the model database just like any other database to add your own
- tables, stored procedures, user datatypes, system variables, and so on. The
- default database size in master..sysconfigures must be at least as large as
- the model database.
-
- Only one database can be created at a time. If two database creation
- requests collide, one user will get the message "MODEL database in use:
- cannot create new database."
-
- If you don't specify a location and size for a database, the default
- location is any default database device indicated in master..sysdevices, and
- the default size is the size of the model database.
-
- If SQL Server can't give you as much space as you want where you've
- requested it, it creates the database anyway, giving you as much space as
- possible on each database device and prints a message telling how much space
- was allocated where.
-
- Each new database inherits its database option settings from the model
- database. For example, the database option select into/bulkcopy is
- originally set to "off". You can change that default with the sp_dboption
- system procedure.
-
- Since the CREATE DATABASE statement must clear every page (to guarantee the
- database can be recovered), it takes some number of seconds per megabyte to
- complete.
-
- It is important to back up the master database with the DUMP DATABASE or
- DUMP TRANSACTION statement after each use of CREATE DATABASE. This makes
- recovery easier and safer in case the master database is damaged. (If you
- create a database and fail to back up master, you may be able to recover the
- changes with DISK REFIT.)
-
- Whenever you create a database larger than about 4 megabytes, you should
- assign it to at least two separate database devices with the CREATE DATABASE
- statement and then use sp_logdevice to put the database's syslogs table on
- one of these database devices. This is essential to guarantee that SQL
- Server's roll-forward mechanism works correctly. Putting the transaction log
- and the rest of the database on different database devices also improves
- performance.
-
- ────────────────────────────────────────────────────────────────────────────
- NOTE
-
- A smaller database can be created on a single database device and the
- transaction log stored together with the rest of the database, but you must
- rely on the DUMP DATABASE statement for backups.
- ────────────────────────────────────────────────────────────────────────────
-
- The size of the database 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 database device 10% to 25% of the
- space you allocate to the database itself. It is best to start small, since
- space allocated to a transaction log database device cannot be reclaimed and
- cannot be used for storage of data.
-
- To display a report on a database or on all databases on SQL Server, execute
- the sp_helpdb system procedure. For a report on the space used in a
- database, use sp_spaceused.
-
-
- Permissions
-
- CREATE DATABASE permission defaults to the System Administrator, who can
- transfer it to other users who are listed in the sysusers table of the
- current database. However, CREATE DATABASE permission is often centralized
- to maintain control over disk allocation. See the SQL Server System
- Administrator's Guide for details. CREATE DATABASE permission is not
- included when you use the GRANT ALL statement.
-
-
- See Also
-
- ALTER DATABASE, DISK INIT, DROP DATABASE, sp_changedbowner, sp_diskdefault,
- sp_helpdb, sp_logdevice, sp_renamedb, sp_spaceused
-
-
- CREATE DEFAULT
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Specifies a value that will be inserted in a column (or in all columns of a
- user-defined datatype) if no value is explicitly supplied at insert time.
-
-
- Syntax
-
- CREATE DEFAULT [owner.]default_name
- AS constant_expression
-
-
- Examples
-
- create default namedefault as "unknown"
-
- A default value has been defined. Now you need to bind it to the appropriate
- column or user datatype with the sp_bindefault system procedure.
-
-
- Options
-
- default_name
- The name of the default. It must conform to the rules for identifiers.
-
- constant_expression
- An expression that contains only constant values (that is, it does not
- include the names of any columns or other database objects). Built-in
- functions that do not reference database objects can be included.
-
-
- Comments
-
- After you've created a default, use the sp_bindefault system procedure to
- bind it to a column or user-defined datatype.
-
- Defaults cannot be bound to SQL-Server-supplied datatypes.
-
- The default must be compatible with the datatype of the column. You cannot
- use "N/A", for example, as a default for a numeric column. If the default is
- not compatible with the column to which you've bound it, SQL Server will
- generate an error message when it tries to insert the default value (not
- when you bind it).
-
- Be sure to enclose character and date constants in quotation marks and to
- precede binary constants with "0x".
-
- If the default value is too long for the column to which you've bound it,
- the value will be truncated.
-
- CREATE DEFAULT statements cannot be combined with other SQL statements in a
- single batch.
-
- You can create a default in the current database only.
-
- Default definitions are stored in syscomments. After a default is bound to a
- particular column or user datatype, its object ID number is stored in the
- syscolumns or systypes system table. To display definitions and binding
- information, execute the sp_helptext system procedure.
-
- You must drop a default before you create a new one of the same name and you
- must unbind a default (with the sp_unbindefault system procedure) before you
- drop it.
-
- You can bind a new default to a column or datatype without unbinding the old
- one; the new default overrides the old one.
-
- You can bind one default to a user datatype and another default to a column
- of that datatype. The default most recently bound takes precedence.
-
- If a column has both a default and a rule associated with it, the default
- value must not violate the rule. A default that conflicts with a rule will
- never be inserted. SQL Server will generate an error message each time it
- attempts to insert the default.
-
- If you specify NOT NULL when you create a column and do not create a default
- for it, an error message will be generated whenever a user fails to make an
- entry in that column. The following table illustrates the relationship
- between the existence of a default and the definition of a column as NULL or
- NOT NULL. The entries in the table show the result:
-
- No entry
- ────────────────────────────────────────────────────────────────────────────
- NULL null default null null
- NOT error default error error
- NULL
-
- ────────────────────────────────────────────────────────────────────────────
-
-
- You can find the value of a default by using the sp_helptext system
- procedure with the default name as the parameter.
-
- To rename a default, use sp_rename. For a report on a default, use sp_help.
-
-
-
- Permissions
-
- CREATE DEFAULT permission defaults to the Database Owner, who can transfer
- it to other users.
-
-
- See Also
-
- Batch Queries, CREATE RULE, DROP DEFAULT, DROP RULE, sp_bindefault, sp_help,
- sp_helptext, sp_rename, sp_unbindefault
-
-
- CREATE INDEX
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Creates indexes.
-
-
- Syntax
-
- CREATE [UNIQUE] [CLUSTERED | NONCLUSTERED] INDEX index_name
- ON [[database.]owner.]table_name (column_name [, column_name]...)
- [WITH {FILLFACTOR = x , IGNORE_DUP_KEY ,
- [IGNORE_DUP_ROW | ALLOW_DUP_ROW]}]
-
-
- Examples
-
- A. create index au_id_ind
- on authors (au_id)
-
- B. create unique clustered index au_id_ind
- on authors (au_id)
-
- C. create index ind1
- on titleauthor (au_id, title_id)
-
- D. create nonclustered index zip_ind
- on authors (zip)
- with fillfactor = 25
-
-
- Options
-
- UNIQUE
- Prohibits duplicate index, or key, values. The system checks for duplicate
- key values when the index is created (if data already exists) and checks
- each time data is added with an INSERT or UPDATE. You cannot create a
- unique index if there are duplicate key values: the statement is aborted
- and an error message giving the first duplicate is printed. UPDATE or
- INSERT statements that would generate duplicate key values are rolled
- back, and SQL Server displays an error message. This is true even if the
- UPDATE or INSERT statement would have changed many rows but caused only
- one duplicate. Composite indexes (indexes in which the key value is
- composed of more than one column) can be unique.
-
- CLUSTERED
- Indicates that the physical order of rows is the same as the indexed order
- of the rows, and the bottom, or leaf, level of the clustered index
- contains the actual data pages. A clustered index almost always retrieves
- data faster than a nonclustered index. By definition, only one clustered
- index is permitted per table. The clustered index is often created on the
- table's primary key─the column or columns that uniquely identify the row.
- The primary key is declared with the sp_primarykey system procedure.
-
- NONCLUSTERED
- Indicates that there is an extra level between the index structure and the
- data itself. You can have up to 250 nonclustered indexes per table;
- however, you cannot exceed a total of 250 indexes, both clustered and
- nonclustered. If CLUSTERED is not specified, NONCLUSTERED is assumed.
-
- index_name
- The name of the index. Index names must be unique within a table but need
- not be unique within a database.
-
- table_name
- The name of the table in which the indexed column or columns are located.
-
- column_name
- The column or columns to which the index applies. Composite indexes are
- based on the combined values in up to 16 columns. The sum of the maximum
- lengths of all the columns used in a composite index cannot exceed 256
- bytes. List the columns to be included in the composite index (in
- sort-priority order) inside the parentheses after table_name.
-
- FILLFACTOR
- Specifies how full SQL Server will make each page when it is creating a
- new index on existing data. The fillfactor percentage affects performance,
- because SQL Server must take the time to split pages when they fill up.
- The fillfactor percentage is relevant only at the time the index is
- created and becomes less important as the data changes. The pages are not
- maintained at any particular level of fullness.
-
- The default for FILLFACTOR is 0. Legal values are between 0 and 100. A
- fillfactor of 0 does not mean that pages are 0% full. Rather, it is like
- 100 in that SQL Server creates clustered indexes with completely full
- 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 the clustered and nonclustered case. There
- is seldom a reason to change the fillfactor variable, especially since you
- can override it in the CREATE INDEX statement.
-
- If FILLFACTOR is 100, SQL Server creates both clustered and nonclustered
- indexes with each page 100% full. A fillfactor of 100 makes sense only for
- read-only tables─tables to which no additional data will ever be added.
- Smaller fillfactor values (except 0, which is a special case) cause SQL
- Server to create new indexes with pages that are not completely 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 fillfactor values cause each index to take more storage space.
-
- The default FILLFACTOR value can be altered by updating sysconfigures.
-
- IGNORE_DUP_KEY
- An infrequently used keyword. Its most common function is to sort through
- a batch of data that includes duplicate rows you wish to eliminate.
-
- IGNORE_DUP_KEY controls what happens when you attempt to enter a duplicate
- key in a unique clustered index. It is meaningful only when the UPDATE or
- INSERT statement affects multiple rows.
-
- If IGNORE_DUP_KEY is not set and an attempt is made to enter data that
- would create duplicate keys, the entire data modification statement fails.
- (If there are other statements in the same transaction, they execute
- normally.)
-
- If IGNORE_DUP_KEY is set and you give an UPDATE or INSERT statement that
- would create duplicate keys, the row that would cause the duplicates is
- not added or changed. In fact, in the case of UPDATE, the row is
- discarded. (See the following warning.)
-
- Other changes to the database caused by the UPDATE or INSERT attempt (for
- example, changes to index pages) are also backed out. However, if the
- UPDATE or INSERT affects multiple rows, the other rows are added or
- changed as usual.
-
- ────────────────────────────────────────────────────────────────────────────
- WARNING
-
- With IGNORE_DUP_KEY set, if you try to update a row in such a way that a
- duplicate key would be created, that row is discarded. Neither the new value
- nor the original value of the row that would have produced the duplicate
- exists in the updated table. For example, if you try to update "Smith" to
- "Jones" and "Jones" already exists, you will have one "Jones" and no
- "Smith." The disappearance of the row for "Smith" is distressing, but
- unavoidable, because an UPDATE statement is actually a DELETE followed by an
- INSERT. SQL Server has no way to know about the disallowed duplicate when it
- deletes the row, and the whole transaction can't be rolled back because the
- purpose of IGNORE_DUP_KEY (and of the IGNORE_DUP_ROW option) is to allow a
- transaction to proceed in spite of the presence of duplicates.
- ────────────────────────────────────────────────────────────────────────────
-
- You cannot create a unique index on a column that includes duplicate
- values, whether or not IGNORE_DUP_KEY is set. If you attempt to do so, SQL
- Server prints an error message that gives the first of the duplicate
- values. You must eliminate duplicates before you create a unique index on
- the column.
-
- IGNORE_DUP_ROW and ALLOW_DUP_ROW
- Keywords allowed only with a nonunique clustered index. (From the point of
- view of a nonclustered index, there are never any duplicate rows─even for
- identical data values─because nonclustered indexes include a unique row
- identification number along with the index value.) Only one of the
- IGNORE_DUP_ROW and ALLOW_DUP_ROW options can be set.
-
- The ALLOW_DUP_ROW option allows duplicate rows in a table. If
- ALLOW_DUP_ROW is set, you can create a new clustered index on a table that
- includes duplicate rows, and you can subsequently create duplicate rows
- with INSERT or UPDATE.
-
- If ALLOW_DUP_ROW is not set, the handling of duplicate rows depends on
- whether IGNORE_DUP_ROW is set. You cannot set ALLOW_DUP_ROW if
- IGNORE_DUP_ROW is set.
-
- If any index in the table is unique, the requirement for uniqueness─the
- most stringent requirement─takes precedence over the ALLOW_DUP_ROW option.
- Thus, ALLOW_DUP_ROW applies only to tables with nonunique indexes: you
- cannot use this keyword if a unique clustered index exists on any column
- in the table.
-
- (However, you might create a table with a nonunique clustered index and
- the ALLOW_DUP_ROW option, and then create a unique nonclustered index on
- the same table. If at that time the existing data does not include any
- duplicate rows, the CREATE UNIQUE NONCLUSTERED INDEX statement will
- succeed, but subsequent attempts to enter duplicate rows will fail because
- of the requirement for uniqueness on the new nonclustered index. If
- duplicate rows do exist when you attempt to create a unique nonclustered
- index, the statement fails.)
-
- The IGNORE_DUP_ROW option, like IGNORE_DUP_KEY, is used infrequently. Its
- most common function is to sort through a batch of data that includes
- errors you wish to eliminate.
-
- IGNORE_DUP_ROW controls what happens when you attempt to enter duplicate
- rows into a table in which they're not allowed. IGNORE_DUP_ROW applies
- only to tables with nonunique indexes: you cannot use this keyword if a
- unique index exists on any column in the table. If ALLOW_DUP_ROW is set,
- IGNORE_DUP_ROW is meaningless. If IGNORE_DUP_ROW is not set (and
- ALLOW_DUP_ROW is not set), the entire statement fails. (If there are other
- statements in the same transaction, they are executed normally.)
-
- If IGNORE_DUP_ROW is set, the row that would duplicate another row is not
- added or changed, and you get an error message. Changes to the database
- caused by the attempt to duplicate a row (for example, changes to index
- pages) are also backed out. Other rows are added or changed, or the rest
- of the index is created, as usual.
-
- ────────────────────────────────────────────────────────────────────────────
- WARNING
-
- With IGNORE_DUP_ROW set, if you try to update a row in such a way that a
- duplicate row would be created, that row is discarded. Neither the new value
- nor the original value of the row that would have produced the duplicate
- exists in the updated table. For example, if you try to update "Smith" to
- "Jones" and "Jones" already exists, you will have one "Jones" and no
- "Smith." The disappearance of the row for "Smith" is distressing, but
- unavoidable, because an UPDATE statement is actually a DELETE followed by an
- INSERT. SQL Server has no way to know about the disallowed duplicate when it
- deletes the row, and the whole transaction can't be rolled back because the
- purpose of IGNORE_DUP_ROW (and of the IGNORE_DUP_KEY option) is to allow a
- transaction to proceed in spite of the presence of duplicates.
- ────────────────────────────────────────────────────────────────────────────
-
- In the default situation, neither ALLOW_DUP_ROW nor IGNORE_DUP_ROW is set.
- Attempting to insert duplicate rows or create an index on a table with
- duplicate rows causes the entire statement to fail.
-
- The following table illustrates how ALLOW_DUP_ROW and IGNORE_DUP_ROW
- affect attempts to create a nonunique clustered index on a table that
- includes duplicate rows, and to enter duplicate rows into a table.
-
- Create index Insert duplicate rows
- (table has duplicate
- rows)
- ────────────────────────────────────────────────────────────────────────────
- Neither Option Set Command fails. Command fails.
-
- ALLOW_DUP_ROW Set Command is completed. Command is completed.
-
- IGNORE_DUP_ROW Set Index created but All rows accepted except
- duplicate rows thrown duplicates; error message.
- out; error message. See the previous warning.
-
- ────────────────────────────────────────────────────────────────────────────
-
-
-
- Comments
-
- Indexes speed data retrieval but can slow data update.
-
- Columns regularly used in joins should always be indexed.
-
- Creating a clustered index requires work-table space that is 1.21 times the
- size of the data.
-
- Create the clustered index before creating any nonclustered indexes, since
- nonclustered indexes are automatically rebuilt when a clustered index is
- created.
-
- Columns of bit, text, and image types cannot be indexed.
-
- You can create an index on a temporary table. It disappears when the table
- disappears.
-
- As the syntax signifies, you can create an index on a table in another
- database as long as you are the owner of that table.
-
- If there is no data in the table when an index is created, you should run
- UPDATE STATISTICS after data is added.
-
- A composite index, like any other index, is represented by one row in
- sysindexes.
-
- To display a report on an object's indexes, execute the sp_helpindex system
- procedure.
-
- Space is allocated to tables and indexes in increments of one extent, or 8
- pages, at a time. In other words, an extent is allocated when the table or
- index is created, and another extent is allocated each time the previous
- extent becomes full. For a report on the amount of space allocated and used
- by an index, use sp_spaceused.
-
- Indexes cannot be created on columns containing text or image values.
-
-
- Permissions
-
- CREATE INDEX permission defaults to the table owner and is not transferable.
-
-
-
- See Also
-
- CREATE TABLE, DROP INDEX, INSERT, RECONFIGURE, SET, UPDATE, UPDATE
- STATISTICS, sp_helpindex, sp_spaceused
-
-
- CREATE PROCEDURE
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Creates a stored procedure (a precompiled collection of SQL statements,
- often including control-of-flow language) that can take one or more
- user-supplied parameters.
-
-
- Syntax
-
- CREATE PROCedure [owner.]procedure_name [;number]
- [[(]@parameter_name datatype [= default]
- [, @parameter_name datatype [= default]]...[)]]
- [WITH RECOMPILE]
- AS SQL_statements
-
-
- Examples
-
- A. create procedure showind @tabname varchar(30)
- as
- select sysobjects.name, sysindexes.name, indid
- from sysindexes, sysobjects
- where sysobjects.name = @tabname
- and sysobjects.id = sysindexes.id
-
- Given a table name, the procedure showind (example A) displays its name and
- the names and identification numbers of any indexes on any of its columns.
-
- The following are the acceptable syntax forms for executing showind:
-
- execute showind titles
-
- execute showind @tabname = "titles"
-
- Or, if this is the first statement in a file or batch:
-
- showind titles
-
- B. create procedure showsysind @table varchar(30) = "sys%"
- as
- select sysobjects.name, sysindexes.name, indid
- from sysindexes, sysobjects
- where sysobjects.name like @table
- and sysobjects.id = sysindexes.id
-
- The procedure in example B displays information about the system tables if
- the user does not supply a parameter.
-
- C. create procedure showindnew @table varchar(30) = null
- as
- if @table is null
- print "Please give a table name"
- else
- select sysobjects.name, sysindexes.name, indid
- from sysindexes, sysobjects
- where sysobjects.name = @table
- and sysobjects.id = sysindexes.id
-
- The procedure in example C specifies an action to be taken if the parameter
- is NULL (that is, if the user does not give a parameter).
-
-
- Options
-
- procedure_name
- The name of the procedure. It must conform to the rules for identifiers.
-
- ;number
- An optional integer used to group procedures of the same name so that they
- can be dropped together with a single DROP PROCEDURE statement. Procedures
- used in the same application are often grouped this way. For example, the
- procedures used with the application orders might be named orderproc;1,
- orderproc;2, and so on. The statement DROP PROCEDURE orderproc would drop
- the entire group. Once procedures have been grouped, individual procedures
- within the group cannot be dropped. For example, the statement DROP
- PROCEDURE orderproc;2 is not allowed.
-
- parameter_name
- The name of a parameter to the procedure. The value of each parameter is
- supplied when the procedure is executed. (Parameter names are optional in
- CREATE PROCEDURE statements─a procedure need not take any parameters.)
-
- Parameter names must be preceded by the "at" symbol (@). The parameter
- name conforms to the rules for identifiers except that it can contain from
- 1 to 29 characters. Parameters are local to the procedure; the same
- parameter names can be used in other procedures. Parameters can only take
- the place of constants; they cannot be used in place of table names,
- column names, or the names of other database objects. However, the value
- of a parameter given at execution time can be an object name.
-
- If the value of a parameter is an object name and the object name is
- qualified by a database name or owner name, the entire name must be
- enclosed in single or double quotation marks.
-
- datatype
- The datatype of the parameter. A length in parentheses after the datatype
- entry is required for some datatypes. See the "Datatypes" section for a
- list of SQL-Server-supplied datatypes and their syntax.
-
- default
- A default parameter value for the procedure. If a default is defined, a
- user can execute the procedure without giving a parameter. The default
- must be a constant. It can include the wildcard characters (%, _, [ ], and
- [^]) if the procedure uses the parameter name with the LIKE keyword. (See
- example B.)
-
- The default can be NULL. The procedure definition can specify that some
- action be taken if the parameter value is NULL. (See example C.)
-
- WITH RECOMPILE
- Indicates that SQL Server will never save a plan for this procedure; the
- procedure will be recompiled each time it is executed. Use this optional
- clause when you expect that the parameters you supply to the procedure
- won't be typical, that is, they would not result in the same optimal plan.
-
- SQL_statements
- Statements that specify the actions the procedure is to take. Any number
- and kind of SQL statements can be included with the exception of CREATE
- statements. The SQL statements in a CREATE PROCEDURE statement can also
- include parameters.
-
- CREATE PROCEDURE statements often include control-of-flow language,
- including one or more of the following: DECLARE; IF...ELSE; WHILE; BREAK;
- CONTINUE; BEGIN...END; GOTO; RETURN; WAITFOR; /* comment */.
-
- The SQL statements can reference objects in another database as long as
- they are properly qualified.
-
-
- Comments
-
- Since stored procedures are compiled the first time they are executed,
- subsequent run time is much shorter than for the equivalent set of
- stand-alone statements.
-
- Most SQL Server database administration tasks are accomplished with
- predefined system procedures. Each of the system procedures' names begins
- with sp_.
-
- CREATE PROCEDURE statements cannot be combined with other SQL statements in
- a single batch.
-
- You can create a stored procedure in the current database only.
-
- A CREATE PROCEDURE statement cannot include any CREATE VIEW, CREATE DEFAULT,
- CREATE RULE, CREATE TRIGGER, or other CREATE PROCEDURE statements.
-
- The maximum number for each parameter, local variable, and global variable
- in a procedure is 40. (See "Variables (Local and Global)".)
-
- The maximum amount of text in a stored procedure is 65,280 characters. This
- limit is imposed by the fact that the text is stored in syscomments, where
- each procedure can occupy 255 rows of 256 bytes each.
-
- Once a procedure is created, you can run it by executing the EXECUTE
- statement along with the procedure's name and any parameters. Or, if a
- procedure is the first statement in a batch, you can give its name without
- the keyword EXECUTE.
-
- Any objects referenced in a procedure must already exist. You can create an
- object within a procedure and then reference it as long as the object is
- created before it is referenced.
-
- You can create a procedure that references a temporary object if the
- temporary object exists at the time the procedure is created or if the
- procedure itself creates the temporary object. A temporary object created in
- a procedure disappears when the procedure exits. If a procedure uses a
- temporary object that it does not create, you must re-create the temporary
- object and the stored procedure before you invoke that procedure. For this
- reason, system procedures (like sp_help) do not work on temporary objects.
- If you have a procedure that uses a temporary table and is not going to call
- other procedures, then it makes sense to use a temporary table. The table
- goes away when you exit the procedure.
-
- If you execute a procedure that calls another procedure, the called
- procedure can access objects created by the calling procedure.
-
- You can use the SET statement inside a stored procedure. The SET option you
- choose remains in effect during the execution of the procedure and then
- reverts to its former setting.
-
- Within a stored procedure, you cannot create an object (including a
- temporary one), drop it, and then create a new object with the same name.
-
- Inside a stored procedure, object names used with certain statements (the
- so-called utility programs) must be qualified with the object owner's name
- if other users are to use the stored procedure. For example, user mary, who
- owns table marytab, should qualify the name of her table inside a stored
- procedure (when it is used with these utility commands) if she wants other
- users to be able to execute it, like this:
-
- create procedure p1
- as
- create index marytab_ind
- on mary.marytab(col1)
-
- This is because the object names are resolved when the procedure is run. In
- the example, if user john tried to execute procedure p1, SQL Server would
- look for a table called marytab owned by John. The utility statements are
- ALTER TABLE, CREATE TABLE, DROP TABLE, TRUNCATE TABLE, CREATE INDEX, DROP
- INDEX, UPDATE STATISTICS, and DBCC. Object names used with other statements
- (for example, SELECT or INSERT) inside a stored procedure need not be
- qualified, because the names are resolved when the procedure is compiled.
-
- The text of the CREATE PROCEDURE statement is stored in syscomments. To
- display it, execute the sp_helptext system procedure with the procedure name
- as the parameter. To display the text of a system procedure, execute
- sp_helptext from the master database.
-
- To rename a procedure, use sp_rename. For a report on the objects referenced
- by a procedure, use sp_depends.
-
-
- Permissions
-
- CREATE PROCEDURE permission defaults to the Database Owner, who can transfer
- it to other users.
-
-
- See Also
-
- Batch Queries, BEGIN...END, BREAK, Comments, CONTINUE, DECLARE, DROP
- PROCEDURE, EXECUTE, GOTO, GRANT, IF...ELSE, Parameters, RETURN, SELECT,
- System Procedures, Variables (Local and Global), WAITFOR, WHILE, Wildcard
- Characters, sp_depends, sp_helptext, sp_rename
-
-
- CREATE RULE
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Specifies the domain of acceptable values for a particular column or for any
- column of a user-specified datatype.
-
-
- Syntax
-
- CREATE RULE [owner.]rule_name
- AS condition_expression
-
-
- Examples
-
- A. create rule limit
- as @advance < $1000
-
- B. create rule pubid_rule
- as @pub_id in ('1389', '0736', '0877')
-
- C. create rule picture
- as @value like '_ _-%[0-9]'
-
-
- Options
-
- rule_name
- The name of the new rule. It must conform to the rules for identifiers.
-
- condition_expression
- The conditions that define the rule. It can be any expression that is
- valid in a WHERE clause and can include arithmetic operators, relational
- operators, IN, LIKE, BETWEEN, and so on. However, it cannot reference any
- column or other database object. Built-in functions that do not reference
- database objects can be included.
-
- A condition_expression takes one parameter. The parameter is prefixed by
- the "at" symbol (@) and refers to the value that is entered with the
- UPDATE or INSERT statement. You can use any name or symbol to represent
- the value when you write the rule, but the first character must be "@".
-
-
- Comments
-
- Rules do not apply to the data already existing in the database at the time
- the rules are created.
-
- CREATE RULE statements cannot be combined with other SQL statements in a
- single batch.
-
- You can create a rule in the current database only.
-
- After you've created a rule, use the sp_bindrule system procedure to link
- the rule to a column or user datatype.
-
- Rules cannot be bound to SQL-Server-supplied datatypes.
-
- The rule must be compatible with the datatype of the column. You cannot use
- "@value like A%", for example, as a rule for a numeric column.
-
- ────────────────────────────────────────────────────────────────────────────
- NOTE
-
- If the rule is not compatible with the column to which you've bound it, SQL
- Server generates an error message when it tries to insert a value (not when
- you bind it).
- ────────────────────────────────────────────────────────────────────────────
-
- Be sure to enclose character and date constants in quotation marks and to
- precede binary constants with "0x".
-
- Rule definitions and binding information are stored in system tables. The
- text of CREATE RULE statements is stored in the syscomments system table. To
- display it, execute the sp_helptext system procedure with the rule name as
- the parameter. After a rule is bound to a particular column or user
- datatype, its ID is stored in the syscolumns or systypes system tables.
-
- To get a report on a rule, use sp_help. To rename a rule, use sp_rename.
-
- You must drop a rule before you can create a new one of the same name, and
- you must unbind a rule (with the sp_unbindrule system procedure) before you
- drop it.
-
- You can bind a new rule to a column or datatype without unbinding the old
- one; the new rule overrides the old one.
-
- When unbinding a rule from a column, use sp_unbindrule.
-
- You can bind one rule to a user datatype and another rule to a column of
- that datatype. The rule most recently bound takes precedence.
-
- If a column has both a default and a rule associated with it, the default
- must fall within the domain defined by the rule. A default that conflicts
- with a rule will never be inserted. SQL Server generates an error message
- each time it attempts to insert the default.
-
-
- Permissions
-
- CREATE RULE permission defaults to the Database Owner, who can transfer it
- to other users.
-
-
- See Also
-
- Batch Queries, CREATE DEFAULT, DROP DEFAULT, DROP RULE, sp_bindrule,
- sp_help, sp_helptext, sp_rename, sp_unbindrule
-
-
- CREATE TABLE
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Creates new tables.
-
-
- Syntax
-
- CREATE TABLE [[database.]owner.]table_name
- (column_name datatype [NOT NULL | NULL]
- [, column_name datatype [NOT NULL | NULL]]...)
-
-
- Examples
-
- create table titles
- (title_id tid,
- title varchar(80),
- type char(12),
- pub_id char(4),
- price money null,
- advance money null,
- royalty float null,
- ytd_sales money null,
- notes varchar(200),
- pubdate datetime)
-
-
- Options
-
- table_name
- The name of the new table. It must conform to the rules for identifiers
- and must be unique within this database and owner.
-
- You can create temporary tables by preceding the table name with a pound
- sign (#). If you wanted the table in example A to be a temporary table,
- you would call it #titles. Temporary tables are stored in
- tempdb..sysobjects by their names plus a system-supplied numeric suffix.
- Temporary tables disappear at the end of the current session or when they
- are explicitly dropped.
-
- You can create a table in a different database as long as you are listed
- in the sysusers table of the other database and have CREATE TABLE
- permission in that database. For example, to create a table called
- newtable in the database otherdb, use the following syntax:
-
- A. create table otherdb..newtable
-
- B. create table otherdb.yourname.newtable
-
- column_name
- The name of the column in the table. It must conform to the rules for
- identifiers and must be unique in the table.
-
- datatype
- The datatype of the column. System or user-defined datatypes are
- acceptable. Some datatypes require a length in the form datatype(n) where
- n is the length. To assign a datatype, use the format column_name
- datatype. (See "Datatypes" for more information.)
-
- NOT NULL
- Indicates that if there is no default for this column, an error message
- will be produced if no entry is made at insert time. Furthermore, the user
- cannot assign the value NULL in this column. If neither NULL nor NOT NULL
- is specified, NOT NULL is assumed. This SQL Server enhancement speeds
- retrievals and updates.
-
- NULL
- Indicates that if the user does not make an entry at insert time and there
- is no default entry for this column, SQL Server will assign the value
- NULL.
-
-
- Comments
-
- There can be up to 2 billion tables per database and 250 columns per table.
-
-
- The table is created in the currently open database unless a different
- database is explicitly specified in the CREATE TABLE statement with the
- optional database and owner names. (Cross-database creation of tables and
- indexes is allowed as long as the creator is listed in the sysusers table of
- the other database and has CREATE TABLE permission in that database.
- However, cross-database creation of views, rules, defaults, stored
- procedures, and triggers is not allowed.)
-
- User-defined datatypes are defined in terms of system datatypes. User
- datatypes permit frequently used type information to be accessed by a name
- you choose with a specified rule, default, and display format attached to
- it. User-defined datatypes are created with the sp_addtype system procedure
- before they are used in a table definition.
-
- You cannot create a row that has more than 1962 bytes of data.
-
- When you create user-defined datatypes with sp_addtype, there are three
- parameters: the name you assign the datatype; the base datatype (one of the
- SQL-Server-supplied datatypes─include length for char, varchar, binary, and
- varbinary); and either NULL or NOT NULL. The last parameter is optional.
-
- If you don't type NULL or NOT NULL, NOT NULL is assumed. The first two
- examples here are NOT NULL; the third is NULL. (Quotation marks are used
- when parameters contain blanks or punctuation marks.)
-
- A. sp_addtype tid1, "char(6)"
-
- B. sp_addtype tid2, "char(6)", "not null"
-
- C. sp_addtype tid3, "char(6)", null
-
- The NULL/NOT NULL assignment of a user datatype can be changed when you use
- it in a CREATE TABLE statement. However, the length specification cannot be
- changed: SQL Server will not allow you to specify a new length for a
- user-defined datatype in a CREATE TABLE statement.
-
- User-defined datatypes are removed with the sp_droptype system procedure.
-
- All of the datatypes that handle numbers (int, smallint, tinyint, money, and
- float) support arithmetic operations and aggregate functions (except that
- you cannot use modulo with float or money). Relational operators can be used
- on any of the datatypes except text and image.
-
- You can use the LIKE keyword and wildcard characters with char, varchar,
- text, and datetime data (but not to search for seconds or milliseconds).
-
- Built-in functions for concatenation and for finding substrings are provided
- for char, varchar, binary, and varbinary datatypes. (See "String
- Functions.")
-
- Conversion from one datatype to another is available with the CONVERT
- statement. (See "Conversion Function.")
-
- You can convert text data to varchar, and image data to varbinary, but it
- will be truncated to 255 bytes.
-
- When you create NULL columns with certain datatypes, SQL Server
- automatically converts them to a different internal datatype to allow the
- storage of null values. The char datatype is automatically converted to
- varchar; binary to varbinary; datetime to datetimn; float to floatn; int,
- smallint, and tinyint to intn; and money to moneyn.
-
- SQL Server does not inform the user of the type change, and the user need be
- concerned about it only if querying the system tables.
-
- Temporary tables are stored in the temporary database (tempdb), and
- permanent ones in the current database.
-
- You cannot create a view on a temporary table, nor can you associate rules,
- defaults, or triggers with temporary tables. You can use a user-defined
- datatype when creating a temporary table only if that type is in
- tempdb..systypes.
-
- (There are two ways to add a user-defined datatype (or any other object) to
- tempdb. To add an object for the current session only, execute sp_addtype
- while using the tempdb database. To add an object permanently, execute
- sp_addtype while using the model database and then restart SQL Server so
- that model is copied to tempdb.)
-
- Within a stored procedure, you cannot create a table, drop it, and then
- create a new table with the same name.
-
- For a report on a table and its columns, execute the sp_help system
- procedure. To rename a table, use sp_rename.
-
- ────────────────────────────────────────────────────────────────────────────
- WARNING
-
- Procedures, triggers, and views that depend on an object whose name has been
- changed work properly until they are recompiled. However, recompilation
- takes place for many reasons and without notification to the user. When the
- procedure, trigger, or view is recompiled by SQL Server, it will no longer
- work. The user must change the procedure, trigger, or view text to reflect
- the new name of the dependent object. The safest course is to change the
- definitions of any dependent objects when you execute sp_rename.
- ────────────────────────────────────────────────────────────────────────────
-
- Space is allocated to tables and indexes in increments of one extent, or 8
- pages, at a time. In other words, an extent is allocated when the table or
- index is created, and another extent is allocated each time the previous
- extent becomes full. For a report on the amount of space allocated and used
- by a table, use sp_spaceused.
-
- For a report on the views and stored procedures that depend on a table, use
- sp_depends.
-
- You can define primary, foreign, and common keys on a table with the
- sp_primarykey, sp_foreignkey, and sp_commonkey system procedures. For a
- report on the keys that have been defined, use sp_helpkey. For a report on
- frequently used joins, use sp_helpjoins.
-
-
- Permissions
-
- CREATE TABLE permission defaults to the Database Owner, who can transfer it
- to other users. Any user can create temporary tables.
-
-
- See Also
-
- CREATE INDEX, CREATE RULE, CREATE VIEW, Datatypes, DROP INDEX, DROP RULE,
- DROP TABLE, sp_addtype, sp_commonkey, sp_depends, sp_foreignkey, sp_help,
- sp_helpjoins, sp_primarykey, sp_rename, sp_spaceused
-
-
- CREATE TRIGGER
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Creates a trigger, which is a special kind of stored procedure often used
- for enforcing integrity constraints. A trigger is executed automatically
- when a user attempts the specified data modification statement on the
- specified table.
-
-
- Syntax
-
- CREATE TRIGGER [owner.]trigger_name
- ON [owner.]table_name
- FOR {INSERT | UPDATE | DELETE}
- [,{INSERT | UPDATE | DELETE}...]
- AS SQL_statements |
- IF UPDATE (column_name)
- [{AND | OR} UPDATE (column_name)...]
-
-
- Examples
-
- A. create trigger reminder
- on titles
- for insert, update as
- print "Don't forget to print a report for accounting."
-
- Example A prints a message every time anyone tries to add data or change
- data in the titles table.
-
- B. create trigger t1
- on titleauthor
- for insert as
- if (select count(*)
- from titles, inserted
- where titles.title_id = inserted.title_id) = 0
- begin
- print "Please put the book's title_id in the titles
- table first."
- rollback transaction
- end
-
- Example B prevents insertion of a new row into titleauthor if there is no
- corresponding title_id in the titles table.
-
- C. create trigger t2
- on publishers
- for update as
- if update (pub_id)
- begin
- update titles
- set titles.pub_id = inserted.pub_id
- from titles, deleted, inserted
- where deleted.pub_id = titles.pub_id
- end
-
- If the pub_id column of the publishers table is changed, example C makes the
- corresponding change in the titles table.
-
- D. create trigger t3
- on titleauthor
- for delete as
- begin
- delete titles
- from titles, deleted
- where deleted.title_id = titles.title_id
- delete titleauthor
- from titleauthor, deleted
- where deleted.title_id = titleauthor.title_id
- print "All references to this title have been deleted
- from titles and titleauthor."
- end
-
- If any row is deleted from titleauthor, that title is also deleted from the
- titles table (example D). If the book was written by more than one author,
- other references to it in titleauthor are also deleted.
-
-
- Options
-
- trigger_name
- The name of the trigger. It must conform to the rules for identifiers and
- must be unique in the database.
-
- INSERT, DELETE, UPDATE
- Keywords that can be included in any combination.
-
- SQL_statements
- Statements that specify trigger conditions and trigger actions. Trigger
- conditions specify additional criteria that determine whether the
- attempted INSERT, DELETE, or UPDATE will cause the trigger action(s) to be
- carried out. Trigger conditions often include a subquery preceded by the
- keyword IF.
-
- The trigger actions specified in the SQL statements go into effect when
- the user action (UPDATE, INSERT, or DELETE) is attempted. If multiple
- trigger actions are specified, they are grouped with BEGIN and END.
-
- Triggers can include any number and kind of SQL statements except SELECT
- statements; a trigger cannot return data to the user. The SQL statements
- in a trigger are similar to those in a stored procedure in that they often
- include control-of-flow language. A few special names are used in CREATE
- TRIGGER statements:
-
-
- ■ Deleted and inserted are logical (conceptual) tables. They are
- structurally like the table on which the trigger is defined─that is,
- the table on which the user action is attempted─and hold the old
- values or new values of the rows that would be changed by the user
- action. Deleted and inserted tables can be examined by the trigger to
- determine whether or how the trigger action(s) should be carried out.
- Deleted tables are used with DELETE and UPDATE; inserted with INSERT
- and UPDATE. See examples.
-
- ■ IF UPDATE is used to test if the specified column has been modified in
- any way. This allows specified trigger actions to be associated with
- updates to specified columns. See example B. More than one column can
- be specified. Use IF UPDATE like this:
-
- IF UPDATE (column_name) [{AND | OR} UPDATE (column_name)...]
-
-
-
-
- Comments
-
- Triggers are commonly used to enforce referential integrity (integrity rules
- about relationships between the primary and foreign keys of tables or
- views), to supply cascading deletes, and to supply cascading updates. (See
- examples B, C, and D, respectively.)
-
- You can define primary, foreign, and common keys on a table or view with the
- sp_primarykey, sp_foreignkey, and sp_commonkey system procedures. For a
- report on the keys that have been defined, use sp_helpkey.
-
- Trigger conditions specify additional criteria that determine whether the
- attempted INSERT, DELETE, or UPDATE will cause the trigger action(s) to be
- carried out. In example B (and in most triggers with trigger conditions),
- the subquery that follows the keyword IF is the trigger condition.
-
- Trigger actions specify the action(s) taken by SQL Server when the user
- action (that meets the trigger condition, if one is included) is attempted.
- Multiple statements are grouped with BEGIN and END.
-
- You can create a trigger in the current database only. If you use an owner
- name to qualify a trigger, you must explicitly qualify the table name the
- same way.
-
- A trigger may reference objects outside the current database.
-
- Triggers cannot be nested. That is, one trigger can't call another. If a
- trigger changes a table on which there is another trigger, the second
- trigger won't be executed.
-
- If you need a trigger to cause two actions, try to put both of the actions
- into a single trigger. (Or consider using a stored procedure instead.)
-
- For example, you might create an INSERT trigger on the sales table that
- updates titles.ytd_sales. You'd also like a trigger on updates to
- titles.ytd_sales that checks the royalty column in titles and changes it if
- necessary.
-
- The correct method is to write a single trigger that takes both actions─the
- update of titles.ytd_sales and the (possible) update of titles.royalty. This
- is because triggers cannot be nested─that is, one trigger cannot cause the
- execution of a second trigger.
-
- In performance terms, trigger overhead is usually very low. The time
- involved in running a trigger is spent mostly in referencing other tables,
- which may be either in memory or on the disk.
-
- The deleted and inserted tables, often referenced by triggers, are always in
- memory rather than on the disk because they are logical tables. The location
- of other tables referenced by the trigger determines the amount of time the
- operation takes.
-
- When an INSERT or UPDATE statement is executed, rows are added to the
- trigger table and to inserted at the same time. So the rows in inserted are
- always duplicates of one or more rows in the trigger table.
-
- Once a trigger is defined, the user action it specifies on the table to
- which it applies is always implicitly part of a transaction, along with the
- trigger itself. Triggers are often used to roll back that transaction if an
- error is detected.
-
- An UPDATE or INSERT trigger can make use of the IF UPDATE statement. It is
- used to test if the UPDATE or INSERT changed a particular column.
-
- IF UPDATE(column_name) is true for an INSERT statement whenever the column
- is assigned a value in the select list or in the VALUES clause. An explicit
- NULL or a default assigns a value to a column and thus activates the
- trigger. An implicit NULL, however, does not. Here are some examples:
-
- CREATE TABLE junk
- (a int null,
- b int not null)
-
- A. INSERT junk (a, b)
- VALUES (1, 2)
-
- IF UPDATE is true for either column
-
- B. INSERT junk
- VALUES (1, 2)
-
- IF UPDATE is true for either column
-
- C. INSERT junk
- VALUES (NULL, 2)
-
- Explicit NULL IF UPDATE is true for either column
-
- D. INSERT junk (b)
- VALUES (2)
-
- With a default for column a, IF UPDATE is true for either column
-
- E. INSERT junk (b)
- VALUES (2)
-
- With no default for column a, IF UPDATE is not true for column a
-
- IF UPDATE is never true for a DELETE statement.
-
- The text of the CREATE TRIGGER statement is stored in syscomments. To
- display it, execute the sp_helptext system procedure.
-
- The execution plan for the trigger is stored in sysprocedures. Each trigger
- is assigned an identification number, which is stored as a new row in
- sysobjects and as an entry in the sysobjects row for the table to which it
- applies.
-
- You can use the SET statement inside a trigger. The SET option you invoke
- remains in effect during the execution of the trigger and then reverts to
- its former setting.
-
- It is recommended that a trigger not include SELECT statements that return
- results to the user, since special handling for these returned results would
- have to be written into every application program in which modifications to
- the trigger table are allowed.
-
- You cannot create a trigger on a view or on a temporary object.
-
- A TRUNCATE TABLE statement is not caught by a DELETE trigger. Although a
- TRUNCATE TABLE statement is, in effect, like a DELETE without a WHERE clause
- (it removes all rows), it is not logged, and so cannot execute a trigger.
-
- Since permission for the TRUNCATE TABLE statement defaults to the table
- owner and is not transferable, only the table owner should be concerned
- about inadvertently circumventing a DELETE trigger with a TRUNCATE TABLE
- statement.
-
- When you drop a table, any triggers associated with it are also dropped.
-
- A trigger cannot apply to more than one table. However, the same trigger
- action can be defined for all three user actions in the same CREATE TRIGGER
- statement. A table can have a maximum of three different triggers─one each
- for INSERT, UPDATE, and DELETE.
-
- For a report on a trigger, execute the sp_help system procedure. For a
- report on the tables and views that are referenced by a trigger, use
- sp_depends.
-
- You can rename a trigger with sp_rename.
-
-
- Permissions
-
- CREATE TRIGGER permission defaults to the table owner and is not
- transferable.
-
-
- See Also
-
- CREATE PROCEDURE, DROP TRIGGER, sp_commonkey, sp_depends, sp_foreignkey,
- sp_help, sp_helptext, sp_primarykey, sp_rename, sp_spaceused
-
-
- CREATE VIEW
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Creates views (alternative ways of looking at the data in one or more
- tables).
-
-
- Syntax
-
- CREATE VIEW [owner.]view_name
- [(column_name [, column_name]...)]
- AS select_statement
-
-
- Examples
-
- A. create view titles_view
- as select title, type, price, pubdate
- from titles
-
- B. create view accounts (title, advance, amt_due)
- as select title, advance, price * royalty * ytd_sales
- from titles
- where price > $5
-
- C. create view cities (authorname, acity, publishername, pcity)
- as select au_lname, authors.city, pub_name, publishers.city
- from authors, publishers
- where authors.city = publishers.city
-
- D. create view cities2
- as select authorname = au_lname, acity = authors.city,
- publishername = pub_name, pcity = publishers.city
- from authors, publishers
- where authors.city = publishers.city
-
-
- Options
-
- view_name
- The name of the new view. It must be a legal identifier.
-
- column_name
- The names to be used for the columns in the view. This is always legal but
- only necessary when a column is derived from an arithmetic expression, a
- function, or a constant; when two or more columns could otherwise have the
- same name (usually because of a join); or when you want to give a column
- in a view a different name than the column from which it is derived. (See
- example C.) Column names can also be assigned in the SELECT statement.
- (See example D.)
-
- If no column names are specified, the view columns acquire the same names
- as the columns in the SELECT statement.
-
- select_statement
- The SELECT statement that defines the view. It can use more than one table
- and other views.
-
-
- Comments
-
- You cannot include ORDER BY or COMPUTE clauses or the DISTINCT or INTO
- keywords in the SELECT statements that define views.
-
- You cannot create a trigger on a view.
-
- You can create a view in the current database only.
-
- Currently there are no temporary views.
-
- If you alter the structure of a view's underlying table(s) by adding
- columns, the new columns will not appear in a view defined with a "SELECT *"
- clause unless the view is deleted and redefined. The asterisk shorthand is
- interpreted and expanded when the view is first created.
-
- If a view depends on a table (or view) that has been dropped, SQL Server
- produces an error message if anyone tries to use the view. If a new table
- (or view) is created to replace the one that has been dropped, the view
- again becomes usable.
-
- You cannot create a view on a temporary table.
-
- You can redefine a view without redefining other views that depend on it
- unless the redefinition makes it impossible for SQL Server to translate the
- dependent view.
-
- CREATE VIEW statements cannot be combined with other SQL statements in a
- single batch.
-
- There are no restrictions on querying through views, but there are some
- restrictions on data update through views.
-
- Data update statements may not change any column in a view that is a
- computation.
-
- Data update statements may not change a view that includes aggregate
- functions (built-in functions and a GROUP BY or COMPUTE BY clause).
-
- INSERT statements are not allowed unless all NOT NULL columns in the
- underlying table or view are included in the view through which you are
- inserting new rows. (SQL Server has no way to supply values for NOT NULL
- columns in the underlying table or view.)
-
- INSERT and UPDATE statements are not allowed unless the columns being
- updated all belong to the same base table. (It's illegal in SQL to use data
- update statements on more than one table in a single statement.) However, if
- a view contains columns from more than one table but the data update
- statement references columns from only one of those tables, the statement is
- legal.
-
- When you query through a view, SQL Server checks to make sure that all the
- database objects referenced anywhere in the statement exist, that they are
- valid in the context of the statement, and that data update statements do
- not violate data integrity rules. If any of these checks fail, you get an
- error message. If the checks are successful, it translates the view into an
- action on the underlying table(s).
-
- You can use views as security mechanisms by granting permission on a view
- but not on underlying tables.
-
- The text of the CREATE VIEW statement is stored in syscomments. To display
- it, execute the sp_helptext system procedure with the view name as the
- parameter.
-
- You can rename a view with sp_rename. To get a report of the tables or views
- on which a view depends, and of objects that depend on a view, execute the
- sp_depends system procedure.
-
- See SQL Server Learning TRANSACT-SQL for more information and examples on
- views.
-
-
- Permissions
-
- CREATE VIEW permission defaults to the Database Owner, who can transfer it
- to other users. The creator of a view must have SELECT permission on any
- objects referenced in the view definition.
-
-
- See Also
-
- DROP VIEW, Views, sp_depends, sp_help, sp_helptext, sp_rename
-
-
-
-
-
- Datatypes
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Specify data characteristics of columns, stored procedure parameters, and
- local variables. For text and image datatypes used to store long string of
- data, see "Text/Image Datatypes."
-
-
- Syntax
-
- column_name text
- column_name image
- column_name timestamp
- {param_name | variable_name | column_name} int
- {param_name | variable_name | column_name} smallint
- {param_name | variable_name | column_name} tinyint
- {param_name | variable_name | column_name} float
- {param_name | variable_name | column_name} char(n)
- {param_name | variable_name | column_name} varchar(n)
- {param_name | variable_name | column_name} binary(n)
- {param_name | variable_name | column_name} varbinary(n)
- {param_name | variable_name | column_name} bit
- {param_name | variable_name | column_name} money
- {param_name | variable_name | column_name} datetime
- {param_name | variable_name | column_name} sysname
- {param_name | variable_name | column_name} user_type_name
-
- Datatypes include system datatypes and user-defined datatypes. SQL Server
- supplies the sysname user datatype. The pubs sample database also supplies
- user datatypes. You can also create your own user datatypes. Some datatypes
- require a length.
-
-
- Examples
-
- A. create table food
- (fname varchar(20),
- fcals int,
- frate int)
-
- B. create procedure auname_sp @auname varchar(40)
- as
- select au_lname, title, au_ord
- from authors, titles, titleauthor
- where @auname = au_lname
- and authors.au_id = titleauthor.au_id
- and titles.title_id = titleauthor.title_id
-
- C. declare @hope money
-
-
- Options
-
- param_name
- The name of a stored procedure parameter. It must conform to the rules for
- identifiers.
-
- variable_name
- The name of a local variable. It must conform to the rules for
- identifiers.
-
- column_name
- The name of a database column. It must conform to the rules for
- identifiers and must be unique within its table.
-
- int
- An integer column that holds whole numbers between 231- 1 (that is,
- 2,147,483,647) and -231+ 1 (that is, -2,147,483,648), inclusive. However,
- you cannot enter -2,147,483,648, but you can enter -2,147,483,647 - 1. You
- can store this number or it can be the result of a calculation. Storage
- size is 4 bytes.
-
- smallint
- A small integer column that holds whole numbers between 215- 1 (32,767)
- and -215 (-32,768), inclusive. Storage size is 2 bytes.
-
- tinyint
- A tiny integer column that holds whole numbers between 0 and 255,
- inclusive. Storage size is 1 byte.
-
- float
- A floating-point column that holds positive or negative floating-point
- numbers. This column has 15-digit precision. The range of values is
- approximately 1.7E - 308 to 1.7E + 308. Storage size is 8 bytes. All the
- arithmetic operations except modulo are available with float.
-
- Data of type float can include an optional exponent. For float data with
- an exponential component, enter a number (with or without a decimal point
- and a positive or negative sign), followed by "e" or "E", followed by an
- optionally signed integer. The value represented by a float is the product
- of the first number and the power of 10 of the second number.
-
- char(n)
- A character column that any combination of up to 255 letters, symbols, and
- numbers. Specify the maximum size of the column with n. A char column can
- contain 0 characters, but n must be between 1 and 255. Storage size is n,
- no matter what the actual entry length.
-
- Columns of type char are accessed a little faster than varchar columns and
- use more storage space. Choose char when you know the size of character
- data (as in a social security number or a zip code). Data of type char
- must be enclosed in single or double quotation marks when it's input.
- Numbers stored in char columns must be converted to a numeric data type
- before you can do arithmetic on them.
-
- You can use the LIKE keyword and wildcard characters with char, varchar,
- and datetime data (but not to search for seconds or milliseconds).
-
- If you enter strings that are too long for the specified length, char and
- varchar entries are truncated.
-
- varchar(n)
- A column of variable-length characters that holds any combination of up to
- 255 letters, symbols, and numbers. Specify the maximum size of the column
- with n. A varchar column can contain 0 characters, but n must be between 1
- and 255. Storage size is the actual size of the data values entered, not
- n.
-
- Because of the way it uses space, varchar is best suited for data-like
- names where the length of each entry can vary considerably.
-
- Data of type varchar must be enclosed in single or double quotation marks
- when it's input. You can use the LIKE keyword and wildcard characters with
- char, varchar, and datetime data (but not to search for seconds or
- milliseconds).
-
- If you enter strings that are too long for the specified length, char and
- varchar entries are truncated.
-
- text
- Variable-length columns that can hold up to 2,147,483,647 (231- 1)
- characters. The text datatype may not be used for variables or parameters
- in stored procedures. (See "Text/Image Datatypes.")
-
- binary(n)
- A column that holds up to 255 bytes of fixed-length binary data. The
- binary datatypes are not for hexadecimal data, but rather for bit
- patterns. They are used for storing programming code or pictures, not for
- hexadecimal numbers.
-
- Specify the maximum byte length of the column with n. A binary column can
- contain 0 bytes, but n must be between 1 and 255. Storage size is n no
- matter what the actual entry length. The maximum binary value is 255
- bytes, each of which is "ff".
-
- Columns of type binary are accessed a little faster than varbinary columns
- and use more storage space. Choose binary when you think the data entries
- in the column will be close to the same size. Data of type binary consists
- of the characters 0 to 9 and A to F (or a to f), and the first binary
- string must be preceded with "0x" when it's input. For example, to input
- "FF", type 0xFF. A length of 10 for a binary or varbinary column means 20
- characters. If you enter strings that are too long for the specified
- length, binary and varbinary entries are truncated.
-
- varbinary(n)
- A variable-length binary column that holds up to 255 bytes of
- variable-length binary data. The binary datatypes are not for hexadecimal
- data, but rather for bit patterns. They are used for storing programming
- code or pictures, not for hexadecimal numbers. Specify the maximum size of
- the column with n. A varbinary column can contain 0 bytes, but n must be
- between 1 and 255. Storage size is the actual size of the data values
- entered, not n.
-
- Because of the way it uses space, choose varbinary when you expect
- variation in the size of the data.
-
- Data of type varbinary consists of the characters 0 to 9 and A to F (or a
- to f), and the first varbinary string must be preceded with "0x" when it's
- input.
-
- A length of 10 for a binary or varbinary column means 20 characters.
-
- If you enter strings that are too long for the specified length, binary
- and varbinary entries are truncated.
-
- image
- A variable-length column that holds between 0 and 2,147,483,647 bytes of
- binary data. The image datatype may not be used for variables or
- parameters in stored procedures. (See "Text/Image Datatypes" for details.)
-
- bit
- A column that holds either a 1 or a 0. Integer values other than 1 or 0
- are accepted but are always interpreted as 1. Storage size is 1 bit.
- Multiple bit types in a table can be collected into bytes. For example, 7
- bit columns fit into 1 byte; 9 bit columns take 2 bytes. The status column
- in the syscolumns system table indicates the unique offset position for
- bit columns.
-
- Columns of type bit cannot be NULL and cannot have indexes on them. Use
- bit for true/false or yes/no types of data.
-
- money
- A column that stores dollar and cent values between
- ±922,337,203,685,477.5807 dollars with accuracy to a ten-thousandth of a
- dollar. Money values are represented as double-precision integers. Storage
- size is 8 bytes.
-
- Use money for all decimal currency entries. Data of type money should be
- preceded with a dollar sign ($) when it's input. If there is no dollar
- sign, SQL Server treats the value as a float. Depending on the exact
- input, SQL Server may not accept it, or may lose some of the value's
- precision.
-
- To represent negative money values, a minus sign (-) must be placed after
- the dollar sign. You cannot enter money values with commas, although the
- default print format for money data places a comma after every three
- digits.
-
- When money values are displayed, they are rounded up to the nearest cent.
- All the arithmetic operations except modulo are available with money.
-
- datetime
- A column that holds dates and times of day. Storage size is two 4-byte
- integers: 4 bytes for the number of days before or after the base date of
- January 1, 1900, and 4 bytes for the number of milliseconds after
- midnight. The date segment of datetime values representing dates before
- the base date are stored as negative values.
-
- Data values for datetime range from January 1, 1753, to December 31, 9999.
- The maximum datetime value is the last day of the year 9999. SQL Server
- will reject all values it cannot recognize as dates between 1753 and 9999.
-
- SQL Server stores datetime data to an accuracy of .003 milliseconds. The
- entries .001, .002, and .003 are stored as .000, while an entry of .004 is
- stored as .003.
-
- The default display format for dates is "mon dd yyyy hh:miAM" (or PM),
- such as "Apr 15 1988 10:23AM".
-
- When you enter datetime values, always enclose them in single or double
- quotation marks. Case is always ignored, and spaces can occur anywhere
- between date parts. SQL Server recognizes a wide variety of data entry
- formats for date and time values.
-
- When time data is entered, the order of time components is significant:
- hours; then minutes; then seconds; then milliseconds; then AM, am, PM, or
- pm (12AM is midnight, 12PM is noon). To be recognized as time, a value
- must contain either a colon or an AM/PM signifier.
-
- Milliseconds can be preceded either with a colon or a period. If preceded
- by a colon, the number means thousandths of a second. If preceded by a
- period, a single digit means tenths of a second, two digits mean
- hundredths of a second, and three digits mean thousandths of a second. For
- example, "12:30:20:1" means twenty and one-thousandth second past 12:30;
- "12:30:20.1" means twenty and one-tenth second past 12:30.
-
- The following formats for time data are acceptable:
-
- 14:30
- 14:30[:20:999]
- 14:30[:20.9]
- 4am
- 4 PM
- [0]4[:30:20:500]AM
-
- When date data is entered, the order of components can vary. Months can be
- in alphabetic or numeric format. Alphabetic format is either the full name
- of the month or its first three letters. Case is not significant.
-
- If the month is given in numeric format, you can use any of the following
- separators: slash (/), hyphen (-), period (.), or space ( ). You can also
- give a date without separators: you can enter January 1, 1998 as
- "19980101" or "980101".
-
- If the month is given in alphabetic format, the day and year can be in any
- location, either before or after the month. In addition to the previously
- mentioned separators, the day can optionally be followed by a comma (,).
- When the month is alphabetic and the values for day and year are grouped
- together, the first value is assumed to be the day. For example, 2 3 mar
- is stored as "Mar 2 2003 12:00:00AM".
-
- If the year is given with two digits, <50 is next century and >=50 is this
- century. So "25" is "2025" while "50" is "1950".
-
- The following formats for date data are acceptable:
-
- Apr[il] 15[,] [19]88
- [15] Apr[il][,] [19]88
- 1988 APR[IL]
- 4/15/1988
- 4-15-88
- [19]88[0415]
-
- A datetime value can be either time then date or date then time, or the
- year can be separated from the rest of the date:
-
- 10:23PM Apr 15 1988
- Apr 15 1988 10:23PM
- Apr 15 10:23PM 1988
-
- If time is missing, it defaults to midnight. For example, if you insert
- "Apr 15 1988", SQL Server stores this as "Apr 15 1988 12:00AM".
-
- If the day of the month is missing, it defaults to the first day of the
- month. If the month is missing, it defaults to January. If the entire date
- is missing, it defaults to the base date, January 1, 1900. For example, if
- you insert "4:33", SQL Server stores it as "Jan 1 1900 4:33AM".
-
- Use the CONVERT function's style parameter to obtain many additional date
- styles. (See "Conversion Function.")
-
- You can do some arithmetic calculations on datetime values with the
- built-in date functions. (See "Date Functions.")
-
- When you use LIKE with datetime values, SQL Server converts the dates to
- the standard datetime format and then to varchar. Since the standard
- storage format doesn't include seconds or milliseconds, you cannot search
- for seconds or milliseconds with LIKE and a match pattern.
-
- It is a good idea to use LIKE when you search for datetime values, since
- datetime entries may contain a variety of date parts. For example, if you
- insert the value "9:20" into a column named arrival_time, the clause WHERE
- arrival_time = "9:20 " would not find it because SQL Server converts the
- entry into "Jan 1, 1900 9:20AM". However, the clause WHERE arrival_time
- LIKE "%9:20%" would find it.
-
- sysname
- A user-defined datatype supplied by SQL Server and used in the system
- tables. Its definition is varchar(30) "NOT NULL".
-
- timestamp
- A column that is automatically updated when you use browse mode in a
- DB-LIBRARY application. (See "Browse Mode.") Every time a row containing a
- timestamp column is inserted or updated, the timestamp column is
- automatically updated. A table can have only one column of timestamp type.
- Its definition is varbinary (8) null.
-
- When a table is created that contains timestamp data, both the column and
- the datatype must be named "timestamp".
-
- user_type_name
- The name of a user-defined datatype created with the sp_addtype system
- procedure. For example, to add a type called nm, you might execute the
- following system procedure:
-
- sp_addtype nm, "varchar(30)", null
-
- The name of the user-defined datatype must conform to the rules for
- identifiers.
-
-
- Comments
-
- All system datatypes and user-defined datatypes default to NOT NULL in
- CREATE TABLE statements. When you include a user-defined datatype in a
- CREATE TABLE statement, you can override its nulltype specification.
- However, you cannot override the length specification.
-
- Datatypes are database objects, and their names must conform to the rules
- for identifiers. The names of the SQL-Server-supplied datatypes are not
- reserved words and can be used to name other objects.
-
- User-defined datatypes are defined in terms of system datatypes. Creating
- user-defined datatypes permits frequently used datatype and length
- information to be accessed under a name you choose. User-defined datatypes
- are created with the sp_addtype system procedure and dropped with
- sp_droptype. Rules and defaults can be bound to user datatypes with the
- sp_bindrule and sp_bindefault system procedures. See Chapter 2, "System
- Procedures," for details.
-
- When you create user-defined datatypes with sp_addtype, there are three
- parameters: the name you assign the datatype; the base datatype (one of the
- SQL-Server-supplied datatypes, which include length for char, varchar,
- binary, and varbinary); and either NULL or NOT NULL. The last parameter is
- optional.
-
- ────────────────────────────────────────────────────────────────────────────
- WARNING
-
- Whenever you create a table containing timestamp data, both the column and
- the datatype must be named literally "timestamp". For example, the following
- table has one timestamp column create table dates (timestamp timestamp)
- Do not change the name of a timestamp column using the sp_addtype system
- procedure. If you do not use "timestamp" as the column name and datatype
- name, the timestamp is not set when rows are inserted into a table.
- ────────────────────────────────────────────────────────────────────────────
-
- If you don't specify NULL or NOT NULL, NOT NULL is assumed. In the following
- examples, the first two examples are NOT NULL; the third is NULL. (Quotation
- marks are used when a parameter contains blanks or punctuation marks.)
-
- sp_addtype tid1, "char(6)"
- sp_addtype tid2, "char(6)", "not null"
- sp_addtype tid3, "char(6)", null
-
- The NULL/NOT NULL assignment for a user-defined datatype can be changed in a
- CREATE TABLE statement. However, the length specification cannot be changed;
- SQL Server will not allow you to specify a length for a user-defined
- datatype in a CREATE TABLE statement.
-
- User-defined datatypes cannot be used in temporary tables unless the
- datatypes exist in the tempdb database, that is, unless they have been
- explicitly created in tempdb during the current session or unless they have
- been permanently added to the model database by changing the instmodl.sql
- script. See the SQL Server Installation Guide for the location of this
- script on your system.
-
- All of the datatypes that handle numbers─int, smallint, tinyint, money, and
- float─support arithmetic operations and aggregate functions (except that you
- cannot use modulo with float or money). Computations that result in overflow
- conditions are handled as errors.
-
- Relational operators can be used on any of the datatypes except text and
- image.
-
- There are two ways to specify literal quotation marks within a char or
- varchar entry. The first method is to use two quotation marks. For example,
- if you have begun a character entry with a single quotation mark and wish to
- include a single quotation mark as part of the entry, use two single
- quotation marks:
-
- 'I don"t understand.'
-
- With double quotation marks:
-
- "He said, ""It's not really confusing."""
-
- The second method is to enclose one quotation mark in the opposite kind of
- quotation mark. In other words, surround an entry containing double
- quotation marks with single quotation marks (or vice versa). Here are some
- examples:
-
- 'George said, "There must be a better way."'
- "Isn't there a better way?"
- 'George asked, "Isn"t there a better way?"'
-
- To continue a character string onto the next line of your screen, enter a
- backslash (\) before going to the next line.
-
- Built-in functions are provided for character, numeric, and date datatypes.
- (See "Date Functions," "Mathematical Functions," "String Functions," and
- "Text Functions" for details.)
-
- Many conversions from one datatype to another are handled automatically by
- SQL Server. Others are available with the CONVERT function. However, there
- are some type conversions that can never be done. For example, you cannot
- convert datetime to tinyint. (See "Conversion Function" for more
- information.) Text and image data can be converted to char or varchar and
- binary or varbinary, respectively.
-
- Use the style parameter of the CONVERT function to obtain a wide variety of
- date display formats. (See "Conversion Function" for more information.)
-
- When you create NULL columns with certain datatypes, SQL Server
- automatically converts them to a different internal datatype to allow the
- storage of null values. The char datatype is automatically converted to
- varchar; binary to varbinary; datetime to datetimn; float to floatn; int,
- smallint, and tinyint to intn; and money to moneyn.
-
- SQL Server does not inform the user of the type change, and the user should
- be concerned about it only if querying the system tables.
-
- For a report on a user-defined datatype, execute sp_help. You can rename a
- user-defined datatype with sp_rename.
-
- When you perform mixed-mode arithmetic─arithmetic operations on values of
- different datatypes, for example int + smallint ─the resultant datatype is
- determined by the hierarchy of datatypes. The hierarchy of datatypes is
- created from the rank ordering of the hexadecimal values of the datatype
- codes. In a mixed-mode expression, the lower type is converted internally to
- the higher type.
-
- In the following example, the qty from the sales table is multiplied by
- royalty from the roysched table. The qty is a smallint (INT2), and the
- royalty is an int (INT4). INT2 has a hexadecimal value of 34; INT4 has a
- hexadecimal value of 38. Therefore, the resultant datatype is an int (INT4).
-
-
- smallint(qty) * int(royalty) = int
-
- The hierarchy of datatypes is shown in the systypes system table. (Also see
- the SQL Server System Administrator's Guide and the "Conversion Function.")
-
-
- You can use the following query to obtain a list of datatypes with their
- decimal and hexadecimal values. Select the name of the datatype and its
- decimal type code, then use CONVERT to compute the hexadecimal value of each
- type.
-
- select name, type, hex=convert(varbinary(2),type)
- from systypes
- order by type
- <execute>
-
- ╓┌─┌───────────────────┌────────┌────────────────────────────────────────────╖
- ────────────────────────────────────────────────────────────────────────────
- name type hex
- ------------ ------- -------
- text 35 0x23
- timestamp 37 0x25
- varbinary 37 0x25
- intn 38 0x26
- sysname 39 0x27
- ────────────────────────────────────────────────────────────────────────────
- sysname 39 0x27
- varchar 39 0x27
- binary 45 0x2d
- image 46 0x2e
- char 47 0x2f
- tinyint 48 0x30
- bit 50 0x32
- smallint 52 0x34
- int 56 0x38
- money 60 0x3c
- datetime 61 0x3d
- float 62 0x3e
- floatn 109 0x6d
- moneyn 110 0x6e
- datetimn 111 0x6f
-
- (19 rows affected)
-
-
- The results of this query on one of your databases will be slightly
- different if you have installed any user-defined datatypes. User types take
- on the hexadecimal value of their base types.
-
-
- See Also
-
- Aggregate Functions, Conversion Function, CREATE PROCEDURE, CREATE TABLE,
- Date Functions, EXECUTE, Parameters, Text/Image Datatypes, Text/Image
- Functions, Variables (Local and Global), Wildcard Characters, sp_addtype,
- sp_bindefault, sp_bindrule, sp_droptype, sp_help, sp_rename,
- sp_unbindefault, sp_unbindrule
-
-
- Date Functions
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Manipulate datetime values.
-
-
- Syntax
-
- All date functions take parameters except GETDATE. Function names,
- parameters, and results are as follows:
-
- ╓┌─────────┌────────────────────────────────┌────────────────────────────────╖
- Function Parameter Result
- ────────────────────────────────────────────────────────────────────────────
- DATEADD (datepart, number, date) A date produced by adding an
- interval to a date you specify.
- The result is a datetime value
- equal to the date plus the
- number of date parts.
-
- DATEDIFF (datepart, date1, date2) The number of dateparts between
- two specified dates. The result
- is a signed integer value equal
- to date2 minus date1 in date
- parts.
-
- Function Parameter Result
- ────────────────────────────────────────────────────────────────────────────
- DATENAME (datepart, date) The specified datepart (the
- first parameter) of the
- specified date (the second
- parameter) as a character
- string.
-
- DATEPART (datepart, date) The specified datepart (the
- first parameter) of the
- specified date (the second
- parameter) as an integer.
-
- GETDATE ( ) The current date and time in
- SQL Server's standard internal
- format for datetime values.
- GETDATE takes the NULL
- parameter, ( ).
-
- ────────────────────────────────────────────────────────────────────────────
- Function Parameter Result
- ────────────────────────────────────────────────────────────────────────────
- ────────────────────────────────────────────────────────────────────────────
-
-
-
-
- Examples
-
- A. Statement Result
-
- select rightnow = getdate( ) Nov 25 1995 10:32AM
- select datepart(month, getdate( )) 11
- select datename(month, getdate( )) November
-
- Example A assumes a current date of November 25, 1995, 10:32 am.
-
- B. select interval = dateadd(day, 21, pubdate)
- from titles
-
- Example B displays the new publication dates when the publication dates of
- all the books in the titles table slip 21 days.
-
- C. select newdate = datediff(day, pubdate, getdate())
- from titles
-
- Example C finds the number of days elapsed between pubdate and the current
- date (found with the GETDATE function).
-
-
- Options
-
- date
- A parameter used with DATEADD, DATEDIFF, DATENAME, and DATEPART. The date
- option can be either the function GETDATE, a character string in one of
- the acceptable date formats (see "Datatypes"), or the name of a datetime
- column.
-
- datepart
- A parameter used with DATEADD, DATEDIFF, DATENAME, and DATEPART. The
- following table lists the dateparts, the abbreviations recognized by SQL
- Server, and the acceptable values:
-
- ╓┌────────────┌─────────────┌────────────────────────────────────────────────╖
- Date Part Abbreviation Values
- ────────────────────────────────────────────────────────────────────────────
- year yy 1753-9999
- quarter qq 1-4
- month mm 1-12
- day of year dy 1-366
- day dd 1-31
- week wk 1-53
- weekday dw 1-7 (Sun.-Sat.)
- hour hh 0-23
- minute mi 0-59
- second ss 0-59
- millisecond ms 0-999
- ────────────────────────────────────────────────────────────────────────────
-
-
- If the year is given with two digits, <50 is the next century and >=50 is
- this century. So "25" is "2025", while "50" is "1950".
-
- When you use week with DATEDIFF, you get the number of Sundays between the
- two dates, including the first date but not the second. For example, the
- difference in weeks between Sunday, January 4, and Sunday, January 11, is
- one.
-
- Milliseconds can be preceded either with a colon or a period. If preceded
- by a colon, the number means thousandths of a second. If preceded by a
- period, a single digit means tenths of a second, two digits mean
- hundredths of a second, and three digits mean thousandths of a second. For
- example, "12:30:20:1" means twenty and one-thousandth second past 12:30;
- "12:30:20.1" means twenty and one-tenth second past 12:30.
-
-
- Comments
-
- Date functions can be used in the select list or WHERE clause of a query.
-
- Use the datetime datatype only for dates after January 1, 1753.
-
- When you enter datetime values, always enclose them in single or double
- quotation marks.
-
- Values of type datetime are stored in a special internal format. They are
- displayed in a default format and can be entered in a variety of formats.
- (See "Datatypes" for more information.)
-
- SQL Server automatically converts between character and datetime values when
- necessary (for example, when you compare a character value to a datetime
- value).
-
- Use the style parameter of the CONVERT function to obtain a wide variety of
- date display formats. (See "Conversion Function" for more information.)
-
- The DATEDIFF function does not produce reliable results if your result in
- milliseconds is greater than 2 billion. For example, if you try to find the
- difference in milliseconds between two dates more than a year apart, your
- result will not be accurate.
-
-
- See Also
-
- Conversion Function, Expressions, Functions, SELECT, WHERE Clause
-
-
- DBCC
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Checks the logical and physical consistency of a database, ordinarily either
- because damage is suspected or as part of a periodic check.
-
-
- Syntax
-
- DBCC
- {CHECKTABLE (table_name) | CHECKDB [(database_name)] |
- CHECKALLOC [(database_name)] | CHECKCATALOG [(database_name)] |
- DBREPAIR (database_name, DROPDB) }
-
-
- Examples
-
- A. dbcc checktable(titleauthor)
-
- B. dbcc checkalloc(pubs)
-
- C. dbcc dbrepair(pubs, dropdb)
-
-
- Options
-
- CHECKTABLE
- 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, that the data information on each page is reasonable, and that
- page offsets are reasonable.
-
- CHECKDB
- 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.
-
- CHECKALLOC
- 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 the report
- on pubs:
-
- Checking pubs Alloc page 0 (# of extent=32 used pages=65 ref
- pages=65)
- Alloc page 256 (# of extent=32 used pages=140 ref pages=140)
- Alloc page 512 (# of extent=32 used pages=186 ref pages=186)
- Alloc page 768 (# of extent=10 used pages=40 ref pages=40)
- Total (# of extent=106 used pages=431 ref pages=431) in this database
- DBCC execution completed. If DBCC printed error messages,
- see your system administrator.
-
- This database contains four allocation units, 512K each, or 2 megabytes in
- all (the default size of a database).
-
- There are 32 extents (required for the creation of new database objects)
- per allocation page; the number of extents tells whether or not you can
- create new objects in the database. There are 8 pages per extent; the
- number of used pages tells 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.
-
- CHECKCATALOG
- Checks for consistency in 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. CHECKCATALOG also
- reports on any segments that have been defined. If no database name is
- given, CHECKCATALOG checks the current database.
-
- DBREPAIR (database_name, DROPDB)
- Drops a damaged database. The DROP DATABASE statement does not work on a
- damaged database. No user, including the person executing the statement,
- can be using the database that is being dropped when this DBCC statement
- is executed.
-
-
- Comments
-
- DBCC (Database Consistency Checker) can be run while the database is active
- except for the DBREPAIR(database_name, DROPDB) option.
-
- A warning message may be issued by DBCC, either during CHECKDB or
- CHECKTABLE, 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, follow this procedure:
-
-
- 1. Use the sp_configure stored procedure to enable updates to system
- catalogs.
-
- 2. Execute the RECONFIGURE WITH OVERRIDE statement for that change in
- configuration to take effect.
-
- 3. When using the database where the DBCC check was done, execute the
- following 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. Disable updates to system catalogs with sp_configure.
-
- 6. Execute the RECONFIGURE statement.
-
-
- Because of the special status of sysindexes as a system table, it is
- necessary to qualify the update and restrict it to a single row as described
- above. The value for the qualification's comparison to indid will be 1 if
- there is a clustered index on that table and 0 if there is none.
-
-
- Permissions
-
- DBCC permission defaults to the table owner for CHECKTABLE and to the
- Database Owner for CHECKDB, CHECKALLOC, CHECKCATALOG, and DBREPAIR. It is
- not transferable.
-
-
- See Also
-
- DROP DATABASE, sp_helpdb
-
-
- DECLARE
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Declares the name and type of local variables for a batch or procedure.
- Local variables are assigned values with a SELECT statement.
-
-
- Syntax
-
- Variable declaration:
-
- DECLARE @variable_name datatype
- [, @variable_name datatype...]
-
- Variable assignment:
-
- SELECT @variable = expression [, @variable = expression...]
- [FROM table_list]
- [WHERE search_conditions]
- [GROUP BY group_by_list] [HAVING search_conditions]
- [ORDER BY order_by_list]
- [COMPUTE function_list [BY by_list]]
-
-
- Examples
-
- A. declare @one varchar(18), @two varchar(18)
- select @one = "this is one", @two = "this is two"
- if @one = "this is one"
- print "you got one"
- if @two = "this is two"
- print "you got two"
- else print "nope"
-
- B. declare @veryhigh money
- select @veryhigh = max(price)
- from titles
- if @veryhigh > $20
- print "Ouch!"
-
-
- Options
-
- variable_name
- The name of the variable. It must conform to the rules for identifiers.
- Variables can be used only in place of constants. They cannot be used in
- place of the names of tables, columns, other database objects, or
- keywords.
-
- datatype
- A system datatype or a user datatype.
-
-
- Comments
-
- The "at" sign (@) denotes a variable name.
-
- Local variables must be used within the batch or procedure in which they are
- declared.
-
- Local variables are often used in a batch or procedure as counters for WHILE
- loops or IF...ELSE blocks.
-
- When they are used in stored procedures, local variables are declared for
- automatic, noninteractive use by the procedure when it executes.
-
- The SELECT statement that assigns a value to the local variable usually
- returns a single value. If the SELECT variable assignment statement returns
- more than one value, the variable is assigned the last value returned.
-
- The PRINT and RAISERROR statements can take local variables as parameters.
-
- The SELECT statement that assigns values to variables cannot be used to
- retrieve data in the same statement.
-
- The maximum number for each parameter and global variable in a procedure is
- 255. See "Variables (Local and Global)." There is no limit on the number of
- local variables.
-
- Users cannot declare global variables.
-
-
- See Also
-
- Parameters, PRINT, RAISERROR, Variables (Local and Global), WHILE
-
-
- DELETE
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Removes rows from a table.
-
-
- Syntax
-
- A. DELETE [[database.]owner.]{table_name | view_name}
- [FROM [[database.]owner.]{table_name | view_name}
- [, [[database.]owner.]{table_name | view_name}]...]
- [WHERE search_conditions]
-
- B. DELETE [FROM] [[database.]owner.]{table_name | view_name}
- [WHERE search_conditions]
-
-
- Examples
-
- A. delete authors
-
- Example A deletes all rows from the authors table.
-
- B. delete from authors
- where au_lname = "McBadden"
-
- Example B deletes one row from the authors table.
-
- C. delete titles
- from titles, authors, titleauthor
- where authors.au_lname = 'Bennet'
- and authors.au_id = titleauthor.au_id
- and titleauthor.title_id = titles.title_id
-
- Example C deletes rows for books written by Bennet from the titles table.
- (The pubs database includes a trigger (deltitle) that prevents the deletion
- of titles that are recorded in the sales table; you must drop this trigger
- to make the last example work.)
-
-
- Options
-
- FROM (see syntax A)
- The additional FROM optionally lets you name more than one table or view
- to use with a WHERE clause to specify which rows to delete. The additional
- FROM clause allows you to delete rows from one table based on data stored
- in other tables, giving you much of the power of an embedded SELECT
- statement.
-
- FROM (see syntax B)
- An optional keyword for compatibility with other versions of SQL. Follow
- it with the name of the table or view from which you want to remove rows.
-
- WHERE
- A standard WHERE clause. (See "WHERE Clause" for more information.)
-
-
- Comments
-
- If you don't use a WHERE clause, all rows in the table named after DELETE
- [FROM] are removed. The table, though empty of data, continues to exist
- until you use a DROP TABLE statement.
-
- TRUNCATE TABLE and DELETE without specifying any rows are functionally
- equivalent, but TRUNCATE TABLE is faster. DELETE removes rows one at a time
- and logs these transactions; TRUNCATE TABLE removes whole data pages and is
- not logged.
-
- Both DELETE and TRUNCATE TABLE reclaim the space occupied by the data and
- its associated indexes.
-
- The second FROM clause allows you to delete rows from one table based on
- data stored in other tables.
-
- You can define a trigger that takes a specified action when a DELETE
- statement is executed on a specified table.
-
-
- Permissions
-
- DELETE permission defaults to the table or view owner, who can transfer it
- to other users.
-
-
- See Also
-
- CREATE TRIGGER, DROP TABLE, TRUNCATE TABLE
-
-
- DISK INIT
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Reserves and formats physical storage for database devices. Database devices
- contain databases and transaction logs. DISK INIT also provides a physical
- filename and a logical filename for the database file. (You need not use
- DISK INIT on the master database device; it is initialized when SQL Server
- is installed.)
-
-
- Syntax
-
- DISK INIT
- NAME = "logical_name" ,
- PHYSNAME = "physical_name" ,
- VDEVNO = virtual_device_number ,
- SIZE = number_of_blocks
- [, VSTART = virtual_address ,
- CNTRLTYPE = controller_number]
-
-
- Examples
-
- disk init
- name = "user_file",
- physname = "f:\sqlservr\data\userdisk.dat",
- vdevno = 2, size = 5120
-
-
- Options
-
- NAME
- The logical name of the database device. It must correspond to the rules
- for identifiers and must be enclosed in single or double quotation marks.
- This name is used in the CREATE DATABASE and ALTER DATABASE statements.
- Although a name longer than 30 characters is allowed, the name will be
- truncated to 30 characters.
-
- PHYSNAME
- The full pathname of the database device. It must follow the rules for the
- operating system pathnames. It must be enclosed in single or double
- quotation marks.
-
- VDEVNO
- The virtual device number. It must be unique among database devices
- associated with SQL Server. The device number 0 is reserved for the master
- database device. Legal numbers are between 1 and 9. To determine the
- virtual device number, look at the device_number column of sysdevices with
- sp_helpdevice, and use the next integer.
-
- SIZE
- The size of the database device in 2K blocks.
-
- If you are planning to use the new database device for the creation of a
- new database, the minimum SIZE is the size of the model database, 1024 2K
- blocks (2 megabytes). If you are initializing a database device that will
- contain a transaction log, SIZE can be as small as 512 2K blocks (1
- megabyte).
-
- VSTART
- The starting virtual address or the starting offset in 2K blocks. The
- value for VSTART should be 0 (the default). Reset VSTART only if
- instructed to do so.
-
- CNTRLTYPE
- The disk controller. Its default value is zero. Reset CNTRLTYPE only if
- instructed to do so.
-
-
- Comments
-
- Execute DISK INIT once for each new database device. Each time DISK INIT is
- executed, a row is added to master..sysdevices.
-
- It is important to back up the master database with the DUMP DATABASE or
- DUMP TRANSACTION statement after each use of DISK INIT. This makes recovery
- easier and safer in case master is damaged. (If you add a database device
- with DISK INIT and fail to back up master, you may be able to recover the
- changes by using DISK REINIT and then stopping and restarting SQL Server.)
-
- User databases are assigned to database devices with the optional "ON
- database_file" clause of the CREATE DATABASE or ALTER DATABASE statement.
-
- A new database device does not automatically become part of the pool of
- default database storage. Assign default status to a database device with
- the sp_diskdefault system procedure.
-
- To put a database's transaction log (that is, the system table syslogs) on a
- different database device than the one on which the rest of the database is
- stored, name at least two database devices when you create the database, and
- then execute the sp_logdevice system procedure. You can also alter the
- database to a second database device and then run sp_logdevice.
-
- For a report on all database devices and dump devices on your system,
- execute the sp_helpdevice system procedure.
-
- Remove a database device with the sp_dropdevice system procedure. You must
- first drop all existing databases on that database device.
-
- After dropping a database device, you can create a new one with the same
- logical name (using DISK INIT) as long as you give it a different physical
- name and virtual device number. If you wish to use the same physical name
- and virtual device number, you must restart SQL Server.
-
-
- Permissions
-
- DISK INIT permission defaults to the System Administrator and is not
- transferable. The System Administrator must be using the master database to
- use DISK INIT.
-
-
- See Also
-
- CREATE DATABASE, DISK REFIT, DISK REINIT, DUMP DATABASE, DUMP TRANSACTION,
- LOAD DATABASE, LOAD TRANSACTION, sp_diskdefault, sp_helpdevice, sp_logdevice
-
-
-
- DISK REFIT
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Restores a damaged master database if databases have been created or
- database space allocated since the last database or transaction log dump.
- This statement is used after DISK REINIT.
-
-
- Syntax
-
- DISK REFIT
-
-
- Examples
-
- disk refit
-
-
- Comments
-
- DISK REFIT is used after DISK REINIT. It uses information in sysdevices to
- rebuild sysusages and sysdatabases.
-
- Stop and then restart SQL Server after using DISK REFIT.
-
- For more information, see the SQL Server System Administrator's Guide.
-
-
- Permissions
-
- DISK REFIT permission defaults to the System Administrator and is not
- transferable. The System Administrator must be in the master database to use
- DISK REFIT.
-
-
- See Also
-
- DISK INIT, DISK REINIT, sp_addumpdevice, sp_helpdevice
-
-
- DISK REINIT
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Part of the procedure that restores a damaged master database if database
- devices have been added since the last database or transaction log dump.
-
-
- Syntax
-
- DISK REINIT
- NAME = "logical_name",
- PHYSNAME = "physical_name" ,
- VDEVNO = virtual_device_number ,
- SIZE = number_of_blocks
- [, VSTART = virtual_address ,
- CNTRLTYPE = controller_number]
-
-
- Examples
-
- disk reinit
- name = "user_disk",
- physname = "f:\sqlservr\data\userdisk.dat",
- vdevno = 2, size = 5120
-
-
- Options
-
- NAME
- The logical name of the database device. It must correspond to the rules
- for identifiers and must be enclosed in single or double quotation marks.
- This name is used in the CREATE DATABASE and ALTER DATABASE statements.
- Although a name longer than 30 characters is allowed, the name will be
- truncated to 30 characters.
-
- PHYSNAME
- The full pathname of the database device. It must follow the rules for the
- operating system pathnames. It must be enclosed in single or double
- quotation marks.
-
- VDEVNO
- The virtual device number. It must be unique among database devices used
- by SQL Server. The device number 0 is reserved for the master database
- device. Legal numbers are between 1 and 49.
-
- SIZE
- The size of the database device in 2K blocks. The minimum usable size is
- 1024 2K blocks (2 megabytes).
-
- VSTART
- The starting virtual address or the starting offset in 2K blocks. The
- value for VSTART should be 0 (the default). Reset it only if instructed to
- do so.
-
- CNTRLTYPE
- The disk controller. Its default value is 0. Reset it only if instructed
- to do so.
-
-
- Comments
-
- DISK REINIT insures that master..sysdevices is correct if a master database
- has been damaged and database devices have been added since the last dump of
- master.
-
- DISK REINIT is very similar to DISK INIT but does not initialize the disk
- space.
-
- See the SQL Server System Administrator's Guide for more complete
- information on using DISK REINIT.
-
-
- Permissions
-
- DISK REINIT permission defaults to the System Administrator and is not
- transferable. The System Administrator must be in the master database to use
- DISK REINIT.
-
-
- See Also
-
- DISK INIT, DISK REFIT, sp_addumpdevice, sp_helpdevice
-
-
- DROP DATABASE
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Removes one or more databases from SQL Server.
-
-
- Syntax
-
- DROP DATABASE database_name [, database_name...]
-
-
- Examples
-
- A. drop database publishing
-
- B. drop database publishing, newpubs
-
- Examples A and B remove databases and their contents.
-
-
- Comments
-
- Removing a database deletes the database and all its objects, frees its
- storage allocation, and erases references to it in the master database.
-
- You cannot drop a database that is in use (open for reading or writing by
- any user).
-
- A damaged database cannot be removed with DROP DATABASE. Use the DBCC
- DBREPAIR statement:
-
- dbcc dbrepair (database_name, dropdb)
-
-
- Permissions
-
- DROP DATABASE permission defaults to the Database Owner and cannot be
- transferred. The master database must be current at the time. (A database is
- made current with the USE statement.)
-
-
- See Also
-
- ALTER DATABASE, CREATE DATABASE, DBCC, USE, sp_changedbowner, sp_helpdb,
- sp_renamedb, sp_spaceused
-
-
- DROP DEFAULT
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Removes a user-specified default.
-
-
- Syntax
-
- DROP DEFAULT [owner.]default_name
- [, [owner.]default_name...]
-
-
- Examples
-
- drop default datedefault
-
- This example removes user-created default datedefault.
-
-
- Options
-
- default_name
- The name of an existing default. You can find out what defaults exist by
- executing the sp_help system procedure.
-
-
- Comments
-
- A default cannot be dropped if it is currently bound to a column or user
- datatype. Use the sp_unbindefault system procedure to unbind the default
- before you drop it. See Chapter 2, "System Procedures," for details.
-
- You can bind a new default to a column or user datatype without unbinding
- its current default. The new default will override the old one.
-
- When you drop a default for a NULL column, NULL will from then on be
- inserted in that position when rows are added but no value for that column
- is entered. When you drop a default for a NOT NULL column, you'll get an
- error message when rows are added but no value for that column is explicitly
- entered.
-
-
- Permissions
-
- DROP DEFAULT permission defaults to the owner of the default and is not
- transferable.
-
-
- See Also
-
- CREATE DEFAULT, CREATE RULE, DROP RULE, sp_bindefault, sp_help, sp_helptext,
- sp_rename, sp_unbindefault
-
-
- DROP INDEX
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Removes an index from the database.
-
-
- Syntax
-
- DROP INDEX table_name.index_name [, table_name.index_name...]
-
-
- Examples
-
- drop index authors.au_id_ind
-
- This example removes the index au_id_ind in the authors table.
-
-
- Options
-
- table_name
- The table in which the indexed column is located.
-
- index_name
- The index to be dropped. In TRANSACT-SQL, index names need not be unique
- in a database, though they must be unique within a table.
-
-
- Comments
-
- Once the statement is executed, you regain all of the space occupied by the
- index. This space can be used for any database objects.
-
- You can't use DROP INDEX on any of the system tables that exist in the
- master database and in user databases.
-
- To get information about what indexes exist on a table or view, use the
- sp_helpindex system procedure with the table name as parameter.
-
-
- Permissions
-
- DROP INDEX permission defaults to the index owner and is not transferable.
-
-
- See Also
-
- CREATE INDEX, CREATE TABLE, sp_helpindex, sp_spaceused
-
-
- DROP PROCEDURE
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Removes user-created stored procedures from the current database.
-
-
- Syntax
-
- DROP PROCedure procedure_name [procedure_name...]
-
-
- Examples
-
- use pubs
- <execute>
- drop procedure byroyalty
-
- This example removes the stored procedure byroyalty.
-
-
- Comments
-
- You can drop stored procedures only from the current database. The existence
- of a stored procedure is checked on each call to that procedure.
-
- A procedure group (more than one procedure with the same name but with
- different ;number suffixes) can be dropped with a single DROP PROCEDURE
- statement. For example, if the procedures used with the application orders
- were named orderproc;1, orderproc;2, and so on, the following statement
- would drop the entire group:
-
- drop proc orderproc
-
- Once procedures have been grouped, individual procedures within the group
- cannot be dropped. For example, the following statement is not allowed:
-
- drop procedure orderproc;2
-
- The sp_helptext system procedure displays the procedure definition (which is
- stored in syscomments). See Chapter 2, "System Procedures," for details.
-
-
- Permissions
-
- DROP PROCEDURE permission defaults to the procedure owner and is not
- transferable.
-
-
- See Also
-
- CREATE PROCEDURE, EXECUTE, sp_depends, sp_helptext, sp_rename
-
-
- DROP RULE
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Removes a user-specified rule.
-
-
- Syntax
-
- DROP RULE [owner.]rule_name
- [, [owner.]rule_name...]
-
-
- Examples
-
- drop rule pubid_rule
-
- This example removes the pubid_rule rule.
-
-
- Comments
-
- Use the sp_unbindrule system procedure to unbind the rule before dropping
- it. If it is still in effect, an error message will be displayed and the
- DROP RULE statement will be aborted. See Chapter 2, "System Procedures," for
- details.
-
- You can bind a new rule to a column or user datatype without unbinding its
- current rule. The new rule overrides the old one.
-
- After you drop a rule, new data entered into the columns that previously
- were governed by it goes in without these constraints. Already existing data
- is not affected in any way.
-
-
- Permissions
-
- DROP RULE permission defaults to the rule owner and is not transferable.
-
-
- See Also
-
- CREATE DEFAULT, CREATE RULE, DROP DEFAULT, sp_bindrule, sp_help,
- sp_helptext, sp_rename, sp_unbindrule
-
-
- DROP TABLE
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Removes a table definition and all data, indexes, triggers, and permission
- specifications for a table from the database.
-
-
- Syntax
-
- DROP TABLE [[database.]owner.]table_name
- [, [[database.]owner.]table_name...]
-
-
- Examples
-
- drop table roysched
-
- This example removes the roysched table and its data and indexes.
-
-
- Comments
-
- When you drop a table, any rules or defaults on it lose their binding, and
- any triggers associated with it are automatically dropped. If you re-create
- a table, you must rebind the appropriate rules and defaults, and re-create
- any triggers.
-
- The system tables affected when a table is dropped are sysobjects,
- syscolumns, sysindexes, sysprotects, and syscomments.
-
- You can't use the DROP TABLE statement on any of the system tables, either
- in the master database or in a user database.
-
- You can drop a table in any database if you are the table owner. The
- following examples drop newtable in the otherdb database:
-
- drop table otherdb..newtable
-
- drop table otherdb.yourname.newtable
-
- If you delete all the rows in a table or give the TRUNCATE TABLE statement,
- the table still exists until you drop it.
-
-
- Permissions
-
- DROP TABLE permission defaults to the table owner and is not transferable.
-
-
- See Also
-
- ALTER TABLE, CREATE TABLE, DELETE, TRUNCATE TABLE, sp_depends, sp_help,
- sp_rename, sp_spaceused
-
-
- DROP TRIGGER
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Removes a trigger.
-
-
- Syntax
-
- DROP TRIGGER [owner.]trigger_name [, [owner.]trigger_name...]
-
-
- Examples
-
- drop trigger trigger1
-
-
- Permissions
-
- DROP TRIGGER permission defaults to the trigger owner and is not
- transferable.
-
-
- See Also
-
- CREATE TRIGGER, sp_depends, sp_help, sp_helptext, sp_rename
-
-
- DROP VIEW
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Removes views from the database.
-
-
- Syntax
-
- DROP VIEW [owner.]view_name [, [owner.]view_name...]
-
-
- Examples
-
- drop view new_pricey
-
- This example removes the new_pricey view.
-
-
- Comments
-
- When you use DROP VIEW, the definition of the view and other information
- about it are deleted from the system tables sysobjects, syscolumns,
- syscomments, sysprocedures, and sysprotects. All permissions for the view
- are deleted, too.
-
- Existence of a view is checked each time the view is referenced by another
- view or by a stored procedure.
-
-
- Permissions
-
- DROP VIEW permission defaults to the view owner and is not transferable.
-
-
- See Also
-
- CREATE VIEW, Views, sp_depends, sp_help, sp_helptext, sp_rename
-
-
- DUMP DATABASE
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Makes a backup copy of the database and the transaction log in a form that
- can be read in with LOAD DATABASE.
-
-
- Syntax
-
- DUMP DATABASE database_name
- TO dump_device
-
-
- Examples
-
- dump database pubs
- to diskdump1
-
- This example dumps the pubs database to the diskdump1 diskette.
-
-
- Options
-
- database_name
- The name of the database from which you are copying data.
-
- TO dump_device
- The logical name of the dump device to which you are dumping the specified
- database. Logical dump device names are stored in master..sysdevices.name.
- A report on dump devices is displayed when you execute sp_helpdevice.
- (Logical dump device names are in the report column device_name.)
-
- You add dump devices with the sp_addumpdevice system procedure. See
- Chapter 2, "System Procedures," or the SQL Server System Administrator's
- Guide for details.
-
-
- Comments
-
- SQL Server database dump is a dynamic dump─it can take place while the
- database is active. It slows the system down minimally, so you may want to
- run it when the database is not being heavily updated.
-
- The dump device is on the machine on which SQL Server is running.
-
- When the DUMP DATABASE statement is executed for dumping to a diskette, the
- console program prompts the operator and waits for responses. (See Chapter
- 3, "Utility Programs," for more information on console.) If console is not
- running or if the operator does not answer its questions, the dump cannot
- proceed.
-
- The dump captures the state of the database as it was at the moment the
- statement was executed. Any changes made after the dump begins are not
- reflected in the dumped database.
-
- To recover a database, load the most recent database dump and load all the
- transaction log dumps made since that database dump. The database into which
- you are loading the data is replaced by this reconstruction.
-
- DUMP DATABASE backs up the database and the log but does not remove the
- inactive portion of the log. DUMP TRANSACTION backs up the log and removes
- the inactive portion of it.
-
- The DUMP DATABASE statement must be used to back up both the database and
- its transaction log for small databases. Databases smaller than about 4
- megabytes can store their transaction logs on the same database device as
- the rest of the database. In this situation, DUMP DATABASE is used to create
- backups, and DUMP TRANSACTION WITH TRUNCATE_ONLY can be used to purge the
- log of completed transactions. Databases larger than 4 megabytes should
- store their transaction logs on a different database device, which improves
- performance and enables unrestricted use of both the DUMP DATABASE and DUMP
- TRANSACTION statements.
-
- You can run more than one dump (or load) at the same time, but only if the
- cntrltype values of the devices to which you are dumping or loading are
- different. For example, only one dump or load through the disk byte stream
- interface can be active at a time.
-
- For more information on SQL Server's backup and recovery facilities, see the
- SQL Server System Administrator's Guide.
-
-
- Permissions
-
- DUMP DATABASE permission defaults to the Database Owner, who can transfer it
- to other users.
-
-
- See Also
-
- DUMP TRANSACTION, LOAD DATABASE, LOAD TRANSACTION, sp_addumpdevice,
- sp_dropdevice, sp_helpdb, sp_helpdevice, sp_logdevice, sp_spaceused
-
-
- DUMP TRANSACTION
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Removes the inactive part of the transaction log and makes a backup copy of
- it in a form that can be read in with LOAD TRANSACTION. The DUMP TRANSACTION
- and LOAD TRANSACTION statements should be used only when the transaction log
- is stored on a different database device than the rest of the database.
-
-
- Syntax
-
- DUMP TRANsaction database_name
- [TO dump_device]
- [WITH TRUNCATE_ONLY]
- [WITH NO_LOG]
-
-
- Examples
-
- dump transaction pubs
- to diskdump1
-
- This example dumps the transaction log to the diskdump1 dump device.
-
-
- Options
-
- TO dump_device
- The logical name of the dump device to which you are dumping the specified
- transaction log. Logical dump device names are available in
- master..sysdevices.name. To add a dump device, use the sp_addumpdevice
- system procedure.
-
- 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 optional clause 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
- Is used only when you have run out of space in the database so that you
- cannot even run 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 run 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.
-
-
- Comments
-
- A transaction log dump can take place while the database is active.
-
- The DUMP TRANSACTION (and LOAD TRANSACTION) statement should be used only
- when the transaction log is stored on a different database file than the
- rest of the database. This is recommended for databases larger than about 4
- megabytes. The transaction log is transferred to a separate database device
- with the sp_logdevice system procedure.
-
- With smaller databases, the transaction log is usually stored on the same
- database device as the rest of the database. In this situation, you use DUMP
- DATABASE to back up both the database and the transaction log, after which
- you can use DUMP TRANSACTION WITH TRUNCATE_ONLY to remove committed
- transactions from the log.
-
- DUMP TRANSACTION uses much less storage and takes much less time than DUMP
- DATABASE, which backs up both the transaction log and the rest of the
- database.
-
- When the DUMP TRANSACTION statement is executed for dumping to a diskette,
- the console program prompts the operator and waits for a response. If
- console is not running or if the operator does not answer its questions, the
- dump cannot proceed.
-
- Dumps of the transaction log are typically coordinated with DUMP DATABASE as
- part of an overall backup procedure. Transaction log dumps are made more
- frequently than database dumps.
-
- The dump captures the state of the transaction log as it was at the moment
- the statement was executed. Any changes made after the dump begins are not
- reflected in the dumped log.
-
- To recover a database, load the most recent database dump and load all the
- transaction log dumps (in order) made since the database dump. The database
- is restored to its state at the time of the last transaction log dump.
-
- ────────────────────────────────────────────────────────────────────────────
- WARNING
-
- Do not attempt to modify the transaction log table syslogs with a DELETE,
- UPDATE, or INSERT statement. Doing so makes it impossible for SQL Server to
- recover correctly in case of a system failure. In addition, an attempt to
- delete all rows from syslogs causes SQL Server to get into an infinite loop
- that eventually fills up the entire database.
- ────────────────────────────────────────────────────────────────────────────
-
- You can run more than one dump (or load) at the same time, but only if the
- cntrltype values of the devices to which you are dumping or loading are
- different. For example, only one dump or load through the disk byte stream
- interface can be active at a time.
-
- You cannot execute the DUMP TRANSACTION statement while the select
- into/bulkcopy or the trunc. log on chkpt. database options are enabled. Use
- DUMP DATABASE instead, or disable the option with sp_dboption.
-
-
- Permissions
-
- DUMP TRANSACTION permission defaults to the Database Owner, who can transfer
- it to other users. For more information on SQL Server's backup and recovery
- facilities, see the SQL Server System Administrator's Guide.
-
-
- See Also
-
- DUMP DATABASE, LOAD DATABASE, LOAD TRANSACTION, sp_addumpdevice,
- sp_dboption, sp_dropdevice, sp_helpdevice, sp_logdevice
-
-
-
-
-
- EXECUTE
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Runs a system procedure or a user-defined stored procedure. This statement
- is only necessary if other statements are submitted in the same batch.
-
-
- Syntax
-
- [EXECute] [[database.]owner.]procedure_name[;number]
- [[@parameter_name =] value [,[@parameter_name =] value]...]
- [WITH RECOMPILE]
-
-
- Examples
-
- Supply parameters in either of two ways: by value or with "parameter_name =
- value". If you use the "parameter_name = value" form, you need not supply
- the parameters in the order defined in the CREATE PROCEDURE statement.
-
- A. execute showind titles
-
- B. exec showind @tabname = titles
-
- If this is the only statement in a batch or file, you can use the following
- form:
-
- C. showind titles
-
- The showind stored procedure with a parameter value titles has been
- executed.
-
-
- Options
-
- procedure_name
- The name of a procedure that has been defined with a CREATE PROCEDURE
- statement. You can execute a procedure that has been created in another
- database as long as you are its owner or have permission to execute it in
- that database.
-
- ;number
- An optional integer used to group procedures of the same name so that they
- can be dropped together with a single DROP PROCEDURE statement. Procedures
- used in the same application are often grouped this way. For example, the
- procedures used with the application orders might be named orderproc;1,
- orderproc;2, and so on. The statement DROP PROCEDURE orderproc would drop
- the entire group. Once procedures have been grouped, individual procedures
- within the group cannot be dropped. For example, the statement DROP
- PROCEDURE orderproc;2 is not allowed.
-
- parameter_name
- The name of a parameter to the procedure, as defined in the CREATE
- PROCEDURE statement. Parameter names must be preceded by the "at" symbol
- (value" form, parameter names and constants need not be supplied in the
- order defined in the CREATE PROCEDURE statement.
-
- value
- The value of the parameter or parameter to the procedure. If you do not
- use parameter names, parameter values must be supplied in the order
- defined in the CREATE PROCEDURE statement.
-
- If a default is defined in the CREATE PROCEDURE statement, a user can
- execute the procedure without giving a parameter. The default must be a
- constant. It can include the wildcard characters (%, _, [ ], and [^]) if
- the procedure uses the parameter name with the LIKE keyword. See example B
- in the "CREATE PROCEDURE" section.
-
- The default can be NULL. Usually, the procedure definition specifies what
- action should be taken if a parameter value is NULL.
-
- WITH RECOMPILE
- Forces compilation of a new plan only for this execution of the procedure.
- Use this option if the parameter you're supplying for this execution is
- atypical.
-
- The original plan is used on subsequent executions.
-
-
- Comments
-
- If the user does not supply expected parameters, the stored procedure error
- message lists the names of expected parameters in reverse order.
-
- You don't need to use the EXECUTE keyword if the statement is the first one
- in a batch. A batch is a segment of an input file terminated by the go
- command on a line by itself.
-
- Since stored procedures are compiled the first time they are executed,
- subsequent run time is much shorter than for the equivalent set of
- stand-alone statements.
-
- System procedures (for example, sp_help) do not work on temporary tables
- because a procedure cannot access a temporary object unless it created the
- object itself during the current session.
-
- See "System Procedures," later in this chapter, and Chapter 2, "System
- Procedures," for details.
-
-
- Permissions
-
- EXECUTE permission defaults to the owner of the stored procedure, who can
- transfer it to other users.
-
-
- See Also
-
- CREATE PROCEDURE, DROP PROCEDURE, Parameters, System Procedures, Variables
- (Local and Global), Wildcard Characters, sp_depends, sp_helptext
-
-
- Expressions
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Used as variables and constants in many SQL statements.
-
-
- Syntax
-
- An expression returns values. Expressions have the following syntax:
-
- {constant | column_name | function | (subquery)}
- [{arithmetic_operator | bitwise_operator | string_operator}
- {constant | column_name | function | (subquery)}...]
-
- A boolean expression returns true or false. It has the following syntax:
-
- - expression comparison_operator [ANY | ALL] expression
- - expression [NOT] IN expression
- - [NOT] EXISTS expression
- - expression [NOT] BETWEEN expression AND expression
- - expression [NOT] LIKE expression
- - NOT expression LIKE expression
- - expression IS [NOT] NULL
- - NOT boolean_expression
- - boolean_expression {AND | OR} boolean_expression
- - [NOT] boolean_function
-
-
- Options
-
- function
- An aggregate function or a built-in function. See "Functions" for more
- information.
-
- subquery
- A nested SELECT statement with some restrictions. A subquery can be used
- in place of an expression if it returns a single value. See "Subqueries"
- for more information.
-
- arithmetic_operator
- One of the following:
-
- ╓┌───────────────────────┌───────────────────────────────────────────────────╖
- Symbol Meaning
- Symbol Meaning
- ────────────────────────────────────────────────────────────────────────────
- ++ Addition
- - Subtraction
- * Multiplication
- / Division
- % Modulo
- ────────────────────────────────────────────────────────────────────────────
-
-
- Addition, subtraction, division, and multiplication can be used on int,
- smallint, tinyint, float, and money columns. The modulo operator cannot be
- used on money or float columns. Modulo finds the integer remainder after
- dividing two whole numbers. For example, 21 % 11 = 10, because 21 divided
- by 11 equals 1 with a remainder of 10.
-
- bitwise_operator
- One of the following:
-
- Symbol Meaning
- ────────────────────────────────────────────────────────────────────────────
- & Bitwise AND (two operands)
- | Bitwise OR (two operands)
- Bitwise exclusive OR (two operands)
- ~ Bitwise NOT (one operand)
- ────────────────────────────────────────────────────────────────────────────
-
- The bitwise operators that require two operands (&, |, and ^) can be used
- on columns with the datatypes shown below:
-
- ╓┌─────────────────┌─────────────────────────────────────────────────────────╖
- Left Operand Right Operand
- ────────────────────────────────────────────────────────────────────────────
- int int, smallint, tinyint, binary, or varbinary
- smallint int, smallint, tinyint, binary, or varbinary
- tinyint int, smallint, tinyint, binary, or varbinary
- varbinary int, smallint, or tinyint
- bit int, smallint, tinyint, or bit
- float none
- binary int, smallint, or tinyint
- ────────────────────────────────────────────────────────────────────────────
-
-
- The ~ bitwise operator can be used on columns with a datatype of int,
- smallint, tinyint, or bit.
-
- All the bitwise operators translate the integer parameters into binary
- representations before evaluating them. In the following examples, A =
- 10101010 and B = 01001011:
-
- (A & B) 10101010
- 01001011
- --------
- 00001010
-
- The result is 1 where both A and B are 1.
-
- (A | B) 10101010
- 01001011
- --------
- 11101011
-
- The result is 1 where A, B, or A and B are 1.
-
- (A ^ B) 10101010
- 01001011
- --------
- 11100001
-
- The result is 1 where A or B, but not both, are 1.
-
- (~A) 10101010
- --------
- 01010101
-
- All 1s are changed to 0s and all 0s to 1s.
-
- string_operator
- The string operator + can be used to concatenate expressions. See "String
- Functions" for examples.
-
- comparison_operator
- One of the following:
-
- ╓┌────────────────────┌──────────────────────────────────────────────────────╖
- Symbol Meaning
- ────────────────────────────────────────────────────────────────────────────
- = Equal to
- > Greater than
- < Less than
- >= Greater than or equal to
- <= Less than or equal to
- != Not equal to
- !> Not greater than
- !< Not less than
- ────────────────────────────────────────────────────────────────────────────
-
-
- In comparing char and varchar data, < means closer to the beginning of the
- alphabet and > means closer to the end of the alphabet. In the ASCII
- collating sequence, lowercase letters are greater than uppercase letters,
- and uppercase letters are greater than numbers. In comparing dates, <
- means earlier and > means later. Trailing blanks are ignored for
- comparison purposes. For example, "Dirk" is the same as "Dirk ".
-
- Put single or double quotation marks around all character and datetime
- data used with a comparison operator (= "Bennet", > "94609").
-
- ANY
- Is used with <, >, or = and a subquery. It returns results when any value
- retrieved in the subquery matches the value in the WHERE or HAVING clause
- of the outer statement. (See "Subqueries" for more information.)
-
- ALL
- Is used with < or > and a subquery. It returns results when all values
- retrieved in the subquery match the value in the WHERE or HAVING clause of
- the outer statement. (See "Subqueries" for more information.)
-
- NOT
- Negates the meaning of a keyword, a boolean function, or a boolean
- expression.
-
- IN
- Returns results when any value returned by the second expression matches
- the value in the first expression. The second expression must be a
- subquery or a list of values enclosed in parentheses. IN is equivalent to
- = ANY.
-
- See "WHERE Clause" for details.
-
- EXISTS
- Is used to test for the existence of some result. The expression that
- follows must be a subquery.
-
- BETWEEN
- The range-start keyword. Use AND for the range-end keyword. A range of
- between x and y is inclusive. A range of > x < y is not inclusive.
-
- LIKE
- Indicates that the following expression is a matching pattern. With LIKE,
- the second expression must always be a character string. LIKE is only
- available for char, varchar, and datetime columns (but not to search for
- seconds or milliseconds). It can be used with these wildcards:
-
- Wildcard Meaning
- ────────────────────────────────────────────────────────────────────────────
- % Any string of 0 or more characters
-
- _ (underscore) Any single character
-
- [ ] Any single character within the
- specified range ([a-f]) or set ([abcdef])
-
- [^] Any single character not within the
- specified range ([^a-f]) or set
- ([^abcdef])
-
- ────────────────────────────────────────────────────────────────────────────
-
-
- The wildcard and the string must be enclosed in single or double quotation
- marks (LIKE "[dD]eFr_nce"). For complete information, see "Wildcard
- Characters."
-
- NULL
- Indicates the value is "unknown" to the system. Use IS NULL or IS NOT NULL
- in queries on columns defined as NULL. If you use IS NULL or IS NOT NULL
- to query columns defined as NOT NULL, SQL Server displays an error
- message.
-
- An expression with a bitwise or arithmetic operator evaluates to NULL if
- any of the operands is null.
-
- AND
- Connects two expressions and returns results when both are true.
-
- When more than one logical operator is used in a statement, AND is handled
- first. However, you can change the order of execution with parentheses.
-
- OR
- Connects two or more conditions and returns results when either of the
- conditions is true.
-
- When more than one logical operator is used in a statement, OR is
- evaluated after AND. However, you can change the order of execution with
- parentheses.
-
- boolean_function
- A function that returns true or false.
-
-
- Comments
-
- Parentheses can be used to group the elements in an expression or a boolean
- expression.
-
- When "expression" is given as a variable in a syntax statement, a simple
- expression is assumed. "Boolean expression" is specified when only a boolean
- expression is acceptable.
-
- Operators have the following precedence levels, where 1 is the highest level
- and 6 is the lowest level:
-
-
- 1. (unary) ~ - +
-
- 2. * / %
-
- 3. + - & | ^
-
- 4. NOT
-
- 5. AND
-
- 6. OR
-
-
- When all operators in an expression are of the same level, the order of
- execution is left to right. You can change the order of execution with
- parentheses─the most deeply nested expression is evaluated first.
-
- There are two ways to specify literal quotation marks within a char or
- varchar entry. The first method is to use two quotation marks. For example,
- if you have begun a character entry with a single quotation mark and wish to
- include a single quotation mark as part of the entry, use two single
- quotation marks:
-
- 'I don"t understand.'
-
- With double quotation marks:
-
- "He said, ""It's not really confusing."""
-
- The second method is to enclose a quote in the opposite kind of quotation
- mark. In other words, surround an entry containing a double quotation mark
- with single quotation marks (or vice versa). Here are some examples:
-
- 'George said, "There must be a better way."'
- "Isn't there a better way?"
- 'George asked, "Isn"t there a better way?"'
-
- To continue a character string to the next line on your screen, enter a
- backslash (\) before going to the next line.
-
-
- See Also
-
- Functions, Joins, Search Conditions, SELECT, Subqueries, WHERE Clause,
- Wildcard Characters, sp_helpjoins
-
-
- Functions
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Return special information from the database. Functions are used in SELECT
- statements and are divided into aggregate functions (SUM, AVG, COUNT,
- COUNT(*), MAX, and MIN), date functions, mathematical functions, string
- functions, system functions, text/image functions, and type conversion
- functions. Each of these groups is discussed in its own section of this
- manual.
-
-
- Syntax
-
- Aggregate functions return summary values. See "Aggregate Functions" for
- syntax and other information.
-
- Date functions compute datetime values and their components, dateparts. See
- "Date Functions" for syntax and other information.
-
- Mathematical functions perform operations on numeric data. See "Mathematical
- Functions" for syntax and other information.
-
- String functions perform operations on character and binary data. See
- "String Functions" for syntax and other information.
-
- System functions return special information from the database. See "System
- Functions" for syntax and other information.
-
- Text/image functions perform operations on text and image data. See
- "Text/Image Functions" for syntax and other information.
-
- Conversion functions convert expressions of one datatype to another
- datatype. See "Conversion Function" for syntax and other information.
-
-
- Comments
-
- Unlike the aggregate functions, the other built-in functions are often used
- on their own or as part of a stored procedure or program. When they are used
- in SQL statements, they are allowed in the select list, in the WHERE clause,
- and anywhere an expression is allowed.
-
- Many of the miscellaneous built-in functions are SQL Server extensions to
- SQL.
-
-
- See Also
-
- Aggregate Functions, COMPUTE Clause, Conversion Function, Date Functions,
- Mathematical Functions, Search Conditions, SELECT, String Functions, System
- Functions, Text/Image Functions
-
-
- GOTO
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Causes an unconditional branching to a user-defined label.
-
-
- Syntax
-
- label:
-
- GOTO label
-
-
- Examples
-
- declare @count smallint
- select @count = 1
- restart:
- print "yes"
- select @count = @count + 1
- while @count <= 4
- goto restart
-
-
- Comments
-
- The label name must follow the rules for identifiers and must be followed by
- a colon (:) when it is declared. It is not followed by a colon when it is
- used with GOTO.
-
- GOTO is usually made dependent on an IF or WHILE test, or some other
- condition to avoid an endless loop between GOTO and the label.
-
-
- See Also
-
- Control-of-Flow Language, IF...ELSE, WHILE
-
-
- GRANT
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Assigns permissions to users.
-
-
- Syntax
-
- Object permissions:
-
- GRANT {ALL | permission_list}
- ON {table_name [(column_list)] | view_name [(column_list)] |
- stored_procedure_name}
- TO {PUBLIC | name_list}
-
- Statement permissions:
-
- GRANT {ALL | statement_list}
- TO {PUBLIC | name_list}
-
-
- Examples
-
- A. use pubs /* Permissions can be granted on objects in
- the
- ** current database only. */
- grant insert, delete
- on titles
- to mary, sales
-
- B. grant update
- on titles (royalty, advance)
- to public
-
- C. grant create database, create table
- to mary, john
-
- D. grant all on titles
- to public
-
- E. grant all
- to public
-
-
- Options
-
- ALL
- When used to assign object permissions (first syntax format), this keyword
- specifies that all permissions applicable to the specified object are
- granted or revoked. Only the System Administrator can use ALL to assign
- statement permissions (second syntax format), since only the System
- Administrator can grant or revoke CREATE DATABASE permission.
-
- permission_list
- A list of permissions granted. When permissions are granted 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 on columns, the permission list can include
- one or both of the following items: SELECT and UPDATE.
-
- When permissions are granted on stored procedures, the permission list can
- include EXECUTE only.
-
- If more than one permission is listed, separate them with commas.
-
- statement_list
- A list of statements granted. The statement list can include CREATE
- DATABASE (if the user executing the statement is the System
- Administrator), CREATE DEFAULT, CREATE PROCEDURE, CREATE RULE, CREATE
- TABLE, CREATE VIEW, DUMP DATABASE, and DUMP TRANSACTION.
-
- If more than one statement is listed, separate them with commas.
-
- table_name
- The name of a table in the current database. Only one table can be listed
- for each GRANT statement.
-
- 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.
-
- view_name
- The name of a view in the current database. Only one view can be listed
- for each GRANT statement.
-
- stored_procedure_name
- The name of a stored procedure in the current database. Only one stored
- procedure can be listed for each GRANT statement.
-
- PUBLIC
- All users in the public group, which includes all users not explicitly in
- another group.
-
- name_list
- A list of users' database names and/or groupnames, separated by commas.
- These names are stored in the database's sysusers table. Users are added
- with sp_adduser; groups are added with sp_addgroup. New users are made
- members of groups with sp_adduser; group membership is modified with
- sp_changegroup.
-
-
- Comments
-
- You can substitute the word "FROM" for "TO" in the GRANT syntax.
-
- Table summarizes the SQL Server protection system. Permission to use each
- statement defaults to the System Administrator, the Database Owner, the
- table owner, or the default group public. This user can grant or revoke the
- permission if it is transferable. Users at higher levels are either
- automatically assigned the permission or (in the case of Database Owners)
- can get it via the SETUSER statement.
-
- For example, the owner of a database does not automatically receive
- permissions on objects owned by other users. A Database Owner can always
- take any permission by assuming the identity of the object owner with the
- SETUSER statement and then executing the appropriate GRANT or REVOKE
- statements. The System Administrator has permission to do anything at any
- time.
-
- For permissions that default to PUBLIC, no permission is required─that is,
- no GRANT or REVOKE statements must be written.
-
- Table Summary of Permissions System
-
- ╓┌────────────┌──────────┌──────────┌──────────┌───────┌──────────┌───┌──────╖
- Can Be
- Defaults Granted /
- to Revoked
- System Db Owner Table Public Yes No N/A
- Admin Owner
- 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 ─
-
- COMMIT ─ ─ ─ X ─ ─ X
- TRANSACTION
-
- CREATE X ─ ─ ─ X ─ ─
- Can Be
- Defaults Granted /
- to Revoked
- System Db Owner Table Public Yes No N/A
- Admin Owner
- Statement:
- CREATE X ─ ─ ─ X ─ ─
- DATABASE
-
- CREATE ─ X ─ ─ X ─ ─
- DEFAULT
-
- CREATE ─ ─ X ─ ─ X ─
- INDEX
-
- CREATE ─ X ─ ─ X ─ ─
- PROCEDURE
-
- CREATE RULE ─ X ─ ─ X ─ ─
-
- CREATE ─ X ─ (2) X(2) ─ ─
- Can Be
- Defaults Granted /
- to Revoked
- System Db Owner Table Public Yes No N/A
- Admin Owner
- Statement:
- CREATE ─ X ─ (2) X(2) ─ ─
- TABLE
-
- CREATE TRIG ─ ─ X ─ ─ X ─
- GER
-
- CREATE VIEW ─ X ─ ─ X ─ ─
-
- DBCC ─ X ─ ─ ─ ─ X
-
- DELETE ─ ─ X(3) ─ X ─ ─
-
- DISK INIT X ─ ─ ─ ─ X ─
-
- DISK REFIT X ─ ─ ─ ─ X ─
- Can Be
- Defaults Granted /
- to Revoked
- System Db Owner Table Public Yes No N/A
- Admin Owner
- Statement:
- DISK REFIT X ─ ─ ─ ─ X ─
-
- DISK REINIT X ─ ─ ─ ─ X ─
-
- DROP (any ─ ─ ─ ─ ─ X ─
- object)(4)
-
- DUMP ─ X ─ ─ X ─ ─
- DATABASE
-
- DUMP ─ X ─ ─ X ─ ─
- TRANSACTION
-
- EXECUTE (5) ─ ─ ─ ─ X ─ ─
-
- Can Be
- Defaults Granted /
- to Revoked
- System Db Owner Table Public Yes No N/A
- Admin Owner
- Statement:
- GRANT ─ X ─ ─ ─ X ─
-
- GRANT on ─ ─ ─ ─ ─ X ─
- object (4)
-
- INSERT ─ ─ X(3) ─ X ─ ─
-
- KILL X ─ ─ ─ ─ X ─
-
- LOAD ─ X ─ ─ ─ X ─
- DATABASE
-
- LOAD ─ X ─ ─ ─ X ─
- TRANSACTION
- Can Be
- Defaults Granted /
- to Revoked
- System Db Owner Table Public Yes No N/A
- Admin Owner
- Statement:
- TRANSACTION
-
- PRINT ─ ─ ─ X ─ ─ X
-
- RAISERROR ─ ─ ─ X ─ ─ X
-
- READTEXT ─ ─ X(3) ─ X ─ ─
-
- RECONFIGURE X ─ ─ ─ ─ X ─
-
- REVOKE ─ X ─ ─ ─ X ─
-
- REVOKE on ─ ─ ─ ─ ─ X ─
- object (4)
-
- Can Be
- Defaults Granted /
- to Revoked
- System Db Owner Table Public Yes No N/A
- Admin Owner
- Statement:
- ROLLBACK ─ ─ ─ X ─ ─ X
- TRANSACTION
-
- SAVE ─ ─ ─ X ─ ─ X
- TRANSACTION
-
- SELECT ─ ─ X(3) ─ X ─ ─
-
- SET ─ ─ ─ X ─ ─ X
-
- SETUSER ─ X ─ ─ ─ X ─
-
- TRUNCATE ─ ─ X ─ ─ X ─
- TABLE
- Can Be
- Defaults Granted /
- to Revoked
- System Db Owner Table Public Yes No N/A
- Admin Owner
- Statement:
- TABLE
-
- UPDATE ─ ─ X(3) ─ X ─ ─
-
- UPDATE ─ ─ X ─ ─ X ─
- STATISTICS
-
- WRITETEXT ─ ─ X(3) ─ X ─ ─
-
- ────────────────────────────────────────────────────────────────────────────
-
-
-
- (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
-
-
- You can grant or revoke permissions on objects in the current database only.
-
-
- The statement permissions include CREATE DATABASE (which can be granted only
- by the System Administrator), CREATE DEFAULT, CREATE PROCEDURE, CREATE RULE,
- CREATE TABLE, CREATE VIEW, DUMP DATABASE, and DUMP TRANSACTION.
-
- User groups allow you to grant or revoke permissions to more than one user
- with a single statement. Each user can be a member of at most one group.
-
- The Database Owner or System Administrator can add new users with sp_adduser
- and create groups with sp_addgroup.
-
- A guest user can be added with sp_adduser to allow users with login IDs on
- SQL Server to use the database with limited permissions.
-
- By default, all users are a member of the group public if they have not
- explicitly been added to another group. To add a new user to a group other
- than public, use the sp_adduser system procedure. To change an established
- user's group, use the sp_changegroup system procedure.
-
- To remove a user, use the sp_dropuser system procedure. To remove a group,
- use sp_dropgroup.
-
- To display the members of a group, use sp_helpgroup. Its optional parameter
- is the groupname. If you do not give a groupname, sp_helpgroup displays all
- the groups that exist and lists the members of each.
-
- The sp_helprotect system procedure reports permissions on a database object
- or on a user.
-
- See Chapter 2, "System Procedures," for details on the procedures for adding
- and dropping groups and users.
-
- The SQL Server setup program assigns a set of permissions to the default
- group, public.
-
- GRANT and REVOKE statements are order sensitive. The statement that takes
- effect when there is a conflict is the most recently executed one.
-
- Permission to grant and revoke defaults to particular users and cannot be
- transferred.
-
-
- See Also
-
- REVOKE, SETUSER, sp_addgroup, sp_adduser, sp_changedbowner, sp_changegroup,
- sp_dropgroup, sp_dropuser, sp_helpgroup, sp_helprotect, sp_helpuser
-
-
- GROUP BY and HAVING Clauses
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Divide a table into groups. These clauses are used in SELECT statements.
-
-
- Syntax
-
- GROUP BY [ALL] aggregate_free_expression
- [, aggregate_free_expression...]
- [HAVING search_conditions]
-
-
- Examples
-
- A. select type, avg(advance), sum(ytd_sales)
- from titles
- group by type
-
- Example A calculates the average advance and the sum of the sales for each
- type of book.
-
- B. select type, pub_id, avg(advance), sum(ytd_sales)
- from titles
- group by type, pub_id
-
- Example B groups the results by type and then by pub_id within each type.
-
- C. select type, avg(price)
- from titles
- group by type
- having type like 'p%'
-
- Example C displays results for groups having a type beginning with "p" only.
-
-
- D. select pub_id, sum(advance), avg(price)
- from titles
- group by pub_id
- having sum(advance) > $15000
- and avg(price) < $10
- and pub_id > "0800"
-
- Example D displays results for groups matching the conditions in the HAVING
- clause.
-
-
- Options
-
- GROUP BY
- Specifies the groups into which the table will be divided and, if
- aggregate functions are included in the select list, finds a summary value
- for each group. These summary values appear as new columns in the results,
- rather than as new rows. When GROUP BY is used with standard SQL, each
- item in the select list must either have a fixed value in every row in the
- group or be used with aggregate functions that produce a single value for
- each group. TRANSACT-SQL has no such restrictions on the items in the
- select list. Also, TRANSACT-SQL allows you to group by a column name or
- any expression (except a column heading or alias), while with standard SQL
- you can only group by a column name. You can use these aggregate functions
- with GROUP BY (the expression in the syntax is usually a column name):
-
- ╓┌─────────────────────────────────┌─────────────────────────────────────────╖
- Aggregate Function Result
- ────────────────────────────────────────────────────────────────────────────
- SUM([DISTINCT] expression) Returns the total of the [distinct]
- values in the numeric column
-
- Aggregate Function Result
- ────────────────────────────────────────────────────────────────────────────
- AVG([DISTINCT] expression) Returns the average of the [distinct]
- values in the numeric column
-
- COUNT([DISTINCT] expression) Returns the number of [distinct]
- non-null values in the expression
-
- COUNT(*) Returns the number of selected rows
-
- MAX(expression) Returns the highest value in the
- expression
-
- MIN(expression) Returns the lowest value in the
- expression
-
- ────────────────────────────────────────────────────────────────────────────
-
-
-
- A table can be grouped by any combination of columns─that is, groups can
- be nested within each other.
-
- ALL
- Includes all groups in the results, even those that don't have any rows
- that meet the search conditions. For example:
-
- select type, avg(price)
- from titles
- where royalty = 10
- group by all type
-
- ╓┌─┌──────────────────┌──────────────────────────────────────────────────────╖
- ────────────────────────────────────────────────────────────────────────────
- type
- ------------ ----------
- UNDECIDED NULL
- business 17.31
- mod_cook NULL
- popular_comp 20.00
- psychology 14.14
- ────────────────────────────────────────────────────────────────────────────
- psychology 14.14
- trad_cook 17.97
- (6 rows affected)
-
-
- ALL is meaningful only if the SELECT statement includes a WHERE clause.
-
- aggregate_free_expression
- An expression that includes no aggregate functions. TRANSACT-SQL allows
- you to group by such an expression as well as by a column name.
-
- Note that you cannot group by a column heading or alias. This example is
- correct:
-
- select Price=avg(price), Pay=avg(advance), Total=price * $1.15
- from titles
- group by price * $1.15
-
- HAVING
- Sets conditions for the GROUP BY clause, similar to the way that WHERE
- sets conditions for the SELECT clause. HAVING search conditions are
- identical to WHERE search conditions with one exception: WHERE search
- conditions cannot include aggregate functions and HAVING search conditions
- can. Here's an example of a HAVING clause with aggregate functions:
-
- select pub_id, total = sum(ytd_sales)
- from titles
- where ytd_sales is not null
- group by pub_id
- having count(*)>5
-
- There is no limit on the number of conditions that can be included in a
- HAVING clause.
-
- HAVING can be used without GROUP BY.
-
- If there are columns in the select list that neither have aggregate
- functions applied to them nor are included in the query's GROUP BY clause
- (illegal in standard SQL), the meanings of HAVING and WHERE are somewhat
- different. For examples, see the next section, "Comments."
-
-
- Comments
-
- You can use a column name or any expression (except a column heading) after
- GROUP BY.
-
- Null values in the GROUP BY column are put into a single group.
-
- Columns of type text or image are invalid in GROUP BY and HAVING clauses.
-
- Aggregate functions can be used in the select list or in the HAVING clause
- of a SELECT statement. They cannot be used in a WHERE clause.
-
- The aggregate functions, which calculate summary values from the non-null
- values in a column, can be divided into two groups. If they are applied to
- all the rows in a table (producing a single value per function), they are
- called scalar aggregate functions. If they are applied to all the rows that
- have the same value in a specified column or expression with the GROUP BY
- and, optionally, the HAVING clause (producing a value for each group per
- function), they are called vector aggregate functions. In either case, the
- results of the aggregate functions are shown as new columns.
-
- You can nest a vector aggregate function inside a scalar aggregate function.
- (See "Aggregate Functions" for more information and an example.)
-
- In standard SQL, columns in a select list that include aggregate functions
- must either have aggregate functions applied to them or be in the GROUP BY
- list. TRANSACT-SQL has no such restrictions. The first example shows a
- SELECT statement with the standard restrictions; the second one shows the
- same statement with another item (title_id) added to the select list to
- illustrate the difference in displays. The "extra" columns can also be
- referenced in the HAVING clause. For example:
-
- A. select type, avg(price)
- from titles
- group by type
-
- ╓┌─┌──────────────────┌──────────────────────────────────────────────────────╖
- ────────────────────────────────────────────────────────────────────────────
- type
- --------------- -----------
- UNDECIDED NULL
- ────────────────────────────────────────────────────────────────────────────
- UNDECIDED NULL
- business 13.73
- mod_cook 11.49
- popular_comp 21.48
- psychology 13.50
- trad_cook 15.96
- (6 rows affected)
-
-
- B. select type, title_id, avg(price)
- from titles
- group by type
-
- ╓┌─┌───────────────────┌─────────┌───────────────────────────────────────────╖
- ────────────────────────────────────────────────────────────────────────────
- type title_id
- --------------- -------- ---------
- business BU1032 13.73
- business BU1111 13.73
- business BU2075 13.73
- ────────────────────────────────────────────────────────────────────────────
- business BU2075 13.73
- business BU7832 13.73
- mod_cook MC2222 11.49
- mod_cook MC3021 11.49
- UNDECIDED MC3026 NULL
- popular_comp PC1035 21.48
- popular_comp PC8888 21.48
- popular_comp PC9999 21.48
- psychology PS1372 13.50
- psychology PS2091 13.50
- psychology PS2106 13.50
- psychology PS3333 13.50
- psychology PS7777 13.50
- trad_cook TC3218 15.96
- trad_cook TC4203 15.96
- trad_cook TC7777 15.96
- (18 rows affected)
-
-
- If there are columns in the select list that neither have aggregate
- functions applied to them nor are included in the query's GROUP BY clause
- (illegal in standard SQL), the meanings of HAVING and WHERE are somewhat
- different.
-
- In this situation, a WHERE clause restricts the rows that are included in
- the calculation of the aggregate function but does not restrict the rows
- returned by the query. Conversely, a HAVING clause restricts the rows
- returned by the query but does not affect the calculation of the aggregate
- function.
-
- The following examples illustrate the situation:
-
- A. select pub_id, count(pub_id)
- from publishers
-
- ╓┌─┌──────────────────┌──────────────────────────────────────────────────────╖
- ────────────────────────────────────────────────────────────────────────────
- pub_id
- ----------- ---------
- 0736 3
- 0877 3
- ────────────────────────────────────────────────────────────────────────────
- 0877 3
- 1389 3
- (3 rows affected)
-
-
- B. select pub_id, count(pub_id)
- from publishers
- where pub_id < "1000"
-
- ╓┌─┌──────────────────┌──────────────────────────────────────────────────────╖
- ────────────────────────────────────────────────────────────────────────────
- pub_id
- ------------ -----------
- 0736 2
- 0877 2
- 1389 2
-
- (3 rows affected)
-
-
- Since the select list includes the pub_id column, which has no aggregate
- function applied and is not grouped, the WHERE clause returns all the values
- for pub_id, although it counts only rows where pub_id is less than 1000.
-
- C. select pub_id, count(pub_id)
- from publishers
- having pub_id < "1000"
-
- ╓┌─┌──────────────────┌──────────────────────────────────────────────────────╖
- ────────────────────────────────────────────────────────────────────────────
- pub_id
- ------------ ---------
- 0736 3
- 0877 3
-
- (2 rows affected)
-
-
- In example C, the HAVING clause means that only rows where pub_id is less
- than 1000 are returned. All the rows in the table are counted for the
- purposes of calculating the aggregate function.
-
- D. select pub_id, count(pub_id)
- from publishers
- where pub_id < "1000"
- having pub_id < "1000"
-
- ────────────────────────────────────────────────────────────────────────────
- pub_id
- ------------ --------
- 0736 2
- 0877 2
- (2 rows affected)
-
- Since both HAVING and WHERE clauses are included (example D), only rows
- where pub_id is less than 1000 are returned, and only these rows are
- included in the calculation of the COUNT aggregate function.
-
-
- See Also
-
- Aggregate Functions, COMPUTE Clause, Functions, Row Aggregate Functions,
- Search Conditions, SELECT, WHERE Clause
-
-
- Identifiers
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Name database objects─databases, tables, views, columns, indexes, triggers,
- procedures, defaults, rules, and so on.
-
-
- Syntax
-
- Identifiers are 1 to 30 characters long. The first character must be a
- letter or the symbols #, or _. (A table name beginning with # denotes a
- temporary table.)
-
- Characters following the first character can include letters, digits, or the
- symbols #, $, or _. No embedded spaces are allowed in identifiers.
-
- ────────────────────────────────────────────────────────────────────────────
- NOTE
- When an identifier is preceded by the "at" symbol (@), the identifier is
- from 1 to 29 characters long. (For example, variable names and stored
- procedure parameter names are preceded by "@".)
- ────────────────────────────────────────────────────────────────────────────
-
- By default, SQL Server is not sensitive to the case (upper or lower) of
- identifiers and data. If required, a System Administrator can build a
- case-sensitive SQL Server with the bldmastr program. The case of switches
- for utility programs is significant.
-
- Object names need not be unique in a database. However, column names and
- index names must be unique within a table, and other object names must be
- unique for each owner within a database. Database names must be unique on
- SQL Server. You can uniquely identify a table or column by adding other
- names that qualify it─the database name, owner's name, and (for a column)
- the table or view name. Each of these qualifiers is separated from the next
- by a period:
-
- database.owner.table_name.column_name
- database.owner.view_name.column_name
-
- The naming conventions are indicated in the syntax as follows:
-
- [[database.]owner.]table_name
- [[database.]owner.]view_name
-
- The default value for owner is the current user, and the default value for
- database is the current database.
-
- If desired, intermediate elements in a name can be omitted and their
- positions indicated by periods, as long as the system is given enough
- information to identify the object:
-
- database..table_name
- database..view_name
-
-
- Comments
-
- When qualifying a column name and a table name in the same statement, be
- sure to use the same qualifying expressions for each; they are evaluated as
- strings and must match or an error is returned.
-
- Two examples are shown, with different entries for the column name. Example
- B is not correct because the syntax for the column name does not match the
- syntax for the table name.
-
- A. select demo.mary.publishers.city
- from demo.mary.publishers
-
- city
- -----------------------
- Boston
- Washington
- Berkeley
-
- B. select demo.mary.publishers.city
- from demo..publishers
-
- The column prefix "demo.mary.publishers" does not match
- a table name or alias name used in the query.
-
- The names of system datatypes and built-in functions are not reserved words
- and may be used to name database objects.
-
- When you reference an object without qualifying it with the database name
- and owner name, SQL Server tries to find the object in the current database
- among the objects you own. You need not qualify references to your objects
- in the current database, nor do you need to qualify objects owned by the
- Database Owner. However, you must qualify objects owned by other users by
- using the user's name.
-
- You can rename user objects (including user-defined datatypes) with
- sp_rename.
-
-
- See Also
-
- CREATE DATABASE, CREATE DEFAULT, CREATE PROCEDURE, CREATE RULE, CREATE
- TABLE, CREATE TRIGGER, CREATE VIEW, Datatypes, SELECT, sp_rename
-
-
- IF...ELSE
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Impose conditions on the execution of an SQL statement. The SQL statement
- following an IF keyword and its condition executes if the condition is
- satisfied (when the boolean expression returns "true"). The optional ELSE
- keyword introduces an alternate SQL statement that executes when the IF
- condition is not satisfied (when the boolean expression returns "false").
-
-
- Syntax
-
- IF
- boolean_expression
- statement
- [ELSE
- [boolean_expression]
- statement]
-
-
- Examples
-
- A. if 3 > 2
- print "yes"
-
- B. if exists (select zip from authors
- where zip = "94705")
- print "Berkeley author"
-
- C. if (select max(id) from sysobjects) < 50
- print "No user-created objects in this database"
- else
- begin
- print "These are the user-created objects"
- select name, type, id
- from sysobjects
- where id > 50
- end
-
- The IF...ELSE condition tests for the presence of user-created objects (all
- of which have ID numbers that are larger than 50) in a database. Where user
- tables exist, the ELSE clause prints a message and selects their names,
- types, and ID numbers.
-
-
- Options
-
- boolean_expression
- An expression (a column name, a constant, any combination of column names
- and constants connected by arithmetic or bitwise operators, or a subquery)
- that returns "true" or "false." If the boolean expression contains a
- SELECT statement, the SELECT statement must be enclosed in parentheses.
-
-
- Comments
-
- The IF or ELSE condition can affect the performance of only a single SQL
- statement unless statements are grouped into a block between the keywords
- BEGIN and END, as in the last example.
-
- If a SELECT statement is used as part of the boolean expression, it must
- return a single value.
-
- The statement clause could be an EXECUTE statement or any other legal SQL
- statement or statement block.
-
- IF...ELSE constructs can be used either in a stored procedure (where they
- are often used to test for the existence of some parameter) or in ad hoc
- queries as in the earlier examples.
-
- IF tests can be nested, either within another IF or following an ELSE. There
- is no limit on the number of levels of nesting.
-
-
- See Also
-
- BEGIN...END, Control-of-Flow Language, CREATE PROCEDURE, Expressions,
- Subqueries
-
-
- INSERT
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Adds new rows to a table or view.
-
-
- Syntax
-
- INSERT [INTO]
- [[database.]owner.]{table_name | view_name} [(column_list)]
- {VALUES (constant_expression [, constant_expression]...) |
- select_statement}
-
-
- Examples
-
- A. insert titles
- values("BU2222", "Faster!", "business", "1389",
- null, null, null, null, "ok", "06/17/87")
-
- B. insert titles(title_id, title, type, pub_id, notes, pubdate)
- values ('BU1237', 'Get Going!', 'business', '1389',
- 'great', '06/18/86')
-
- C. insert authors
- select *
- from newauthors
- where city = "San Francisco"
-
- D. insert test
- select *
- from test
- where city = "San Francisco"
-
-
- Options
-
- INTO
- An optional keyword.
-
- column_list
- A list of one or more columns to which data is to be added. The columns
- can be in any order, but the incoming data (whether in a VALUES clause or
- a SELECT clause) must be in the same order.
-
- The column_list is only necessary when some, but not all, of the columns
- in the table are to receive data. Enclose the items in column_list in
- parentheses. If no column_list is given, all of the columns in the
- receiving table (in CREATE TABLE order) is assumed.
-
- The column_list determines the order in which values are entered. In the
- first example, the columns in the column_list of the receiving table match
- the columns in the select list of the contributing table. Given a name
- like Euphemia Briggs, Euphemia (the first name) will be stored in the
- au_fname column and Briggs (the last name) will be stored in the au_lname
- column.
-
- In the second example, the order of the columns in the select list is not
- the same as the order of the columns in column_list. Euphemia (the first
- name) is stored in the au_lname column and Briggs (the last name) is
- stored in the au_fname column.
-
- A. insert authors (au_lname, au_fname)
- select au_lname, au_fname
- from newauthors
-
- B. insert authors (au_lname, au_fname)
- select au_fname, au_lname
- from newauthors
-
- VALUES
- Introduces a list of constant expressions.
-
- constant_expression
- Constant or null values for the indicated columns. The values list must be
- enclosed in parentheses and must match the explicit or implicit columns
- list. Enclose char, varchar, and datetime constants in single or double
- quotation marks.
-
- select_statement
- A standard SELECT statement used to retrieve the values to be inserted.
-
-
- Comments
-
- INSERT adds new rows only. Use UPDATE to modify any column values in a row
- you've already inserted.
-
- You can leave out items in the column_list and VALUES list as long as the
- omitted columns are defined to allow null values. See example B.
-
- You can select rows from a table and insert them into the same table in a
- single statement. See example D.
-
- If you have two tables identical in structure except that one has NULL
- fields and some NULL data and the other has NOT NULL fields, this difference
- makes it impossible to insert the data from the NULL table into the NOT NULL
- table with a SELECT statement.
-
- INSERT interacts with the IGNORE_DUP_KEY, IGNORE_DUP_ROW, and ALLOW_DUP_ROW
- options set with the CREATE INDEX statement. (See "CREATE INDEX" for more
- information.)
-
- A rule can be created and bound to a column to restrict the domain of legal
- values that can be entered into it. Rules are created with CREATE RULE and
- bound with the sp_bindrule system procedure.
-
- A default can be created and bound to a column in order to supply a value if
- a user does not explicitly enter one. Defaults are created with CREATE
- DEFAULT and bound with the sp_bindefault system procedure.
-
- You can define a trigger that takes a specified action when an INSERT
- statement is executed on a specified table.
-
- If an INSERT statement violates domain or integrity rules (see "CREATE RULE"
- and "CREATE TRIGGER") or if it is the wrong datatype (see "CREATE TABLE" and
- "Datatypes"), the statement fails, and SQL Server displays an error message.
-
-
-
- Permissions
-
- INSERT permission defaults to the table or view owner, who can transfer it
- to other users.
-
-
- See Also
-
- CREATE DEFAULT, CREATE INDEX, CREATE RULE, CREATE TABLE, CREATE TRIGGER,
- Datatypes, DELETE, SELECT, UPDATE, sp_bindefault, sp_bindrule,
- sp_unbindefault, sp_unbindrule
-
-
- Joins
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Compare two or more tables (or views) by specifying a column from each,
- comparing the values in those columns row by row, and concatenating rows
- that have matching values.
-
-
- Syntax
-
- FROM {table_list | view_list}
- WHERE [NOT] [table_name. | view_name.] column_name
- join_operator [table_name. | view_name.] column_name
- [{AND | OR} [NOT] [table_name. | view_name.] column_name
- join_operator [table_name. | view_name.] column_name...]
-
-
- Examples
-
- A. select au_fname, au_lname, pub_name
- from authors, publishers
- where authors.city = publishers.city
-
- B. select au_fname, au_lname, pub_name
- from authors, publishers
- where authors.city *= publishers.city
-
- C. update titles
- set price = price * 2
- from titles, publishers
- where titles.pub_id = publishers.pub_id
- and publishers.state = "CA"
-
- D. select type, au_lname, au_fname, title
- from authors, titles, titleauthor
- where authors.au_id = titleauthor.au_id
- and titles.title_id = titleauthor.title_id
- order by type
-
- E. select au_fname, au_lname, pub_name
- from authors, publishers
- where authors.city = publishers.city
- and authors.state = publishers.state
-
- F. select au1.au_fname, au1.au_lname, au2.au_fname, au2.au_lname
- from authors au1, authors au2
- where au1.zip = au2.zip
- and (au1.au_lname + au1.au_fname) != (au2.au_lname + au2.au_fname)
-
- Example F finds the authors that live in the same zip code area as other
- authors, eliminating the rows where the author's name matches itself.
-
- G. select titles.type, t1.title_id, t1.price, t2.title_id,
- t2.price
- from titles t1, titles t2
- where t1.type = t2.type
- and t1.price != t2.price
-
-
- Options
-
- FROM table_list, view_list
- The table(s) and view(s) that are being joined. All tables and/or views
- referenced elsewhere in the statement must be included in the FROM clause.
-
- WHERE clause
- The connection between the table(s) and view(s) named in the FROM clause,
- restricting the rows to be included in the results. Qualify column names
- if there is ambiguity about the table or view to which they belong.
- Columns being joined must be join compatible─they must both be numeric or
- both be character columns (or SQL Server must be instructed to treat them
- that way with the CONVERT function).
-
- join_operator
- One of the following:
-
- ╓┌─────────────────────────────────┌─────────────────────────────────────────╖
- Symbol Meaning
- ────────────────────────────────────────────────────────────────────────────
- = Equal to.
-
- > Greater than.
-
- < Less than.
-
- >= Greater than or equal to.
-
- <= Less than or equal to.
-
- != Not equal to.
-
- !> Not greater than.
- Symbol Meaning
- ────────────────────────────────────────────────────────────────────────────
- !> Not greater than.
-
- !< Not less than.
-
- *= Includes all rows from the first table
- that meet the statement's restrictions.
- The second table generates values if
- there is a match on the join condition.
- Otherwise, the second table generates
- null values.
-
- =* Includes in the results all rows from
- the second table that meet the
- statement's restrictions. The first
- table generates values if there is a
- match on the join condition. Otherwise,
- the first table generates null values.
-
- ────────────────────────────────────────────────────────────────────────────
- Symbol Meaning
- ────────────────────────────────────────────────────────────────────────────
- ────────────────────────────────────────────────────────────────────────────
-
-
-
-
- Comments
-
- If a join is to have meaningful results, the columns being joined must have
- similar values─values drawn from the same domain.
-
- You can use more than one join operator either to join more than two tables
- or to join more than two pairs of columns. (See examples D and E.) These
- "join expressions" are almost always connected with AND, although OR is also
- legal.
-
- The expression NOT column_name = column_name is equivalent to column_name !=
- column_name.
-
- Joins based on equality (=) are called equijoins. A natural join is an
- equijoin with only one of the matching columns displayed in the results.
-
- Joins that compare values within the same column of one table are called
- self-joins. To distinguish the two roles in which the table appears, use
- aliases. See example F.
-
- Joins based on a comparison of scalar values (=, > , >= , < , <= , !=, !<,
- !>) are called theta joins.
-
- The "not equal join" is meaningful only with a self-join. See example G.
- Otherwise, it is rarely used, except by mistake. For example, it would be
- easy to think you could find the authors that do not live in a city in which
- a publisher is located with a not equal join:
-
- /* INCORRECT STATEMENT */
- select distinct au_lname, authors.city
- from publishers, authors
- where publishers.city != authors.city
-
- However, this query actually finds the authors who live in a state where
- some publisher is not located, which is all of them. The correct SQL
- statement is as follows:
-
- select distinct au_lname, authors.city
- from publishers, authors
- where authors.city not in
- (select city from publishers
- where authors.city = publishers.city)
-
- Joins that include all rows regardless of whether there is a matching row
- (*= and =*) are called outer joins. See example B. If a table is an inner
- member of an outer join (the second table is the inner table if the join
- operator is *= ; the first table is the inner table if the join operator is
- =*), you can't place any restrictions on it except outer join restrictions.
-
-
- Null values in tables or views being joined will never match each other.
-
- Joins can also be stated as subqueries. (See the section on "Subqueries" for
- more information.)
-
- Joins may not be used for columns containing text or image values.
-
-
- See Also
-
- DELETE, INSERT, SELECT, Subqueries, WHERE Clause, UPDATE, sp_helpjoins
-
-
- KILL
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Kills a process.
-
-
- Syntax
-
- KILL spid
-
-
- Examples
-
- kill 1378
-
-
- Options
-
- spid
- The identification number of the process you want to kill, stored in
- sysprocesses.spid. The sysprocesses table also stores other process
- information, like status (runnable, waiting for a lock, infected, and so
- on), the uid (the ID of the user who executed the statement), program_name
- (the name of the application program), and so on.
-
-
- Comments
-
- You can get a report on the current processes with the sp_who system
- procedure. Here's a typical report:
-
- ╓┌───────┌───────────┌───────────┌───────────┌───────────┌───────┌───────┌───
- ─────────────────────────────────────────────────────────────────────────────
- spid status login_id hostname blk dbname cmd
-
- ---- --------- -------- --------- --- ----- -----
-
- 1 sleeping sa PC Client 0 pubs AWAIT
-
- 2 sleeping sa 0 master NETWO
-
- 3 sleeping sa 0 master CHECK
-
- 4 sleeping karenp PC Client 1 pubs SELEC
-
- 5 runnable karenp PC Client 0 pubs SELEC
-
- (5 rows
- affected)
-
-
-
- The spid column contains process identification numbers used in the
- TRANSACT-SQL KILL statement. The blk column contains the process ID of a
- blocking process, if there is one. A blocking process (which may have an
- exclusive lock) is one that is holding resources that another process needs.
- In the earlier example, process 4 (a SELECT on a table) is blocked by
- process 1 (a BEGIN TRANSACTION followed by an INSERT on the same table).
-
- Server processes cannot be killed. If you try to kill a server process, it
- is not killed and is still listed when you execute the sp_who system
- procedure.
-
- Sleeping processes that are killed don't die until they wake up, so you may
- still see them listed after you execute the KILL statement.
-
- You can get a report on the current locks and the spids of the processes
- holding them with the sp_lock system procedure.
-
- ╓┌─┌──────┌─────────────┌────────────┌──────┌────────────────────────────────╖
- ────────────────────────────────────────────────────────────────────────────
- spid locktype table_id page dbname
- ----- ------------ ----------- ----- --------
- 1 Sh_intent 16003088 0 master
- ────────────────────────────────────────────────────────────────────────────
- 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
-
-
-
- Permissions
-
- KILL permission defaults to the System Administrator and is not
- transferable.
-
-
- See Also
-
- sp_lock, sp_who
-
-
- LOAD DATABASE
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Loads a backup copy of a user database and its transaction log that was
- created with DUMP DATABASE.
-
-
- Syntax
-
- LOAD DATABASE database_name
- FROM dump_device
-
-
- Examples
-
- load database pubs
- from diskdump1
-
- The pubs database has been reloaded from the diskdump1 device.
-
-
- Options
-
- database_name
- The name of the database that has been created to receive data from a
- dumped backup copy. 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.
-
- dump_device
- The logical name of the dump device from which you are loading the
- database. Logical dump device names are available in
- master..sysdevices.name or with the sp_helpdevice system procedure.
-
-
- Comments
-
- The specified database must not be in use during the load. Any data in the
- specified database is replaced by the loaded data.
-
- When the LOAD DATABASE statement is executed for loading from a diskette,
- the console program prompts the operator and waits for responses. If the
- console program is not running or if the operator does not answer its
- questions, the load cannot proceed. For more information, see Chapter 3,
- "Utility Programs."
-
- The recipient database must be large enough for dumped data: it must be
- large enough to hold the highest logical page that was used by the dumped
- database. If the recipient database is too small, SQL Server displays an
- error message that gives the required size.
-
- To recover a database, load the most recent database dump and load all the
- transaction log dumps made since that database dump. The database into which
- you are loading the data is replaced by this reconstruction.
-
- Loading a master database that has been damaged is done with a different
- procedure. See "DISK REFIT," "DISK REINIT," or the SQL Server System
- Administator's Guide for details.
-
- For more information on SQL Server's backup and recovery facilities, see the
- SQL Server System Administrator's Guide.
-
-
- Permissions
-
- LOAD DATABASE permission defaults to the Database Owner and is not
- transferable.
-
-
- See Also
-
- DBCC, DUMP DATABASE, DUMP TRANSACTION, LOAD TRANSACTION, sp_helpdevice
-
-
- LOAD TRANSACTION
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Loads a backup copy of the transaction log. The DUMP TRANSACTION and LOAD
- TRANSACTION statements should be used only when the transaction log is
- stored on a different dump device than the rest of the database.
-
-
- Syntax
-
- LOAD TRANsaction database_name
- FROM dump_device
-
-
- Examples
-
- load transaction pubs
- from diskdump1
-
- The transaction log for the pubs database,
- previously dumped to diskdump1, has been reloaded.
-
-
- Options
-
- database_name
- The name of the destination database.
-
- dump_device
- The logical name of the dump device from which the transaction log is
- being loaded. Logical dump device names are available in
- master..sysdevices.name or with the sp_helpdevice system procedure.
-
-
- Comments
-
- LOAD TRANSACTION loads a backup copy of the transaction log made with DUMP
- TRANSACTION.
-
- To recover a database, load the most recent database dump and then load (in
- order) all the transaction log dumps made since the database dump. The
- database is restored to its state at the time of the last transaction log
- dump.
-
- When the LOAD TRANSACTION statement is executed for loading from a diskette,
- the console program prompts the operator and waits for a response. If the
- console program is not running or if the operator does not answer its
- questions, the load cannot proceed. For more information, see Chapter 3,
- "Utility Programs."
-
- SQL Server checks timestamps on the dumped transaction log to make sure that
- the transactions are being loaded into the correct database and in the
- correct sequence.
-
- Do not attempt to modify syslogs with a DELETE, UPDATE, or INSERT statement.
- Doing so makes it impossible for SQL Server to recover correctly in case of
- a system failure. In addition, an attempt to delete all rows from syslogs
- causes SQL Server to get into an infinite loop that eventually fills up the
- entire database.
-
- For more information on SQL Server's backup and recovery facilities, see the
- SQL Server System Administrator's Guide.
-
-
- Permissions
-
- LOAD DATABASE permission defaults to the Database Owner and is not
- transferable.
-
-
- See Also
-
- DUMP DATABASE, DUMP TRANSACTION, LOAD DATABASE, sp_helpdevice
-
-
- Mathematical Functions
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Return values commonly needed for operations on mathematical data.
- Mathematical function names are not keywords.
-
-
- Syntax
-
- Mathematical functions have the following syntax:
-
- function_name(parameters)
-
- Function names, parameters, and results are listed in the following table:
-
-
-
-
- ╓┌─────────┌────────────────────────────────┌────────────────────────────────╖
- Function Parameters Result
- ────────────────────────────────────────────────────────────────────────────
- ABS (numeric_expr) An absolute value of a given
- expression. The expression can
- be of integer, float, or money
- type. Results are of the same
- type as the numeric expression.
-
- ACOS (float_expr) An angle (in radians) whose
- cosine is the specified
- floating-point value.
-
- Function Parameters Result
- ────────────────────────────────────────────────────────────────────────────
- ASIN (float_expr) An angle (in radians) whose
- sine is the specified
- floating-point value.
-
- ATAN (float_expr) An angle (in radians) whose
- tangent is the specified
- floating-point value.
-
- ATN2 (float_expr1, float_expr2) An angle (in radians) whose
- tangent is (
- float_expr1/float_expr2).
-
- CEILING (numeric_expr) The smallest integer greater
- than or equal to the specified
- value. The expression can be of
- integer, float, or money type.
- Results are of the same type as
- the numeric expression.
- Function Parameters Result
- ────────────────────────────────────────────────────────────────────────────
- the numeric expression.
-
- COS (float_expr) The trigonometric cosine of the
- specified angle (in radians).
-
- COT (float_expr) The trigonometric cotangent of
- the specified angle (in
- radians).
-
- DEGREES (numeric_expr) Degrees converted from radians.
- The expression can be of
- integer, float, or money type.
- Results are of the same type as
- the numeric expression.
-
- EXP (float_expr) The exponential value of the
- specified value.
-
- FLOOR (numeric_expr) The largest integer less than
- Function Parameters Result
- ────────────────────────────────────────────────────────────────────────────
- FLOOR (numeric_expr) The largest integer less than
- or equal to the specified value.
- The expression can be of
- integer, float, or money type.
- Results are of the same type as
- the numeric expression.
-
- LOG (float_expr) The natural logarithm of the
- specified value.
-
- LOG10 (float_expr) The base 10 logarithm of the
- specified value.
-
- PI ( ) The constant value of
- 3.1415926535897936.
-
- POWER (numeric_expr, y) The value of numeric_expr to
- the power of y. The expression
- and y can be of integer, float,
- Function Parameters Result
- ────────────────────────────────────────────────────────────────────────────
- and y can be of integer, float,
- or money type. Results are of
- the same type as numeric_expr.
-
- RADIANS (numeric_expr) Radians converted from degrees.
- The expression can be of
- integer, float, or money type.
- Results are of the same type as
- numeric_expr.
-
- RAND ([int_expr]) A random float number using
- int_expr as the optional seed.
-
- ROUND (numeric_expr, int_expr) A numeric expression rounded
- off to the precision specified
- in int_expr. The expression can
- be of integer, float, or money
- type. Results are of the same
- type as numeric_expr.
- Function Parameters Result
- ────────────────────────────────────────────────────────────────────────────
- type as numeric_expr.
-
- SIGN (numeric_expr) Positive (+1), zero (0), or
- negative (-1). The expression
- can be of integer, float, or
- money type. Results are of the
- same type as numeric_expr.
-
- SIN (float_expr) The trigonometric sine of the
- specified angle (measured in
- radians).
-
- SQRT (float_expr) The square root of the
- specified value.
-
- TAN (float_expr) The trigonometric tangent of
- the specified angle (measured
- in radians).
-
- Function Parameters Result
- ────────────────────────────────────────────────────────────────────────────
- ────────────────────────────────────────────────────────────────────────────
-
-
-
-
- Examples
-
- Statement Result
-
- A. select floor(123.45) 123.000000
- select floor(-123.45) -124.000000
- select floor($123.45) $123.00
-
- B. select ceiling(123.45) 124.000000
- select ceiling(-123.45) -123.000000
- select ceiling($123.45) $124.00
-
- C. select round(123.4545, 2) 123.450000
- select round(123.45, -2) 100.000000
-
- The ROUND function always returns a value even if the length is illegal. If
- the specified length is positive and longer than the digits after the
- decimal point, 0 is added after the fraction digits.
-
- If the length is negative and larger than or equal to the digits before the
- decimal point, ROUND returns 0.00.
-
- The last digit in a floating-point number is always an estimate:
-
- round(123.9995, 3) = 123.999
-
- while
-
- round(123.9996, 3) = 124.000
-
-
- Comments
-
- Error traps are provided to handle domain or range errors of these
- functions. A user can set the options ARITHABORT or ARITHIGNORE, which
- respectively abort the query or return NULL when a domain error occurs. No
- warning message is displayed. If neither of these options is set, the system
- returns NULL and prints a warning message after the query is executed.
-
-
- See Also
-
- Conversion Function, Functions, SET, String Functions, Text/Image Functions
-
-
-
-
-
-
- Null Values
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Mark columns having an unknown value (as opposed to those that have 0 or a
- blank as a value). NULL allows you to distinguish between a deliberate entry
- of zero (for numerical columns) or a blank (for character columns) and a
- nonentry (NULL for both numerical and character columns).
-
-
- Syntax
-
- In CREATE TABLE statements:
-
- column_name datatype [NULL | NOT NULL]
-
- In SELECT statements:
-
- WHERE column_name IS [NOT] NULL
-
- In INSERT statements:
-
- VALUES({constant | NULL} [, {constant | NULL}]...)
-
- In UPDATE statements:
-
- SET column_name = {expression | NULL}
- [, column_name = {expression | NULL}...]
-
- The ISNULL built-in function:
-
- isnull(expression, value)
-
-
- Examples
-
- A. create table test
- (t1 char(10) null,
- t2 char(10) not null)
- insert test
- values (null, "stuff")
- insert test (t2)
- values ("stuff")
-
- Because column t1 of table test is defined as accepting NULL in the CREATE
- TABLE statement (example A), these two INSERT statements are equivalent to
- each other. The user can explicitly insert NULL or allow the system to do
- it. NULL is inserted in the t1 column whenever the user inserts rows but
- does not specify a value for the column.
-
- B. select isnull(t1, "unknown")
- from test
-
- Example B selects all the rows from test and displays all the null values in
- column t1 with the value unknown.
-
- C. update titles
- set advance = null
- where title_id = "TC3218"
-
- D. select title_id, advance
- from titles
- where advance < $5000 or advance is null
-
-
- Options
-
- NULL
- Indicates that the user (or a program) has made no entry. The value is
- unknown rather than blank or 0. In CREATE TABLE statements, NULL after a
- column name means that if there is no default for this column, SQL Server
- assigns a null value whenever the user does not make an entry for this
- column at insert time.
-
- In SELECT statements, use IS [NOT] NULL to retrieve null values (allowed
- only if the column has been defined to allow null values in the CREATE
- TABLE statement).
-
- An expression with a bitwise or arithmetic operator evaluates to NULL if
- any of the operands is null.
-
- NOT NULL
- Is the default in CREATE TABLE statements. It can also be used in SELECT
- statements to retrieve all values except those that are NULL.
-
-
- Comments
-
- Only columns for which NULL was specified in the CREATE TABLE statement, and
- into which you have explicitly entered NULL or into which no data has been
- entered contain null values. (Avoid entering the character string "NULL" as
- data for a character column. Use "N/A" or "none" instead. When you wish to
- enter the value NULL explicitly, do not use single or double quotation
- marks.)
-
- NOT NULL (the default) in a CREATE TABLE statement means that NULL is not a
- legal value for this column. If there is no default for this column, an
- error message will be produced whenever the user does not make an entry for
- this column at insert time. In addition, the user cannot assign NULL as a
- value with an INSERT or UPDATE statement.
-
- Columns added to an existing table with the ALTER TABLE statement (except
- bit columns, which cannot be added to an existing table) must allow NULL
- because the initial values of the new columns in existing rows are set to
- NULL.
-
- When you create NULL columns with certain datatypes, SQL Server
- automatically converts them to a different internal datatype to allow the
- storage of null values. SQL Server does not inform the user of the type
- change, and the user should be concerned about it only if querying the
- system tables.
-
- The char datatype is automatically converted to varchar; binary to
- varbinary; datetime to datetimn; float to floatn; int, smallint, and tinyint
- to intn; and money to moneyn.
-
- An expression with an arithmetic or bitwise operator evaluates to NULL if
- any of the operands is NULL. For example, 1 + column1 evaluates to NULL if
- column1 is NULL.
-
- An expression with a comparison operator evaluates to false if any of the
- operands is NULL. This means that null values will never match another value
- (not even another NULL) when used with a comparison operator. Use IS NULL to
- find null values in queries (when the columns being searched are defined as
- allowing null values). If you try to find null values in columns defined as
- NOT NULL, SQL Server generates an error message.
-
- The result of a subquery that returns no values is NULL.
-
- The result of a divide-by-zero is NULL.
-
- Aggregate functions ignore null values, except COUNT(*), which includes
- them. For example, in the calculation avg(advance), null values in the
- advance column are not counted, either in calculating the total amount or
- the number of values.
-
- When the GROUP BY clause is used, null values form their own group.
-
- With ORDER BY, null values come before all others.
-
- In a SELECT clause with the DISTINCT keyword, which selects unique rows
- only, null values are considered duplicates of each other. Only one NULL is
- selected, no matter how many are encountered.
-
- Null values are never joined, not even to other null values.
-
- If you have two tables identical in structure except that one has NULL
- fields and some null values, while the other has NOT NULL fields, this
- difference makes it impossible to insert the data from the NULL table into
- the NOT NULL table with SELECT.
-
- If a subquery returns NULL, the statement results will not be what you
- expect.
-
- If you specify NOT NULL when you create a column and do not create a default
- for it, an error message is produced whenever a user fails to make an entry
- in that column. The following table illustrates the relationship between the
- existence of a default and the definition of a column as NULL or NOT NULL.
- The entries in the table show the result:
-
- No entry
- ────────────────────────────────────────────────────────────────────────────
- NULL null default null null
-
- NOT NULL error default error error
-
- ────────────────────────────────────────────────────────────────────────────
-
-
- For information on NULL as the default parameter for a procedure, see
- "CREATE PROCEDURE."
-
- The sp_help system procedure reports the nulltype of a column (whether or
- not the column accepts null values).
-
-
- See Also
-
- Aggregate Functions, CREATE PROCEDURE, Expressions, GROUP BY and HAVING
- Clauses, INSERT, Search Conditions, SELECT, Subqueries, UPDATE, sp_help
-
-
- ORDER BY Clause
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Returns query results in the specified column(s) in sorted order.
-
-
- Syntax
-
- [ORDER BY {[table_name. | view_name.] column_name |
- select_list_number | expression} [ASC | DESC]
- [,{[table_name. | view_name.] column_name |
- select_list_number | expression} [ASC | DESC]]...]
-
-
- Examples
-
- A. select title, type, price
- from titles
- where price > $9.99
- order by title
-
- B. select type, price, advance
- from titles
- order by type desc
- compute avg(price), avg(advance) by type
-
-
- Options
-
- ORDER BY
- Sorts the results by columns. You can sort up to 16 columns. In
- TRANSACT-SQL, you can use this statement for items that do not appear in
- the select list. You can sort by a column heading, a column name, an
- expression, or a number representing the position of the item in the
- select list (the select_list_number).
-
- ASC
- Indicates that results are to be sorted in ascending order. ASC is the
- default; if you do not specify ASC or DESC, ASC is assumed.
-
- DESC
- Indicates that results are to be sorted in descending order.
-
-
- Comments
-
- ORDER BY cannot be specified on text or image datatype columns.
-
- With ORDER BY, null values come before all others.
-
- If you use COMPUTE BY, you must also use an ORDER BY clause. The columns
- listed after COMPUTE BY must be identical to or a subset of those listed
- after ORDER BY, and must be in the same left-to-right order, start with the
- same expression, and not skip any expressions. For example, say the ORDER BY
- clause is
-
- order by a, b, c
-
- In that case, the COMPUTE BY clause can be any (or all) of these:
-
- compute by a, b, c
- compute by a, b
- compute by a
-
- You can use a column name, an expression, or a column heading (or alias) in
- the ORDER BY clause.
-
- The COMPUTE keyword can be used without BY to generate grand totals, grand
- counts, and so on. ORDER BY is optional if you use the COMPUTE keyword
- without BY.
-
- Subqueries cannot include an ORDER BY clause, a COMPUTE clause, or the INTO
- keyword.
-
- View definitions cannot include an ORDER BY clause, a COMPUTE CLAUSE, or the
- INTO keyword.
-
- The ORDER BY clause cannot be specified on columns containing text or image
- datatypes.
-
-
- See Also
-
- COMPUTE Clause, Expressions, GROUP BY and HAVING Clauses, SELECT, WHERE
- Clause
-
-
- Parameters
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Values supplied to a stored procedure. Parameters are defined (optionally)
- when a stored procedure is created, and their values are supplied by the
- user when a procedure is executed.
-
-
- Syntax
-
- CREATE PROCEDURE [[database.]owner]procedure_name[;number]
- [[(]@parameter_name datatype [= default]
- [,@parameter_name datatype [= default]]...[)]]
- [WITH RECOMPILE]
- AS SQL_statements
-
- [EXECute] procedure_name [value [, value]...] or
-
- [EXECute] procedure_name [@parameter_name = value
- [,@parameter_name = value]...]
-
-
- Examples
-
- create procedure showtype @tabname varchar(18), @colname varchar(18)
- as
- select syscolumns.name, syscolumns.length, systypes.name
- from syscolumns, systypes, sysobjects
- where sysobjects.id = syscolumns.id
- and @tabname = sysobjects.name
- and @colname = syscolumns.name
- and syscolumns.type = systypes.type
-
- exec showtype sales, qty
-
-
- Options
-
- @parameter_name
- The name of the parameter or parameter to the stored procedure. Parameter
- names must be preceded by the "at" symbol (@) and conform to the rules for
- identifiers.
-
- datatype
- The datatype of the parameter. A length in parentheses after the datatype
- entry is required for some datatypes. See the "Datatypes" section for a
- list of SQL-Server-supplied datatypes and their syntax.
-
- default
- A default parameter value for the procedure. If a default is defined, a
- user can execute the procedure without giving a parameter. The default
- must be a constant. It can include the wildcard characters (%, _, [ ], and
- [^]) if the procedure uses the parameter name with the LIKE keyword.
-
- The default can be NULL. The procedure definition can specify that some
- action be taken if the parameter value is NULL. See "CREATE PROCEDURE" for
- examples.
-
-
- Comments
-
- Parameter names are optional in CREATE PROCEDURE statements; a procedure
- need not take any parameters.
-
- Parameter names are local to the procedure; that is, the same parameter
- names can be used in other procedures.
-
- Parameter names can take the place of constants only; they cannot be used in
- place of table names, column names, or the names of other database objects.
- However, the value of a parameter given at execution time can be an object
- name. See "EXECUTE" for examples.
-
- Enclose any parameter value that includes punctuation (such as an object
- name qualified by a database name or owner name) in single or double
- quotation marks.
-
- Parameters cannot be of text or image datatype.
-
-
- See Also
-
- CREATE PROCEDURE, DECLARE, Datatypes, DROP PROCEDURE, EXECUTE, Variables
- (Local and Global)
-
-
- PRINT
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Prints a user-defined message on the user's screen.
-
-
- Syntax
-
- PRINT {"any ASCII text" | local variable |
- @version global variable}
-
-
- Examples
-
- A. if exists (select zip from authors
- where zip = '94705')
- print "Berkeley author"
-
- B. declare @msg char(50)
- select @msg = "What's up, doc?"
- print @msg
-
- What's up, doc?
-
- C. declare @tabname varchar(30)
- select @tabname = "titles"
- declare @username varchar(30)
- select @username = "ezekiel"
- declare @message varchar(255)
- select @message = "The table '" + @tabname + "' is not
- owned
- by the user '" + @username + ".'"
- print @message
-
- The table 'titles' is not owned
- by the user 'ezekiel.'
-
-
- Comments
-
- The message can be up to 255 characters long.
-
- The local variable must be of type char or varchar and must be declared
- within the batch or procedure in which it is used.
-
- The global variable must be of type char or varchar or automatically
- convertible to these types, such as @VERSION.
-
- You can generate a "formatted" message with more than one parameter by using
- the concatenation operator, as shown in example C.
-
-
- See Also
-
- DECLARE, RAISERROR, Variables (Local and Global)
-
-
- RAISERROR
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Prints a user-defined error message on the user's screen and sets a system
- flag to record that an error has occurred.
-
-
- Syntax
-
- RAISERROR number {"text of message" | local variable}
-
-
- Examples
-
- create procedure showtable_sp @tabname varchar(18)
- as
- if @tabname is null
- begin
- raiserror 99999 "You must give a table name"
- end
- else
- begin
- select sysobjects.name, type, crdate, indid
- from sysindexes, sysobjects
- where sysobjects.name = @tabname
- and sysobjects.id = sysindexes.id
- end
-
-
- Comments
-
- The error message can be up to 255 characters long.
-
- Error numbers for user-defined error messages must be greater than 20,000.
-
- When RAISERROR is executed, the error number is placed in the global
- variable @ERROR, which stores the error number most recently generated by
- the system.
-
- The local variable must be of type char or varchar, and must be declared
- within the batch or procedure in which it is used.
-
- Use RAISERROR instead of PRINT when you want an error number stored in
- @ERROR.
-
-
- See Also
-
- DECLARE, PRINT, Variables (Local and Global)
-
-
- READTEXT
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Reads text and image values, starting from a specified offset and reading a
- specified number of bytes.
-
-
- Syntax
-
- READTEXT [[database.]owner.]table_name.column_name
- text_ptr offset size [HOLDLOCK]
-
-
- Examples
-
- declare @val varbinary(30)
- select @val = textptr(blurb) from texttest
- where title_id = "BU7832"
- readtext texttest.blurb @val 1 5
-
- This example selects the second through sixth characters of the blurb column
- from the texttest table.
-
-
- Options
-
- table_name.column_name
- The table name and column name. The table name must be included, but the
- database name and owner name are optional.
-
- text_ptr
- A valid text pointer.
-
- offset
- The number of bytes to skip before starting to read the text or image
- data.
-
- size
- The number of bytes of data to read. If size = 0, 4K bytes of data are
- read.
-
- HOLDLOCK
- Causes the text value to be locked for reads until the end of the
- transaction. Other users can read the value, but they cannot modify it.
-
-
- Comments
-
- Since the TEXTPTR function returns a long binary string, it is best to
- declare a local variable to hold the text pointer and then use the variable
- with READTEXT.
-
- The HOLDLOCK option causes the text value to be locked for reads until the
- end of the transaction. Other users can read the value, but they cannot
- modify it.
-
- The TEXTPTR function returns a pointer to the text or image column in the
- specified row or to the text or image column in the last row returned by the
- query if more than one row is returned.
-
- The value in the global variable @TEXTSIZE, which is the limit on the number
- of bytes of data to be returned, supersedes the size specified for READTEXT
- if it is less than the specified size for READTEXT. Use SET TEXTSIZE to
- change this limit.
-
-
- Permissions
-
- Users must have select permission on the table to use READTEXT.
-
-
- See Also
-
- Text/Image Datatypes, Text/Image Functions, WRITETEXT
-
-
- RECONFIGURE
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Part of the procedure that sets configuration options, which control various
- aspects of SQL Server's memory allocation and performance. The System
- Administrator uses RECONFIGURE.
-
-
- Syntax
-
- RECONFIGURE [WITH OVERRIDE]
-
-
- Examples
-
- reconfigure
-
- The dynamic values in the master..sysconfigures system table are put into
- effect immediately. The static values take effect the next time SQL Server
- is started.
-
-
- Options
-
- WITH OVERRIDE
- Instructs SQL Server to accept the values for system variables supplied by
- the user (with sp_configure). User-supplied values that are unacceptable
- to SQL Server cause the RECONFIGURE statement to abort.
-
- If the user supplies values that SQL Server cannot accept, an error
- message telling the user to re-execute sp_configure is displayed.
-
- The WITH OVERRIDE clause must always be used when you set the allow
- updates variable to 1.
-
-
- Comments
-
- To display a list of the configuration options with their current values and
- the range of permissible values, execute sp_configure without parameters.
- The report looks like this:
-
- ╓┌───────┌─────────────────────┌────────┌────────┌─────────────────────┌─────
- ─────────────────────────────────────────────────────────────────────────────
- name minimum maximum config_value run_val
-
- ----------------- ------- ------- ------------ -------
-
- recovery interval 1 32767 4 3
-
- allow updates 0 1 0 0
-
- user connections * 5 35 0 25
-
- memory 1000 14000 0 1700
-
- open databases 5 100 0 10
- ─────────────────────────────────────────────────────────────────────────────
- open databases 5 100 0 10
-
- locks 5000 50000 0 5000
-
- open objects 100 10000 0 500
-
- procedure cache 1 99 0 20
-
- fill factor 0 100 0 0
-
- time slice 50 1000 0 100
-
- database size 2 10000 0 2
-
- media retention 0 365 0 0
-
- recovery flags 0 1 0 0
-
- serial number 1 999999 0 0
-
- ─────────────────────────────────────────────────────────────────────────────
- (14 rows affected)
-
- * The SQL Server
- maximum is 250; the
- effective number is
- based upon your
- system configuration
- and is stored in the
- global variable
- @MAX_CONNECTIONS.
-
-
-
- The config_value column of the report contains the value to which the
- configuration option was set with sp_configure (the value in
- sysconfigures.value).
-
- The run_value column contains the value SQL Server is using. This value
- changes for dynamic configuration options (recovery interval and allow
- updates) after you run the RECONFIGURE statement. This value changes for
- static configuration options after you shut down and restart SQL Server.
- This is the value in syscurconfigs.value.
-
- To change a configuration option, execute sp_configure with its parameters
- optname (the name of the configuration option) and optvalue (a legal value).
- Then execute the RECONFIGURE statement. (Include the WITH OVERRIDE clause to
- turn the allow updates variable on or to override a warning that the value
- you have specified is considered less than optimal by SQL Server.)
-
- If you have changed any of the static configuration options (all of them
- except allow updates and recovery interval), you must restart SQL Server
- before the new values take effect.
-
- SQL Server checks to make sure that the new values in sysconfigures are
- acceptable (SQL Server will run) and reasonable (SQL Server will run
- optimally).
-
- The values in sysconfigures.value and in the config_value column of the
- sp_configure report do not necessarily reflect the values currently being
- used by SQL Server for two reasons. First, the System Administrator may have
- updated sysconfigures.value but not executed the RECONFIGURE statement
- and/or not restarted SQL Server. Second, the default for most values in
- sysconfigures is 0, which indicates that SQL Server calculates optimum
- values for that parameter.
-
- Here are the contents of sysconfigures:
-
- ╓┌───────┌───────┌──────┌────────────────────────────────────────────────────
- ─────────────────────────────────────────────────────────────────────────────
- config value comment
-
- ------ ----- ------------------------------------------------------
-
- 101 4 Maximum recovery interval in minutes
-
- 102 0 Allow updates to system tables
-
- 103 0 Number of user connections allowed
-
- 104 0 Size of available physical memory in 2K pages
-
- ─────────────────────────────────────────────────────────────────────────────
- 105 0 Number of open databases allowed among all users
-
- 106 0 Number of locks for all users
-
- 107 0 Number of open database objects
-
- 108 0 Percentage of remaining memory used for procedure
- cache
-
- 109 0 Default fill factor percentage
-
- 110 0 Average time slice per process in milliseconds
-
- 111 0 Default database size in megabytes
-
- 112 0 Backup media retention period in days
-
- 113 0 Recovery flags
-
- ─────────────────────────────────────────────────────────────────────────────
- 114 0 Serial Number
-
-
-
- The value in the value column is the value that has been set with
- sp_configure. The value in the status column is 1 if the configuration
- option is dynamic and 0 if it is not.
-
- The overhead of each additional user connection (103) is 34K.
-
- The total size of available memory (104) must be changed when you add or
- remove memory boards. The total available physical memory minus the memory
- required for the operating system is available for SQL Server.
-
- The percentage of memory allocated to the procedure cache (108) and, by
- implication, to the buffer cache, can affect performance noticeably.
-
- You may have to change the database size (111) if the size of your model
- database increases substantially (for example, if you add a lot of your own
- stored procedures to model). You may want to change the default database
- size if most of your databases are larger than the value in syscurconfigs,
- which is 2 megabytes.
-
- For more information, see the SQL Server System Administrator's Guide.
-
-
- Permissions
-
- RECONFIGURE permission defaults to the System Administrator and is not
- transferable.
-
-
- See Also
-
- sp_configure
-
-
- RETURN
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Exits unconditionally from a query or procedure. Statements following RETURN
- are not executed.
-
-
- Syntax
-
- RETURN
-
-
- Examples
-
- create procedure findrules @nm varchar(30) = null as
- if @nm is null
- begin
- print "You must give a user name"
- return
- end
- else
- begin
- select sysobjects.name, sysobjects.id, sysobjects.uid
- from sysobjects, master..syslogins
- where master..syslogins.name = @nm
- and sysobjects.uid = master..syslogins.suid
- and sysobjects.type = "R"
- end
-
- If no username is given as a parameter, the RETURN keyword causes the
- procedure to exit after a message has been sent to the user's screen. If a
- username is given, the names of the rules created by this user in the
- current database are retrieved from the appropriate system tables.
-
-
- Comments
-
- The RETURN keyword can be used at any point where you want to exit from a
- procedure.
-
- RETURN is immediate and complete: statements after RETURN are not executed.
-
-
-
- See Also
-
- BEGIN...END, IF...ELSE, WHILE
-
-
- REVOKE
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Revokes permissions from users.
-
-
- Syntax
-
- Object permissions:
-
- REVOKE {ALL | permission_list}
- ON {table_name [(column_list)] | view_name [(column_list)] |
- stored_procedure_name}
- FROM {PUBLIC | name_list}
-
- Statement permissions:
-
- REVOKE {ALL | statement_list}
- FROM {PUBLIC | name_list}
-
-
- Examples
-
- A. use pubs /* Permissions can be revoked on objects
- ** in the current database only. */
- revoke insert, delete
- on titles
- from mary, sales
-
- B. revoke update
- on titles (royalty, advance)
- from public
-
- C. revoke create database, create table
- from mary, john
-
- D. revoke all
- from mary
-
- E. revoke all
- on titles
- from mary
-
-
- Options
-
- ALL
- When used to revoke object permissions (first syntax format), this keyword
- specifies that all permissions applicable to the specified object are
- revoked. When used to revoke statement permissions (second syntax format),
- this keyword specifies that all statement permissions are revoked. (CREATE
- DATABASE permission can be granted only by the System Administrator.)
-
- permission_list
- A list of granted permissions. When permissions are revoked on a table or
- a view, the permission list can include one or more of the following:
- SELECT, INSERT, DELETE, and UPDATE. When permissions are revoked on
- columns, the permission list can include one or both of the following:
- SELECT and UPDATE. When permissions are revoked on stored procedures, the
- permission list can include EXECUTE only. If more than one permission is
- listed, separate them with commas.
-
- statement_list
- A list of granted statements. The statement list can include CREATE
- DATABASE (which can be granted only by System Administrator), CREATE
- DEFAULT, CREATE PROCEDURE, CREATE RULE, CREATE TABLE, CREATE VIEW, DUMP
- DATABASE, and DUMP TRANSACTION. If more than one statement is listed,
- separate them with commas.
-
- table_name
- The name of the table in the current database. Only one object can be
- listed for each REVOKE statement.
-
- 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.
-
- view_name
- The name of the view in the current database. Only one object can be
- listed for each REVOKE statement.
-
- stored_procedure_name
- The name of the stored procedure in the current database. Only one object
- can be listed for each REVOKE statement.
-
- PUBLIC
- All users.
-
- name_list
- A list of usernames and/or groupnames, separated by commas.
-
-
- Comments
-
- Permissions can be granted or revoked on objects in the current database
- only.
-
- You can substitute the word "TO" for the word "FROM" in the REVOKE statement
- if you wish.
-
- User groups allow you to grant or revoke permissions to more than one user
- at a time. Each user can be a member of only one group.
-
- Groups are created with the sp_addgroup system procedure, which takes the
- groupname as its parameter.
-
- New users can be added to a group (other than public, the default group)
- with the sp_adduser system procedure. Users' groups can be changed with
- sp_changegroup.
-
- To remove a group, use the sp_dropgroup system procedure. Its parameter is
- the groupname.
-
- To display the members of a group, use the sp_helpgroup system procedure.
- Its optional parameter is the groupname. If you do not give a groupname,
- sp_helpgroup displays all the groups that exist and lists the members of
- each.
-
- GRANT and REVOKE statements are order sensitive. The statement that takes
- effect when there is a conflict is the most recently executed one.
-
-
- See Also
-
- GRANT, SETUSER, sp_addgroup, sp_adduser, sp_changedbowner, sp_changegroup,
- sp_dropgroup, sp_dropuser, sp_helpgroup, sp_helprotect, sp_helpuser
-
-
- ROLLBACK TRANSACTION
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Rolls back a user-specified transaction to the last savepoint inside a
- transaction or to the beginning of a transaction.
-
-
- Syntax
-
- ROLLBACK TRANsaction [transaction_name | savepoint_name]
-
-
- Examples
-
- begin transaction royaltychange
- /* A user sets out to change the royalty split for the
- two authors of The Gourmet Microwave. Since the
- database would be inconsistent between the two updates,
- they must be grouped into a user-defined transaction. */
-
- update titleauthor
- set royaltyper = 65
- from titleauthor, titles
- where royaltyper = 75
- and titleauthor.title_id = titles.title_id
- and title = "The Gourmet Microwave"
-
- update titleauthor
- set royaltyper = 35
- from titleauthor, titles
- where royaltyper = 25
- and titleauthor.title_id = titles.title_id
- and title = "The Gourmet Microwave"
-
- save transaction percentchanged
- /* After having updated the royaltyper entries
- for the two authors, the user inserts the savepoint
- percentchanged, and then experiments to see how
- a 10% increase in the book's price would affect the
- authors' royalty earnings. */
-
- update titles
- set price = price * $1.1
- where title = "The Gourmet Microwave"
-
- select (price * royalty * ytd_sales) * royaltyper
- from titles, titleauthor
- where title = "The Gourmet Microwave"
- and titles.title_id = titleauthor.title_id
- /* The transaction is rolled back to the savepoint
- with the ROLLBACK TRANSACTION statement.*/
-
- rollback transaction percentchanged
-
- commit transaction
-
- /* End of royaltychange. */
-
-
- Options
-
- transaction_name
- The name assigned to the transaction. It must conform to the rules for
- identifiers.
-
- savepoint_name
- The name assigned to the savepoint. It must conform to the rules for
- identifiers.
-
-
- Comments
-
- Use the form ROLLBACK TRANSACTION transaction_name. When you rollback a
- transaction, all of the transaction's statements or procedures are undone.
- It is as though you had never performed any of those statements on
- procedures.
-
- If no savepoint_name or transaction_name is given with the ROLLBACK
- TRANSACTION statement, the transaction is rolled back to the previous BEGIN
- TRANSACTION.
-
- A savepoint is a marker set by a user within a transaction. It is used to
- cancel part of a transaction with the statement ROLLBACK TRANSACTION
- savepoint_name. All of the statements or procedures between the savepoint
- and the ROLLBACK TRANSACTION are undone. After a transaction is rolled back
- to a savepoint, it must proceed to completion (with more SQL statements if
- desired and a COMMIT TRANSACTION statement), or it must be canceled
- altogether (by rolling it back to its beginning).
-
- There is no limit on the number of savepoints within a transaction.
-
- The ROLLBACK TRANSACTION statement must appear within a transaction; you
- can't roll back a transaction after COMMIT TRANSACTION has been entered.
-
- Define a transaction by enclosing SQL statements and/or stored procedures
- with BEGIN TRANSACTION and COMMIT TRANSACTION.
-
- Within a transaction, duplicate savepoint_names are allowed, but only the
- first instance of a savepoint_name is used.
-
-
- Permissions
-
- ROLLBACK TRANSACTION permission defaults to public; no permission is
- required to use it.
-
-
- See Also
-
- BEGIN TRANSACTION, COMMIT TRANSACTION, SAVE TRANSACTION
-
-
- Row Aggregate Functions
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Generate summary values that appear as additional rows in the query results
- (unlike the aggregate function results, which appear as new columns). They
- allow you to see detail and summary rows in one set of results. Row
- aggregate functions (SUM, AVG, MIN, MAX, and COUNT) are used in a SELECT
- statement with the COMPUTE clause. You can calculate summary values for
- subgroups, and you can calculate more than one aggregate function for the
- same group. COMPUTE and the row aggregate functions are SQL Server
- enhancements to standard SQL.
-
-
- Syntax
-
- COMPUTE row_aggregate(column_name) [, row_aggregate(column_name)...]
- [BY column_name [, column_name]...]
-
-
- Examples
-
- select type, price
- from titles
- where price > $10
- and type like "%cook"
- order by type, price
- compute sum(price) by type
-
- ╓┌─┌──────────────────┌──────────────────────────────────────────────────────╖
- ────────────────────────────────────────────────────────────────────────────
- type price
- ----------- ----------
- mod_cook 19.99
- sum
- ----------
- 19.99
- type price
- ------------ ----------
- ────────────────────────────────────────────────────────────────────────────
- ------------ ----------
- trad_cook 11.95
- trad_cook 14.99
- trad_cook 20.95
- sum
- ----------
- 47.89
- (6 rows affected)
-
-
- This example calculates the sum of the price of each type of cookbook over
- $10. (See "COMPUTE Clause" for more examples and information.)
-
-
- Options
-
- row_aggregate
- One of the following:
-
- ╓┌─────────────────────────────────┌─────────────────────────────────────────╖
- Aggregate Function Result
- ────────────────────────────────────────────────────────────────────────────
- SUM([DISTINCT] expression) Returns the total of the [distinct]
- values in the numeric column
-
- AVG([DISTINCT] expression) Returns the average of the [distinct]
- values in the numeric column
-
- COUNT(*) Returns the number of non-null values in
- the column
-
- MAX(expression) Returns the highest value in the column
-
- MIN(expression) Returns the lowest value in the column
-
- ────────────────────────────────────────────────────────────────────────────
-
-
-
- column_name
- The name of a column. It must be enclosed in parentheses. Only numeric
- columns can be used with SUM and AVG. One COMPUTE clause can apply the
- same function to several columns. When using more than one function, use
- more than one COMPUTE clause.
-
- BY
- Indicates that row aggregate function values are to be calculated for
- subgroups. Whenever the value of the BY item changes, row aggregate
- function values are generated. If you use BY, you must use ORDER BY.
- Listing more than one item after BY breaks a group into subgroups and
- applies a function at each level of grouping.
-
-
- Comments
-
- The row aggregate functions make it possible to retrieve detail and summary
- rows with one command. The aggregate functions, on the other hand,
- ordinarily produce a single value for all the selected rows in the table or
- for each group, and these summary values are shown as new columns. The
- following examples illustrate the differences:
-
- A. select type, sum(price), sum(advance)
- from titles
- where type like "%cook"
- group by type
-
- ╓┌───┌─────────────────────────────────────────┌─────────────┌───────────────╖
- ────────────────────────────────────────────────────────────────────────────
- type
- ---------- ---------- ------------
- mod_cook 22.98 15,000.00
- trad_cook 47.89 19,000.00
- (2 rows affected)
- B. select type, price, advance
- from titles
- where type like "%cook"
- order by type
- compute sum(price), sum(advance) by type
- type price advance
- ---------- ------------ ------------
- mod_cook 2.99 15,000.00
- mod_cook 19.99 0.00
- sum sum
- ────────────────────────────────────────────────────────────────────────────
- sum sum
- ------------ ------------
- 22.98 15,000.00
- type price advance
- ---------- ------------ ------------
- trad_cook 11.95 4,000.00
- trad_cook 14.99 8,000.00
- trad_cook 20.95 7,000.00
- sum sum
- ------------ ------------
- 47.89 19,000.00
- (7 rows affected)
-
-
- The columns in the COMPUTE clause must appear in the select list.
-
- You can't use SELECT INTO in the same statement as a COMPUTE clause because
- statements that include COMPUTE generate tables that include the summary
- results, which are not stored in the database.
-
- If you use COMPUTE BY, you must also use an ORDER BY clause. The columns
- listed after COMPUTE BY must be identical to or a subset of those listed
- after ORDER BY, and must be in the same left-to-right order, start with the
- same expression, and not skip any expressions. For example, say the ORDER BY
- clause is
-
- order by a, b, c
-
- the COMPUTE BY clause can be any or all of these:
-
- compute by a, b, c
- compute by a, b
- compute by a
-
- You must use a column name or an expression in the ORDER BY clause; you
- cannot sort by a column heading.
-
- The COMPUTE keyword can be used without BY to generate grand totals, grand
- counts, and so on. ORDER BY is optional if you use the COMPUTE keyword
- without BY.
-
- When you sum or average integer data, SQL Server treats the result as an int
- value, even if the datatype of the column is smallint or tinyint.
-
- ────────────────────────────────────────────────────────────────────────────
- WARNING
-
- To avoid overflow errors in DB-LIBRARY programs, make all variable
- declarations for results of averages or sums type int.
- ────────────────────────────────────────────────────────────────────────────
-
- In a SELECT statement with a COMPUTE clause, the order of columns in the
- select list overrides the order of the aggregate functions in the COMPUTE
- clause. For example:
-
- ╓┌─┌───────────────────────────────┌───────────┌─────────────────────────────╖
- ────────────────────────────────────────────────────────────────────────────
- select a, b, c
- from test
- compute sum(c), max(b), min(a)
- a b c
- --------- ---------- ----------
- ────────────────────────────────────────────────────────────────────────────
- --------- ---------- ----------
- 1 2 3
- 3 2 1
- sum
- =======
- 4
- max
- =======
- 2
- min
- =========
- 1
- (3 rows affected)
-
-
- DB-LIBRARY programmers must be aware of this to put the aggregate function
- results in the right place.
-
-
- See Also
-
- Aggregate Functions, COMPUTE Clause, Functions, GROUP BY and HAVING Clauses,
- SELECT
-
-
- SAVE TRANSACTION
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Sets a savepoint within a transaction.
-
-
- Syntax
-
- SAVE TRANsaction savepoint_name
-
-
- Examples
-
- begin transaction royaltychange
- /* A user sets out to change the royalty split for the
- two authors of The Gourmet Microwave. Since the
- database would be inconsistent between the two updates,
- they must be grouped into a user-defined transaction. */
-
- update titleauthor
- set royaltyper = 65
- from titleauthor, titles
- where royaltyper = 75
- and titleauthor.title_id = titles.title_id
- and title = "The Gourmet Microwave"
-
- update titleauthor
- set royaltyper = 35
- from titleauthor, titles
- where royaltyper = 25
- and titleauthor.title_id = titles.title_id
- and title = "The Gourmet Microwave"
-
- save transaction percentchanged
- /* After having updated the royaltyper entries
- for the two authors, the user inserts the savepoint
- percentchanged and then experiments to see how
- a 10% increase in the book's price would affect the
- authors' royalty earnings. */
-
- update titles
- set price = price * $1.1
- where title = "The Gourmet Microwave"
-
- select (price * royalty * ytd_sales) * royaltyper
- from titles, titleauthor
- where title = "The Gourmet Microwave"
- and titles.title_id = titleauthor.title_id
- /* The transaction is rolled back to the savepoint
- with the ROLLBACK TRANSACTION statement. */
-
- rollback transaction percentchanged
-
- commit transaction
-
- /* End of royaltychange. */
-
-
- Options
-
- savepoint_name
- The name assigned to the savepoint. It must conform to the rules for
- identifiers.
-
-
- Comments
-
- A savepoint is a marker set by a user within a transaction. It is used to
- cancel part of a transaction with the statement ROLLBACK TRANSACTION
- savepoint_name. All of the statements or procedures after the savepoint are
- undone. After a transaction is rolled back to a savepoint, it must proceed
- to completion (with more SQL statements if desired and a COMMIT TRANSACTION
- statement), or it must be canceled altogether (by rolling it back to its
- beginning).
-
- To cancel an entire transaction, use the form ROLLBACK TRANSACTION
- transaction_name. All of the transaction's statements or procedures are
- undone.
-
- If no savepoint_name or transaction_name is given with the ROLLBACK
- TRANSACTION statement, the transaction is rolled back to the previous BEGIN
- TRANSACTION.
-
- The ROLLBACK TRANSACTION statement must appear within a transaction; you
- can't roll back a transaction after COMMIT TRANSACTION has been entered.
-
- Define a transaction by enclosing SQL statements and/or stored procedures
- with BEGIN TRANSACTION and COMMIT TRANSACTION. Within a transaction,
- duplicate savepoint_names are allowed, but only the first instance of a
- savepoint_name is used.
-
-
- Permissions
-
- SAVE TRANSACTION permission defaults to public; no permissions are required
- to use it.
-
-
- See Also
-
- BEGIN TRANSACTION, COMMIT TRANSACTION, ROLLBACK TRANSACTION
-
-
- Search Conditions
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Set the conditions in a WHERE or HAVING clause. (Joins and subqueries are
- specified in the search conditions; see the "Joins" and "Subqueries"
- sections for full details.)
-
-
- Syntax
-
- Search conditions immediately follow the keywords WHERE or HAVING in a
- SELECT, INSERT, UPDATE, or DELETE statement. (HAVING search conditions
- differ from WHERE search conditions only in that aggregate functions are not
- allowed in WHERE conditions.) If you use more than one of the search
- conditions in a single statement, connect the conditions with AND or OR.
-
- {WHERE|HAVING}[NOT]expression comparison_operator expression
- {WHERE|HAVING}[NOT]column_name [NOT] LIKE "match_string"
- {WHERE|HAVING}[NOT]expression [NOT] BETWEEN expression AND expression
- {WHERE|HAVING}[NOT]expression [NOT] IN ({value_list|subquery})
- {WHERE|HAVING}[NOT]EXISTS (subquery)
- {WHERE|HAVING}[NOT]expression comparison_operator{ANY|ALL}(subquery)
- {WHERE|HAVING}[NOT]column_name join_operator column_name
- {WHERE|HAVING}[NOT]boolean_expression
- {WHERE|HAVING}[NOT]boolean_expression {AND|OR} boolean_expression
- {WHERE|HAVING}[NOT]column_name IS [NOT] NULL
-
- (The last clause is allowed only where column_name has been defined as
- allowing NULL in the CREATE TABLE statement.)
-
-
- Examples
-
- A. where advance * $2 > ytd_sales * price
-
- B. where phone not like '415%'
-
- Example B finds all rows in which the phone number does not begin with 415.
-
-
- C. where au_lname like "[CK]ars[eo]n"
-
- Example C finds the rows for authors named Carson, Carsen, Karsen, and
- Karson.
-
- D. where advance < $5000 or advance is null
-
- E. where (type = "business" or type = "psychology")
- and
- advance > $5500
-
- F. where ytd_sales between 4095 and 12000
-
- G. where state in ('CA', 'IN', 'MD')
-
- Examples D-G find the rows in which the state is one of the three in the
- list.
-
-
- Options
-
- expression
- A column name, a constant, a function, any combination of column names,
- constants, and functions connected by arithmetic or bitwise operators, or
- a subquery. The arithmetic operators are as follows:
-
- ╓┌───────────────────────┌───────────────────────────────────────────────────╖
- Symbol Meaning
- ────────────────────────────────────────────────────────────────────────────
- ++ Addition
- - Subtraction
- * Multiplication
- / Division
- % Modulo
- ────────────────────────────────────────────────────────────────────────────
- Symbol Meaning
- ────────────────────────────────────────────────────────────────────────────
- ────────────────────────────────────────────────────────────────────────────
-
-
- Addition, subtraction, division, and multiplication can be used on int,
- smallint, tinyint, float, and money columns. The modulo operator cannot be
- used with money or float columns. A modulo is the integer remainder after
- a division involving two integers. For example, 21 % 9 = 3 because 21
- divided by 9 equals 2 with a remainder of 3. The bitwise operators are as
- follows:
-
- Symbol Meaning
- ────────────────────────────────────────────────────────────────────────────
- & Bitwise and (two operands)
- | Bitwise or (two operands)
- Bitwise exclusive or (two operands)
- ~ Bitwise not (one operand)
- ────────────────────────────────────────────────────────────────────────────
-
- The bitwise operators can be used on int, smallint, and tinyint columns
- only. All the bitwise operators translate the integer parameters into
- binary representation before evaluating them. (See "Expressions" for more
- information.)
-
- comparison_operator
- One of the following:
-
- ╓┌────────────────────┌──────────────────────────────────────────────────────╖
- Symbol Meaning
- ────────────────────────────────────────────────────────────────────────────
- = Equal to
- > Greater than
- < Less than
- >= Greater than or equal to
- <= Less than or equal to
- != Not equal to
- !> Not greater than
- !< Not less than
- ────────────────────────────────────────────────────────────────────────────
-
-
- In comparing char and varchar data, < means closer to the beginning of the
- alphabet, and > means closer to the end of the alphabet. Case and special
- character evaluations depend on the sorting sequence used by the operating
- system on the machine on which SQL Server is located. On ASCII machines,
- for example, lowercase letters are greater than uppercase letters, and
- uppercase letters are greater than numbers. In comparing dates, < means
- earlier and > means later. Trailing blanks are ignored for the purposes of
- comparison. "Dirk" is the same as "Dirk ". Put quotation marks around all
- character and datetime data used with a comparison operator (= "Bennet", >
- "94609").
-
- column_name
- The name of a column used in the comparison. Qualify the column name with
- its table or view name if there is any ambiguity.
-
- NOT
- Negates any boolean expression and keywords, such as LIKE, NULL, BETWEEN,
- IN, and EXISTS.
-
- LIKE
- Indicates that the following character string (enclosed by single or
- double quotation marks) is a matching pattern. LIKE is available for char,
- varchar, and datetime columns (but not to search for seconds or
- milliseconds). You can use the LIKE keyword and wildcard characters with
- datetime data as well as with char and varchar. When you use LIKE with
- datetime values, SQL Server converts the dates to the standard datetime
- format and then to varchar. Since the standard storage format doesn't
- include seconds or milliseconds, you cannot search for seconds or
- milliseconds with LIKE and a pattern. It is a good idea to use LIKE when
- you search for datetime values, since datetime entries can contain a
- variety of date parts.
-
- For example, if you insert the value "9:20" into a column named
- arrival_time, the clause WHERE arrival_time = "9:20" would not find it
- because SQL Server converts the entry into "Jan 1, 1900 9:20AM". However,
- the clause WHERE arrival_time LIKE "%9:20%" would find it.
-
- match_string
- A string of characters and wildcards enclosed in quotation marks. The
- wildcards are as follows:
-
- Symbol Meaning
- ────────────────────────────────────────────────────────────────────────────
- % Any string of 0 or more characters
-
- _ (underscore) Any single character
-
- [ ] Any single character within the
- specified range ([a-f]) or set ([abcdef])
-
- [^] Any single character not within the
- specified range ([^a-f]) or set
- ([^abcdef])
-
- ────────────────────────────────────────────────────────────────────────────
-
-
- The wildcard and the string must be enclosed in single or double quotation
- marks. For complete information, see "Wildcard Characters."
-
- IS [NOT] NULL
- Keywords that search for null values (or all values except null values).
- It is allowed only if the column has been defined to allow null values in
- the CREATE TABLE statement. An expression with a bitwise or arithmetic
- operator evaluates to NULL if any of the operands is null.
-
- BETWEEN
- The range-start keyword. Use AND for the range-end value. A range of
- BETWEEN x and y, unlike a range of > x < y, is inclusive.
-
- IN
- Allows you to select values that match any one of a list of values. The
- comparator can be a constant or a column name, and the list can be a set
- of constants or, more commonly, a subquery. (See "Subqueries" for
- information on using IN with a subquery.) Enclose the list of values in
- parentheses.
-
- value_list
- A list of values. Put single or double quotation marks around char,
- varchar, and datetime values, and separate each value from the following
- one with a comma. (See example E, earlier in this section.)
-
- EXISTS
- Is used with a subquery to test for the existence of some result from the
- subquery. (See "Subqueries" for more information.)
-
- subquery
- A restricted SELECT statement (ORDER BY and COMPUTE clauses and the INTO
- keyword are not allowed) in the WHERE or HAVING clause of a SELECT,
- INSERT, DELETE, or UPDATE statement, or in a subquery or expression. (See
- "Subqueries" for more information.)
-
- ANY
- Is used with <, >, or = and a subquery. It returns results when any value
- retrieved in the subquery matches the value in the WHERE or HAVING clause
- of the outer statement. (See "Subqueries" for more information.)
-
- ALL
- Is used with < or > and a subquery. It returns results when all values
- retrieved in the subquery match the value in the WHERE or HAVING clause of
- the outer statement. (See "Subqueries" for more information.)
-
- join_operator
- A comparison operator, =* or *=. (See "Joins" for more information.)
-
- boolean_expression
- An expression that returns true or false. (See "Expressions" for a full
- definition.)
-
- AND
- Joins two conditions and returns results when both of the conditions are
- true. When more than one logical operator is used in a statement, AND
- operators are normally evaluated first. However, you can change the order
- of execution with parentheses.
-
- OR
- Joins two conditions and returns results when either of the conditions is
- true. When more than one logical operator is used in a statement, OR
- operators are normally evaluated after AND operators. However, you can
- change the order of execution with parentheses.
-
-
- Comments
-
- WHERE and HAVING search conditions are identical, except that aggregate
- functions are not permitted in WHERE clauses (HAVING avg(price) > $20 is
- legal; WHERE avg(price) > $20 is not legal). See "Aggregate Functions" for
- information on the use of aggregate functions.
-
- You can use a HAVING clause without a GROUP BY clause.
-
- If there are columns in the select list that neither have aggregate
- functions applied to them nor are included in the query's GROUP BY clause
- (illegal in standard SQL), the meanings of HAVING and WHERE are somewhat
- different.
-
- In this situation, a WHERE clause restricts the rows that are included in
- the calculation of the aggregate function but does not restrict the rows
- returned by the query. Conversely, a HAVING clause restricts the rows
- returned by the query but does not affect the calculation of the aggregate
- function. See "GROUP BY and HAVING Clauses" for examples.
-
-
- See Also
-
- Aggregate Functions, DELETE, EXECUTE, Expressions, INSERT, Joins, SELECT,
- Subqueries, UPDATE, Wildcard Characters, sp_helpjoins
-
-
- SELECT
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Retrieves rows from the database.
-
-
- Syntax
-
- SELECT [ALL | DISTINCT] select_list
- [INTO [[database.]owner.]table_name]
- [FROM [[database.]owner.]{table_name | view_name} [HOLDLOCK]
- [,[[database.]owner.]{table_name | view_name} [HOLDLOCK]...]
- [WHERE search_conditions]
- [GROUP BY [ALL]
- aggregate_free_expression
- [, aggregate_free_expression...]
- [HAVING search_conditions]
- [ORDER BY {[[[database.]owner.]{table_name. | view_name.}]
- column_name |
- select_list_number | expression} [ASC | DESC]
- [,{[[[database.]owner.]{table_name | view_name.}]
- column_name |
- select_list_number | expression} [ASC | DESC]]...]
- [COMPUTE row_aggregate(column_name)
- [, row_aggregate(column_name)...]
- [BY column_name [, column_name]...]]
- [FOR BROWSE]
-
- The keywords in the SELECT statement, as in all other SQL statements, must
- be used in the order shown in the syntax statement.
-
-
- Examples
-
- A. select *
- from publishers
-
- B. select pub_id, pub_name, city, state
- from publishers
-
- C. select "The publisher's name is", Publisher = pub_name,
- pub_id
- from publishers
-
- D. select pub_id, total = sum (ytd_sales)
- from titles
- where advance < $10000
- and ytd_sales is not null
- group by pub_id
- having count(*) >1
-
-
-
- E. select type, price, advance
- from titles
- order by type desc
- compute avg(price), sum(advance) by type
- compute sum(price), sum(advance)
-
- F. select type, price, advance
- from titles
- compute sum(price), sum(advance)
-
- G. select *
- into coffeetabletitles
- from titles
- where price > $20
-
- H. select *
- into newtitles
- from titles
- where price > $25
- and price < $20
-
-
- Options
-
- ALL
- Includes all rows in the results. This is the default.
-
- DISTINCT
- Includes only unique rows in the results. Null values are considered equal
- for the purposes of the DISTINCT keyword; only one NULL is selected no
- matter how many are encountered.
-
- select_list
- One or more of the following:
-
-
- ■ Asterisk (*), representing all columns in create-table order
-
- ■ A list of column names in the order in which you want to see them
-
- ■ A column heading to replace the default column heading (the column
- name) in the following form:
-
- column_heading = column_name
- or
- column_name column_heading
-
-
- ■ An expression (a column name, constant, function, or any combination
- of column names, constants, and functions connected by arithmetic or
- bitwise operators, or a subquery)
-
- ■ A built-in function or an aggregate function
-
- ■ Any combination of these items
-
- See "Expressions" for information on arithmetic and bitwise
- operators and a more detailed definition of expressions. See
- "Functions" for information on functions. See "Subqueries" for
- information on subqueries.
-
- INTO
- Creates a new table based on the columns specified in the select list and
- the rows chosen in the WHERE clause. The new table must not already exist.
- Its name must be unique in the database and must conform to the rules for
- identifiers. See example G.
-
- You can use SELECT INTO to create a duplicate table with no data by
- having a false condition in the WHERE clause. See example H.
-
- You cannot use SELECT INTO inside a user-defined transaction.
-
- SELECT INTO is a two-step operation. The first step creates the new
- table. The second step inserts the specified rows into the new
- table. If the second step fails for any reason (hardware failure,
- exceeding a system resource, and so on), the new table will exist
- with no rows in it.
-
- The select into/bulkcopy option must be on (by executing
- sp_dboption) to be able to select into a permanent table. You do not
- have to have the select into/bulkcopy option on to select into a
- temporary table, since the tempdb temporary database is never
- recovered.
-
- While the select into/bulkcopy option is on, 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.
-
- By default, the select into/bulkcopy option is off in newly created
- databases. To change the default, turn this option on in the model
- database.
-
- FROM
- Indicates that particular tables and views are used in the SELECT
- statement. It is always required except when the select list contains no
- column names (that is, constants and arithmetic expressions only):
-
- select 5 x, 2 y, "the product is", 5*2 Result
-
- table_name, view_name
- Tables and views used in the SELECT statement. If there is more than one
- table or view in the list, separate their names with commas. The order of
- the tables and views after the FROM keyword makes no difference in the
- results.
-
- As the syntax indicates, you can query tables in different databases
- in the same statement.
-
- Table names and view names can be given aliases, either for
- convenience or to distinguish the different roles that a table or
- view play in a self-join or subquery. Give the table or view name,
- then a space, then the alias name, like this:
-
- select *
- from publishers pu, authors au
-
- HOLDLOCK
- Restricts a shared lock on a specified table or view by holding it until
- the completion of a transaction (instead of releasing the shared lock as
- soon as the required table or data page is no longer needed, whether or
- not the transaction has been completed). The HOLDLOCK statement applies
- 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.
-
- search_conditions
- The conditions for the rows that are retrieved. A search condition can
- include column names; expressions; arithmetic operators; comparison
- operators; the keywords NOT, LIKE, IS NULL, AND, OR, BETWEEN, IN, EXISTS,
- ANY, or ALL; subqueries; or any combination of these items. There is no
- limit on the number of search conditions that can be included in an SQL
- statement. WHERE search conditions and HAVING search conditions are
- identical with one exception: WHERE clauses cannot contain aggregate
- functions and HAVING clauses can. See the sections "Search Conditions,"
- "WHERE Clause," "Expressions," and "Subqueries" for more information.
-
- GROUP BY
- Keywords that find a value for each group. These values appear as new
- columns in the results, rather than as new rows.
-
- When GROUP BY is used with standard SQL, each item in the select
- list must either have a fixed value in every row in the group or be
- used with aggregate functions that produce a single value for each
- group. TRANSACT-SQL has no such restrictions on the items in the
- select list.
-
- Also, with TRANSACT-SQL, you can group by any expression (though not
- by a column alias), while with standard SQL you can only group by a
- column.
-
- You can use the following aggregate functions with GROUP BY
- (expression is almost always a column name):
- ╓┌─────────────────────────────────┌─────────────────────────────────────────╖
- Aggregate Function Result
- ────────────────────────────────────────────────────────────────────────────
- SUM([DISTINCT] expression) Returns the total of the [distinct]
- values in the numeric column
-
- AVG([DISTINCT] expression) Returns the average of the [distinct]
- values in the numeric column
-
- COUNT([DISTINCT] expression) Returns the number of [distinct]
- non-null values in the expression
-
- COUNT(*) Returns the number of selected rows
-
- MAX(expression) Returns the highest value in the
- expression
-
- MIN(expression) Returns the lowest value in the
- expression
-
- Aggregate Function Result
- ────────────────────────────────────────────────────────────────────────────
- ────────────────────────────────────────────────────────────────────────────
-
-
-
- (See "GROUP BY" and "Aggregate Functions" for more information.)
-
- A table can be grouped by any combination of columns─that is, groups
- can be nested within each other. Note that you cannot group by a
- column heading; you must use a column name, an expression, or a
- number representing the position of the item in the select list.
-
- ALL
- All groups in the results, even those that don't have any rows that meet
- the search conditions. (See "GROUP BY and HAVING Clauses" for an example.)
-
- aggregate_free_expression
- An expression that includes no aggregate functions.
-
- HAVING
- Sets conditions for the GROUP BY clause, similar to the way that WHERE
- sets conditions for the SELECT clause. There is no limit on the number of
- conditions that can be included.
-
- You can use a HAVING clause without a GROUP BY clause.
-
- If there are columns in the select list that neither have aggregate
- functions applied to them nor are included in the query's GROUP BY
- clause (illegal in standard SQL), the meanings of HAVING and WHERE
- are somewhat different.
-
- In this situation, a WHERE clause restricts the rows that are
- included in the calculation of the aggregate function but does not
- restrict the rows returned by the query. Conversely, a HAVING clause
- restricts the rows returned by the query but does not affect the
- calculation of the aggregate function. See "GROUP BY and HAVING
- Clauses" for examples.
-
- ORDER BY
- Sorts the results by columns. You can sort up to 16 columns. In
- TRANSACT-SQL, you can use ORDER BY for items that do not appear in the
- select list. You can sort by a column name, a column heading (or alias),
- an expression, or a number representing the position of the item in the
- select list (the select_list_number). If you sort by select list number,
- the columns to which the ORDER BY clause refers must be included in the
- select list, and the select list cannot be *.
-
- ASC
- Indicates that results are to be sorted in ascending order, which is the
- default.
-
- DESC
- Indicates that results are to be sorted in descending order.
-
- COMPUTE
- Used with row aggregate functions (SUM, AVG, MIN, MAX, and COUNT) to
- generate control break summary values. The summary values appear as
- additional rows in the query results, allowing you to see detail and
- summary rows with one statement.
-
- You cannot use a SELECT INTO clause with COMPUTE.
-
- If you use COMPUTE BY, you must also use an ORDER BY clause. The
- columns listed after COMPUTE BY must be identical to or a subset of
- those listed after ORDER BY, and must be in the same left-to-right
- order, start with the same expression, and not skip any expressions.
-
- For example, say the ORDER BY clause is
-
- order by a, b, c
-
- Then the COMPUTE BY clause can be any (or all) of these:
-
- compute by a, b, c
- compute by a, b
- compute by a
-
- The COMPUTE keyword can be used without BY to generate grand totals,
- grand counts, and so on. ORDER BY is optional if you use the COMPUTE
- keyword without BY. If more than one item is listed after COMPUTE BY,
- the items must be a subset of those listed after ORDER BY and must be
- in the same order. (See "COMPUTE Clause" for details and examples.)
-
- FOR BROWSE
- DB-LIBRARY only. Allows you to perform updates while viewing data. FOR
- BROWSE is used only in an application program using DB-LIBRARY.
-
-
-
- Comments
-
- The keywords in the SELECT statement, as in all other SQL statements, must
- be used in the order shown in the syntax statement.
-
- Although it is not shown in the syntax, the keyword ALL can be used after
- SELECT for compatibility with other implementations of SQL. ALL is the
- default. Used in this context, ALL is the opposite of DISTINCT: all
- retrieved rows are included in the results, whether or not some are
- duplicates.
-
- Column headings and table aliases must conform to the rules for identifiers.
-
-
- If you have two tables identical in structure except that one has NULL
- fields and the other has NOT NULL fields, this difference makes it
- impossible to insert the data from the NULL table into the NOT NULL table
- with a SELECT, whether or not there is any NULL data. The length of returned
- text defaults to the size of the text. To change the length of returned
- text, use the SET TEXTSIZE statement.
-
- The limit on the length of text data returned with a SELECT statement
- defaults to 32K, or to the size set with SET TEXTSIZE.
-
-
- Permissions
-
- SELECT permission defaults to the owner of the table or view, who can
- transfer it to other users.
-
-
- See Also
-
- Aggregate Functions, COMPUTE Clause, CREATE TRIGGER, DELETE, Expressions,
- Functions, GROUP BY and HAVING Clauses, INSERT, Row Aggregate Functions,
- Search Conditions, UPDATE, WHERE Clause, Wildcard Characters, sp_dboption
-
-
- SET
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Sets SQL Server query-processing options for the duration of the user's work
- session, or inside a trigger or stored procedure.
-
-
- Syntax
-
- SET
- {{ ARITHABORT | ARITHIGNORE |
- BACKGROUND | NOCOUNT | NOEXEC |
- OFFSETS {keyword_list} | PARSEONLY | PROCID |
- SHOWPLAN | STATISTICS IO | STATISTICS TIME }
- {ON | OFF} |
- ROWCOUNT number | TEXTSIZE n}
-
-
- Examples
-
- A. set showplan on
- go
- set noexec on
- go
- select * from publishers
- go
-
- For each query, SQL Server returns a description of the processing plan but
- does not execute it (example A).
-
- B. set rowcount 10
-
- For each query, SQL Server stops processing the query after it returns the
- first ten rows (example B).
-
-
- Options
-
- 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.
-
- BACKGROUND
- Puts processes generated by subsequent statements in the background and
- breaks the connection to the workstation. Once BACKGROUND is on, you can't
- do anything else. Your session is over; you must interrupt it and log in
- again.
-
- If you execute a stored procedure that sets the background option, your
- session becomes disconnected from your workstation. The connection is not
- re-established even when the procedure finishes executing.
-
- 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 on.
-
- NOEXEC
- Compiles each query but does not execute it. NOEXEC is often used with
- SHOWPLAN. Once NOEXEC is turned on, no subsequent statements will be
- executed (including other SET statements) until NOEXEC is turned off.
-
- OFFSETS
- DB-LIBRARY only. 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
- constructs: SELECT, FROM, ORDER, COMPUTE, TABLE, PROCEDURE, STATEMENT,
- PARAM, and EXECUTE.
-
- The OFFSETS option is used only in an application program using
- DB-LIBRARY.
-
- PARSEONLY
- Checks the syntax of each query and returns any error messages without
- generating a sequence tree, compiling, or executing the query. Do not use
- PARSEONLY in a stored procedure. PARSEONLY returns offsets if the OFFSETS
- option is on and there are no errors (however, OFFSETS is used only in an
- application program using DB-LIBRARY).
-
- PROCID
- Returns the ID number of the stored procedure to DB-LIBRARY (not to the
- user) before sending rows generated by that stored procedure.
-
- 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".
-
- SHOWPLAN
- Generates a description of the processing plan for the query and
- immediately processes it unless NOEXEC is set. Do not use SHOWPLAN in a
- stored procedure.
-
- 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 command and the time
- it took to execute each step of the command. Times are given in timeticks,
- the exact value of which is machine-dependent.
-
- TEXTSIZE n
- Specifies the size in bytes of text type data to be returned with a SELECT
- statement. If you specify a textsize of 0, 32K bytes of data are returned
- with a SELECT statement. The @TEXTSIZE global variable stores the current
- setting.
-
-
- Comments
-
- 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.
-
- Do not use the SHOWPLAN or PARSEONLY option within a stored procedure.
-
- The SET options can be 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 to ON. The default setting for ROWCOUNT is 0
- (return all rows); the default for the others is OFF.
-
- ■ The STATISTICS 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 to ON. 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.
-
-
- 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. In the first example, the
- SET statement is combined with the query in the same batch; therefore, the
- SET option doesn't apply to the queries in that batch. In the second
- example, the SET statement is executed before the batch; therefore, the SET
- option does apply to the queries in that batch.
-
- A. set showplan on
- select * from publishers
- go
-
- 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)
-
- B. set showplan on
- go
- select * from publishers
- go
- 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)
-
-
- See Also
-
- Batch Queries, Stored Procedures, Triggers
-
-
- SETUSER
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Impersonates another user. This statement is used by a Database Owner.
-
-
- Syntax
-
- SETUSER ["username"]
-
-
- Examples
-
- setuser "mary"
- go
- grant select on authors to joe
- setuser
- go
-
- The Database Owner temporarily adopts Mary's identity in the database to
- grant permissions on authors, a table owned by Mary.
-
-
- Comments
-
- When the Database Owner uses the SETUSER statement, SQL Server checks the
- permissions of the user being impersonated instead of the permissions of the
- Database Owner.
-
- When the System Administrator uses the SETUSER statement, he or she retains
- full System Administrator permissions.
-
- The user being impersonated must be listed in the sysusers table of the
- database.
-
- The SETUSER statement remains in effect until another SETUSER statement is
- given or until the current database is changed with the USE statement.
-
- The SETUSER statement with no username re-establishes the Database Owner's
- original identity.
-
- SETUSER is used by the Database Owner to adopt the identity of another user,
- to use another user's database object, to grant permissions, to create an
- object, or for some other reason.
-
- The System Administrator can use SETUSER to create objects that will be
- owned by another user. However, since the System Administrator operates
- outside the permissions system, she or he cannot use SETUSER to acquire
- another user's permissions. No matter what SETUSER statements have been
- executed, the System Administrator always has permission to do everything.
-
-
- Permissions
-
- SETUSER permission defaults to the Database Owner and is not transferable.
-
-
- See Also
-
- Batch Queries, GRANT, REVOKE
-
-
- SHUTDOWN
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Brings the system to a halt. This statement can only be executed by the
- System Administrator.
-
-
- Syntax
-
- SHUTDOWN [WITH NOWAIT]
-
-
- Options
-
- WITH NOWAIT
- Keywords that shut SQL Server down immediately, without performing
- checkpoints in every database. SQL Server exits after attempting to
- terminate all user processes and roll back any active transactions.
-
-
- Comments
-
- Unless the System Administrator uses the NOWAIT option, SHUTDOWN waits for
- currently executing SQL statements or stored procedures to finish and then
- performs a checkpoint in every database.
-
- SHUTDOWN minimizes the amount of work that automatic recovery has to do when
- the System Administrator restarts SQL Server.
-
-
- Permissions
-
- SHUTDOWN permission defaults to the System Administrator and cannot be
- transferred.
-
-
- String Functions
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Perform various operations on binary data, character strings, or
- expressions, including concatenation.
-
-
- Syntax
-
- Built-in string functions return values commonly needed for operations on
- character data. String function names are not keywords. String functions
- have the following syntax:
-
- function_name(parameters)
-
- You can concatenate binary or character expressions like this:
-
- (expression + expression [+ expression} . . .)
-
- Function names, parameters, and results are as follows:
-
-
-
- ╓┌───────────┌───────────────────────────────┌───────────────────────────────╖
- Function Parameters Result
- ────────────────────────────────────────────────────────────────────────────
- ASCII (char_expr) The ASCII code value of the
- leftmost character of a
- character expression.
-
- CHAR (int_expr) A character converted from an
- ASCII code. The ASCII code
- should be between 0 and 255;
- otherwise, NULL is returned.
- Function Parameters Result
- ────────────────────────────────────────────────────────────────────────────
- otherwise, NULL is returned.
-
- CHARINDEX ("Pattern", expression) The starting position of the
- specified pattern. The first
- parameter is the pattern. The
- second parameter is an
- expression, usually a column
- name, in which SQL Server
- searches for the pattern. Not
- implemented for text and image
- data.
-
- DATALENGTH (char_expr) The length of any type of data
- value or text field. A NULL
- string returns a length of 1.
-
- DIFFERENCE (char_expr1, char_expr2) The difference between the
- values of two character
- expressions as returned by the
- Function Parameters Result
- ────────────────────────────────────────────────────────────────────────────
- expressions as returned by the
- SOUNDEX function.
-
- LOWER (char_expr) Lowercase converted from
- uppercase.
-
- LTRIM (char_expr) Data without leading blanks.
-
- REPLICATE (char_expr, int_expr) A character expression
- repeated a specified number of
- times. If int_expr is negative,
- a NULL string is returned.
-
- RIGHT (char_expr, int_expr) Part of a character string
- starting int_expr characters
- from the right. If int_expr is
- negative, a NULL string is
- returned.
-
- Function Parameters Result
- ────────────────────────────────────────────────────────────────────────────
- RTRIM (char_expr) Data without trailing blanks.
-
- SOUNDEX (char_expr) A four-digit (SOUNDEX) code
- for use in evaluating the
- similarity of two strings.
-
- SPACE (int_expr) A string of repeated spaces.
- The number of spaces is equal
- to int_expr. If int_expr is
- negative, a NULL string is
- returned.
-
- STR (float_expr [, length [, Character data converted from
- decimal]]) numeric data. The length is
- the total length, including
- decimal point, sign, digits,
- and spaces. The decimal value
- is the number of spaces to the
- Function Parameters Result
- ────────────────────────────────────────────────────────────────────────────
- is the number of spaces to the
- right of the decimal point.
-
- STUFF (char_expr1, start, length, Data where length characters
- char_expr2) have been deleted from
- char_expr1 at start and where
- char_expr2 has been inserted
- into char_expr1 at start. Not
- implemented for text data.
-
- SUBSTRING (expression, start, length) Part of a character or binary
- string. The first parameter
- can be a character or binary
- string, a column name, or an
- expression that includes a
- column name. (Do not use
- expressions that include
- functions or subqueries.) The
- second parameter specifies the
- Function Parameters Result
- ────────────────────────────────────────────────────────────────────────────
- second parameter specifies the
- position at which the
- substring begins. The third
- parameter specifies the number
- of characters in the substring.
- Not implemented for text data.
-
- UPPER (char_expr) Uppercase converted from
- lowercase.
-
- ++ The + option indicates two or
- more concatenated character
- strings, binary strings,
- column names, or a combination
- of them. Enclose character
- strings in single or double
- quotation marks.
-
- ────────────────────────────────────────────────────────────────────────────
- Function Parameters Result
- ────────────────────────────────────────────────────────────────────────────
- ────────────────────────────────────────────────────────────────────────────
-
-
-
-
- Examples
-
- A. select Name = (au_lname + ", " + au_fname)
- from authors
-
- Example A displays author names under the column heading Name in last-name,
- first-name order with a comma after the last name, that is, Bennet, Abraham.
-
-
- B. select au_lname, substring(au_fname, 1, 1)
- from authors
-
- Example B displays the last name and first initial of each author, that is,
- Bennet A.
-
- C. select (au_lname + ", " + substring(au_fname,
- 1, 1) + ".")
- from authors
-
- Example C displays the last name and first initial of each author, that is,
- Bennet, A.
-
- D. select substring ((pub_id + title_id), 1, 6)
- from titles
-
- Example D displays the first six characters of the concatenation of each
- pub_id and title_id. In other words, it displays all four characters of the
- pub_id and the first two characters of the title_id.
-
- E. select charindex("wonderful", notes)
- from titles
- where title_id = "TC3218"
-
- Example E returns the position at which the pattern "wonderful" begins in
- the notes column of titles.
-
- Statement Result
-
- F. select right("abcde", 3) cde
- select right("abcde", 6) abcde
-
- G. select str(123.45, 6, 2) 123.45
-
- H. select stuff("abc", 2, 1, "xyz") axyzc
-
-
- Comments
-
- All string functions and concatenation can be used on char, varchar, binary,
- and varbinary datatypes. In addition, the REPLICATE and RIGHT string
- functions can be used on datetime datatypes.
-
- String functions can be nested. See examples C and D.
-
- When you use constants with string functions, enclose them in single or
- double quotation marks.
-
- String functions can be used in the select list, in the WHERE clause, and
- anywhere an expression is allowed.
-
- Length and decimal parameters to STR (if supplied) should be non-negative.
- The default length is 10. The number is rounded to an integer by default or
- if the decimal parameter is 0. The specified length should be at least equal
- to or greater than the part of the number before the decimal point plus the
- number's sign (if any). If float_expr exceeds the specified length, the
- string returns "**" of the specified length:
-
- select str(123.45, 2, 2)
- --
- **
- (1 row affected)
-
- Do not use a function or subquery as the float_expr in the STR function. A
- short float_expr is right justified in the specified length, and a long
- float_expr is truncated to the specified number of decimal places.
-
- The STUFF function inserts a string into another string. It deletes a
- specified length of characters from char_expr1 at the start position. It
- then inserts char_expr2 into char_expr1 at the start position.
-
- If the start position or the length is negative, a NULL string is returned.
-
-
- If the start position is longer than char_expr1, a NULL string is returned.
-
-
- If the length to delete is longer than char_expr1, it is deleted to the
- first character in char_expr1:
-
- select stuff("abc", 2, 3, "xyz")
- ──
- axyz
-
- (1 row affected)
-
- The SOUNDEX function converts an alpha string to a four-digit code for
- comparison use. All characters that are nonalpha will be used to terminate
- the compression. This function always returns some value.
-
- The DIFFERENCE function compares two strings and evaluates the similarity
- between them, returning a value from 0 to 4. Four is the best match. For
- example:
-
- ╓┌──────────────┌────────────────────────────────────────────────────────────╖
- ────────────────────────────────────────────────────────────────────────────
- select difference("abc", "abc")
- ---------
- 4
- (1 row affected)
- select difference("abc", "abd")
- ---------
- 3
- (1 row affected)
-
-
-
- See Also
-
- Conversion Function, Functions, Mathematical Functions, SELECT, Text/Image
- Functions
-
-
- Subqueries
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Nest a SELECT statement inside a SELECT, INSERT, UPDATE, or DELETE
- statement, another subquery, or anywhere an expression is allowed (if it
- returns a single value). A subquery is always enclosed in parentheses.
-
- Many SQL statements that include subqueries can be alternatively formulated
- as joins. (See "Joins" for more information on joining; see "SELECT" for
- more information on the full SELECT statement; see "WHERE Clause" for more
- information on search conditions and WHERE clause syntax.)
-
-
- Syntax
-
- A subquery can appear anywhere an expression can be used, as long as it
- returns a single value. It is usually nested inside the WHERE or HAVING
- clause of an outer SELECT, INSERT, UPDATE, DELETE, or another subquery. A
- subquery can be used in the following contexts:
-
- A. expression comparison_operator [ANY | ALL] (subquery)
-
- B. expression [NOT] IN (subquery)
-
- C. [NOT] EXISTS (subquery)
-
- A subquery has the following restricted SELECT syntax:
-
- ( SELECT [DISTINCT] subquery_select_list
- [FROM [[database.]owner.]{table_name | view_name} [HOLDLOCK]
- [, [[database.]owner.]{table_name | view_name} [HOLDLOCK]]...]
- [WHERE search_conditions]
- [GROUP BY aggregate_free_expression
- [, aggregate_free_expression]...]
- [HAVING search_conditions] )
-
-
- Examples
-
- A. select distinct pub_name
- from publishers
- where pub_id in
- (select pub_id
- from titles
- where type = "business")
-
- B. select distinct pub_name
- from publishers
- where "business" in
- (select type
- from titles
- where pub_id = publishers.pub_id)
-
- C. select distinct pub_name
- from publishers
- where exists
- (select *
- from titles
- where pub_id = publishers.pub_id
- and type = "business")
-
- Examples A, B, and C find the names of publishers who have published
- business books.
-
- D. select au_lname, au_fname
- from authors
- where au_id in
- (select au_id
- from titleauthor
- where title_id in
- (select title_id
- from titles
- where type = "popular_comp"))
-
- Example D finds the names of authors who have participated in writing at
- least one popular computing book.
-
- E. select title
- from titles
- where advance > all
- (select advance
- from titles, publishers
- where titles.pub_id = publishers.pub_id
- and pub_name = "Algodata Infosystems")
-
- Example E finds the books that commanded an advance greater than the largest
- advance paid by Algodata Infosystems.
-
- F. select au_lname, au_fname
- from authors
- where city = any
- (select city
- from publishers)
-
- Example F finds the authors that live in the same city as some publisher.
-
-
- Options
-
- DISTINCT
- Cannot be used with subqueries that include a GROUP BY clause.
-
- subquery_select_list
- A restricted select list for use with subqueries introduced with IN or a
- comparison operator. It consists of one expression. If a column name is
- used in the WHERE clause of the outer statement, a column name in the
- subquery select list must be join compatible with it.
-
- The select list must consist of only one column name except for the EXISTS
- subquery, in which case the asterisk (*) is usually used in place of the
- single column name. Do not specify more than one column name.
-
- expression
- A column name; a constant; a function; any combination of column names,
- constants, and functions connected by arithmetic or bitwise operators; or
- a subquery. (The three formats for subqueries in the "Syntax" section are
- all considered expressions and can be substituted wherever the word
- "expression" appears as long as the subquery returns a single value.) The
- arithmetic operators are as follows:
-
- ╓┌───────────────────────┌───────────────────────────────────────────────────╖
- Symbol Meaning
- ────────────────────────────────────────────────────────────────────────────
- ++ Addition
- - Subtraction
- * Multiplication
- / Division
- % Modulo
- ────────────────────────────────────────────────────────────────────────────
-
-
- Addition, subtraction, division, and multiplication can be used on int,
- smallint, tinyint, float, and money columns. The modulo operator can be
- used with all integer datatypes but cannot be used with money or float
- columns. A modulo is the integer remainder after dividing two integers.
- For example, 21 % 9 = 3 because 21 divided by 9 equals 2 with a remainder
- of 3. The bitwise operators are as follows:
-
- Symbol Meaning
- ────────────────────────────────────────────────────────────────────────────
- & Bitwise and (two operands)
- | Bitwise or (two operands)
- Bitwise exclusive or (two operands)
- ~ Bitwise not (one operand)
- ────────────────────────────────────────────────────────────────────────────
-
- The bitwise operators can be used on int, smallint, and tinyint columns
- only. All the bitwise operators translate the integer parameters into
- binary representation before evaluating them. (See "Expressions" for more
- information.)
-
- comparison_operator
- One of the following:
-
- ╓┌────────────────────┌──────────────────────────────────────────────────────╖
- Symbol Meaning
- ────────────────────────────────────────────────────────────────────────────
- = Equal to
- > Greater than
- < Less than
- >= Greater than or equal to
- <= Less than or equal to
- Symbol Meaning
- ────────────────────────────────────────────────────────────────────────────
- <= Less than or equal to
- != Not equal to
- !> Not greater than
- !< Not less than
- ────────────────────────────────────────────────────────────────────────────
-
-
- In comparing char and varchar data, < means closer to the beginning of the
- alphabet, and > means closer to the end of the alphabet. Case and special
- character evaluations depend on the collating sequence of the machine on
- which SQL Server is located. On ASCII machines, for example, lowercase
- letters are greater than uppercase letters, and uppercase letters are
- greater than numbers. In comparing dates, < means earlier and > means
- later. Trailing blanks are ignored for comparison purposes. So, for
- example, "Dirk" is the same as "Dirk ". Put quotation marks around all
- character and datetime data used with a comparison operator (= "Bennet", >
- "94609").
-
- ANY
- Is used with >, <, or = and a subquery. > ANY is true (and the subquery
- returns results) when the value in the outer query is greater than any
- value in the list (that is, greater than the minimum value in the list). <
- ANY is true (and the subquery returns results) when the value in the outer
- query is less than any value in the list (that is, less than the maximum
- value in the list).
-
- ALL
- Is used with > or < and a subquery. > ALL means that the value being
- compared must be greater than all values in the list (that is, greater
- than the maximum value). < ALL means that the value being compared must be
- less than all values in the list (that is, less than the minimum value).
-
- IN
- Returns results when any value in the subquery matches the value in the
- WHERE clause of the outer statement. (IN is equivalent to = ANY.) IN can
- also be used with a list of values enclosed in parentheses. See "WHERE
- Clause" for details.
-
- subquery
- A query with the restricted SELECT syntax shown in the "Examples" section.
- It cannot include ORDER BY or COMPUTE clauses or the INTO keyword. If it
- is introduced by an unmodified comparison operator (and therefore returns
- a single value), it cannot include GROUP BY and HAVING clauses. The select
- list must consist of only one column name, except for the EXISTS subquery,
- in which case the asterisk (*) is almost always used. (SQL Server does not
- check the select list of a subquery introduced with EXISTS.) A subquery
- can contain another subquery. A subquery is legal in any TRANSACT-SQL
- syntax that allows an expression as long as it returns a single value.
-
- EXISTS
- Is used with a subquery to test for the existence of some result from the
- subquery. EXISTS is not preceded by an expression. The subquery that
- follows the EXISTS keyword is enclosed in parentheses. If the NOT keyword
- is used, the WHERE clause is satisfied if no rows are returned by the
- subquery. Since EXISTS tests only for the existence of a condition, the
- asterisk (*) is almost always used as the select list.
-
-
- Comments
-
- A subquery can be used anywhere an expression can be used if it returns a
- single value.
-
- Note that the syntax for EXISTS is somewhat different than the syntax for
- the other keywords; it does not take an expression between WHERE and itself.
- The two queries following, which are semantically equivalent, illustrate the
- difference:
-
- A. select distinct pub_name
- from publishers
- where exists
- (select *
- from titles
- where pub_id = publishers.pub_id
- and type = "business")
-
- B. select distinct pub_name
- from publishers
- where pub_id in
- (select pub_id
- from titles
- where type = "business")
-
- A correlated (or repeating) subquery depends on the outer query for its
- values. It is executed repeatedly, once for each row that might be selected
- by the outer query. Here's an example:
-
- select distinct au_lname, au_fname
- from authors
- where 100 in
- (select royaltyper
- from titleauthor
- where titleauthor.au_id = authors.au_id)
-
- The subquery in this statement cannot be evaluated independently of the
- outer query. It needs a value for authors.au_id, but this value changes as
- SQL Server examines different rows in authors.
-
- A correlated subquery can also be used in the HAVING clause of an outer
- query. This example finds the types of books for which the maximum advance
- is more than twice the average for the group:
-
- select t1.type
- from titles t1
- group by t1.type
- having max(t1.advance) >=all
- (select 2 * avg(t2.advance)
- from titles t2
- where t1.type = t1.type)
-
-
- See Also
-
- DELETE, EXECUTE, Expressions, Functions, GROUP BY and HAVING Clauses,
- INSERT, Joins, SELECT, UPDATE, WHERE Clause
-
-
- System Functions
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Return special information from the database.
-
-
- Syntax
-
- function_name(parameters)
-
- Function names, parameters, and results are listed in the following table.
- Where the parameter is optional, the function returns the current value.
-
-
-
- ╓┌────────────┌──────────────────────────────┌───────────────────────────────╖
- Function Parameters Result
- ────────────────────────────────────────────────────────────────────────────
- COL_LENGTH ("object name", "column name") The length of column
-
- COL_NAME (object ID #, column ID #) The column name
-
- DB_ID (["database name"]) The database ID #
-
- DB_NAME ([database ID #]) The database name
- Function Parameters Result
- ────────────────────────────────────────────────────────────────────────────
- DB_NAME ([database ID #]) The database name
-
- HOST_ID ( ) The workstation ID #
-
- HOST_NAME ( ) The workstation name
-
- INDEX_COL ("object name", index ID #, The indexed column name
- key #)
-
- ISNULL (expression, value) NULL entries with the
- specified value
-
- OBJECT_ID ("database object name") The database object ID #
-
- OBJECT_NAME (database object ID #) The database object name
-
- SUSER_ID (["server username"]) The user's login ID #
-
- SUSER_NAME ([server user ID #]) The user's login ID
- Function Parameters Result
- ────────────────────────────────────────────────────────────────────────────
- SUSER_NAME ([server user ID #]) The user's login ID
-
- USER_ID (["username"]) The user's database ID number
-
- USER_NAME ([user ID number]) The username
-
- ────────────────────────────────────────────────────────────────────────────
-
-
-
-
- Examples
-
- A. select user_id("harold")
-
- Example A returns harold's ID #, 13.
-
- B. select user_name(13)
-
- Example B returns the login ID for user #13, harold
-
- C. select avg(isnull(price, $10.00))
- from titles
-
- Example C finds the average of the prices of all titles, substituting the
- value $10.00 for all NULL entries in price.
-
- D. select isnull(price, 0)
- from titles
-
- Example D finds all rows with null values in price and displays the null
- value as "0".
-
-
- Comments
-
- When the parameter to a system function is optional, the current database,
- host computer, server user, or database user is assumed. Built-in functions
- must always be followed by parentheses.
-
- The system functions can be used in the select list, in the WHERE clause,
- and anywhere an expression is allowed.
-
- The System Administrator's server user ID is always 1.
-
- Server user ID -1 is always reserved for a guest account.
-
- The user ID of the Database Owner is always 1.
-
- The USER_NAME function returns the name of the current user if the parameter
- is less than zero.
-
-
- See Also
-
- Functions, SELECT
-
-
- System Procedures
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Stored procedures that SQL Server supplies to update and report from the
- system tables.
-
-
- Comments
-
- Chapter 2 of this manual contains a complete explanation of each system
- procedure.
-
- System procedures are created in the master database. They are owned by the
- master Database Owner.
-
- Since system procedures are located in the master database, their
- permissions are also set there. In other words, the System Administrator or
- master Database Owner must set up permissions for the system procedures in
- the master database, not from user databases.
-
- You can run system procedures from any database. If a system procedure is
- executed from a database other than master, any references to system tables
- are mapped to the database from which the procedure is being run. For
- example, if the Database Owner of pubs runs sp_adduser from pubs, the new
- user is added to pubs..sysusers.
-
- The names of all system procedures begin with "sp_".
-
- You can create your own system procedures that can be executed from any
- database. Simply create a stored procedure in master and give it a name that
- begins with "sp_".
-
- System procedures (for example, sp_help) do not work on temporary tables
- because a procedure cannot access a temporary object unless it created the
- object itself during the current session.
-
- Some of the system procedures can be run only by Database Owners. These
- procedures make sure that the user executing the procedure is the owner of
- the database from which they are being executed.
-
- Other system procedures can be executed by any user who has been granted
- EXECUTE permission on them, but this permission must be granted in master.
- Therefore, a user can either have permission to execute a system procedure
- in all databases or in none of them.
-
- Authorized SQL Server users (those who have a login ID) who are not listed
- in master..sysusers are treated as guest in master. The guest user inherits
- the permissions granted to public (in the setup program), including
- permission to execute certain system procedures (for example, all the
- sp_help procedures).
-
- To deny a user permission on a system procedure, the System Administrator or
- master Database Owner must add him or her to master..sysusers and write a
- REVOKE statement on that procedure. Thus, the owner of a user database
- cannot directly control permissions on the system procedures within his or
- her own database.
-
- When the parameter value for a system procedure contains punctuation marks
- or embedded blanks, it must be enclosed in single or double quotation marks.
- When the parameter is an object name and the object name is qualified by a
- database name or owner name, the entire name must be enclosed in single or
- double quotation marks.
-
- Several system procedure tables in the master database are used by the
- system procedures to convert internal system values (for example, status
- bits) into readable English. One of them, spt_values, is used by a wide
- variety of system procedures: sp_configure, sp_dboption, sp_depends,
- sp_help, sp_helpdb, sp_helpdevice, sp_helpindex, sp_helpkey, sp_helprotect,
- and sp_lock. The table spt_values is never updated. To see how it is used,
- execute sp_helptext to look at the text for one of the system procedures
- that references it. The other system procedure tables are spt_monitor and
- spt_committab. In addition, several of the system procedures create and then
- drop temporary tables: sp_helpdb creates #spdbdesc, sp_helpdevice creates
- #spdevtab, and sp_helpindex creates #spindtab.
-
- See Chapter 2, "System Procedures," for a complete description of the system
- procedures.
-
-
- See Also
-
- CREATE PROCEDURE, EXECUTE
-
-
-
-
-
- Text/Image Datatypes
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- The text datatype stores extremely long (up to 231- 1 or 2,147,483,647) byte
- strings of printable characters.
-
- The image datatype stores extremely long (up to 231- 1 or 2,147,483,647)
- bytes of hexadecimal-encoded binary data.
-
-
- Syntax
-
- The data values for a column of type text or image are stored and managed as
- a linked list of data pages, but they appear to the user as if they were
- stored in a table row. A text or image datatype definition does not include
- a length.
-
- column_name {text | image}
-
-
- Examples
-
- A. create table texttest
- (title_id varchar(6), blurb text, pub_id char(4))
-
- B. insert texttest values
- ("BU7832", "Straight Talk About Computers is an annotated
- analysis of what computers can do for you: a no-hype guide
- for the critical user.", "1389")
-
- C. create table imagetest
- (image_id varchar(6), imagecol image, graphic_id char(4))
-
- D. insert imagetest values
- ("94732", 0xFFFF1111222223333444445555566666FFFFF, "1389")
-
- E. select blurb from texttest
- where blurb like "Straight Talk%"
-
-
- Comments
-
- When you initialize a text or image column with an INSERT, UPDATE, or
- WRITETEXT, SQL Server assigns a text pointer and allocates an entire data
- page, 2K bytes, to hold the text or image value.
-
- Text values, like char and varchar values, require quotation marks in an
- INSERT statement.
-
- SELECT statements returning text and image values return all the data, up to
- the limit specified in the global variable @TEXTSIZE. The SET TEXTSIZE
- statement is used to change this value. The initial value of @TEXTSIZE is
- 32K; the maximum value for @TEXTSIZE is 231- 1 (that is, 2,147,483,647).
-
- You can explicitly convert text values to char or varchar with the CONVERT
- function, but you are limited to the maximum length of these datatypes, 255
- bytes. If you do not specify a length, the converted value has a default
- length of 30 characters. Implicit conversion is not supported.
-
- Text and image values are stored on a linked list of data pages. A text or
- image column in a table contains a pointer to the first data page or value
- fragment for that entry, and thus to the entire text or image value.
-
- Image values, like binary and varbinary values, must be preceded by "0x" for
- an INSERT statement.
-
- You can explicitly convert image values to binary or varbinary with the
- CONVERT function, but you are limited to the maximum length of these
- datatypes, 255 bytes. If you do not specify a length, the converted value
- has a default length of 30 bytes. Implicit conversion is not supported.
-
- There are a number of restrictions on the use of text and image columns.
- They cannot be used under the following conditions:
-
-
- ■ As parameters to stored procedures. It is also illegal to pass text or
- image values to stored procedures.
-
- ■ As local variables.
-
- ■ In an ORDER BY clause.
-
- ■ In a COMPUTE clause.
-
- ■ In a GROUP BY clause.
-
- ■ In an index.
-
- ■ In a search clause (WHERE clause) except with the LIKE expression.
-
- ■ In a join clause.
-
-
- Use the LIKE expression to search for a text pattern.
-
- Use the PATINDEX function to search for the starting position of the first
- occurrence of a specified pattern in a text column.
-
-
- See Also
-
- Datatypes, Functions, READTEXT, Text/Image Functions, WRITETEXT
-
-
- Text/Image Functions
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Return values commonly needed for operations on text and image data. Text
- and image built-in function names are not keywords.
-
-
- Syntax
-
- function_name(parameter)
-
- Function names, parameters, and results are listed in the following table.
-
-
- ╓┌─────────────┌──────────────────────────────┌──────────────────────────────╖
- Function Parameters Result
- ────────────────────────────────────────────────────────────────────────────
- PATINDEX ("pattern", column_name) The starting position of the
- first occurrence of pattern
- in the specified column. You
- can use wildcard characters
- in pattern.
-
- SET TEXTSIZE {n 0} The limit, in bytes, of the
- text or image data to be
- returned with a SELECT
- statement. The current
- setting is stored in the
- @TEXTSIZE global variable. n
- is an integer that specifies
- the limit on the number of
- bytes to be returned. 0
- restores the default limit
- (32K bytes.)
- Function Parameters Result
- ────────────────────────────────────────────────────────────────────────────
- (32K bytes.)
-
-
-
- TEXTPTR (column_name) The text pointer value in
- varbinary format. The text
- pointer is checked to ensure
- that it points to the first
- text page.
-
- TEXTVALID ("table_name.column_name", Checks if a given text
- text_ptr) pointer is valid and returns
- 1 if the pointer is valid and
- 0 if the pointer is invalid.
- Note that the identifier for
- the text column must include
- the table name.
-
- ────────────────────────────────────────────────────────────────────────────
- Function Parameters Result
- ────────────────────────────────────────────────────────────────────────────
- ────────────────────────────────────────────────────────────────────────────
-
-
-
-
- Examples
-
- A. declare @val varbinary(30)
- select @val = textptr(blurb) from texttest
- where title_id = "BU7832"
- readtext texttest.blurb @val 1 5
-
- Example A uses the TEXTPTR function to locate the text column, blurb,
- associated with title_id BU7832 in the texttest table. The text pointer is
- put into a local variable @val and supplied as a parameter to the READTEXT
- statement, which returns 5 bytes starting at the second byte (offset of 1).
-
-
- B. set textsize 100
-
- C. select title_id, textptr(blurb) from texttest
-
- D. select textvalid ("texttest.blurb", textptr(blurb))
- from texttest
-
-
- Comments
-
- "SELECT textptr(column_name) from my_table" returns a long binary string. It
- is a good idea to put this string into a local variable, as in the first
- example, and use it by reference.
-
- Explicit conversion is supported from text to char, and image to binary and
- varbinary, but you are limited to the maximum length for these datatypes,
- 255 bytes. If you do not specify a length, the default value of 30 bytes is
- used. Implicit conversion of text or image to another datatype is not
- supported.
-
- You cannot create an index on a text or image column.
-
- A text value cannot appear in a search clause or join clause, except in
- WHERE clauses using LIKE.
-
- A text value cannot be a local variable or a parameter to a stored
- procedure. It is also illegal to pass text values to stored procedures.
-
- ORDER BY cannot be specified on text type columns.
-
-
- See Also
-
- Conversion Function, Functions, Mathematical Functions, READTEXT, String
- Functions, Text/Image Datatypes
-
-
- TRUNCATE TABLE
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- This example removes all rows in a table as quickly as possible.
-
-
- Syntax
-
- TRUNCATE TABLE [[database.]owner.]table_name
-
-
- Examples
-
- truncate table authors
-
- This example removes all data in the authors table.
-
-
- Comments
-
- TRUNCATE TABLE restores the database to the same state it would be in if the
- CREATE TABLE and CREATE INDEX statements had been run on the table.
-
- The table, though empty of data, continues to exist until you give a DROP
- TABLE statement.
-
- TRUNCATE TABLE and DELETE without any conditions are functionally
- equivalent, but TRUNCATE TABLE is faster. TRUNCATE TABLE removes whole data
- pages and is not logged; DELETE removes rows one at a time and logs these
- transactions. Both DELETE and TRUNCATE TABLE reclaim the space occupied by
- the data and its associated indexes.
-
- A TRUNCATE TABLE statement is not caught by a DELETE trigger. Although a
- TRUNCATE TABLE statement is, in effect, like a DELETE without a WHERE clause
- (it removes all rows), it is not logged, and therefore cannot "fire" a
- trigger.
-
- Since permission for the TRUNCATE TABLE statement defaults to the table
- owner and is not transferable, only the table owner need worry about
- inadvertently circumventing a DELETE trigger with a TRUNCATE TABLE
- statement.
-
- TRUNCATE TABLE permission defaults to the table owner and is not
- transferable.
-
-
- See Also
-
- DELETE, DROP TABLE
-
-
- UPDATE
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Changes data in existing rows, either by adding new data or modifying
- existing data.
-
-
- Syntax
-
- UPDATE [[database.]owner.]{table_name | view_name}
- SET [[[database.]owner.]{table_name. | view_name.}]
- column_name1 = {expression1 | NULL}
- [, column_name2 = {expression2 | NULL}...]
- [WHERE search_conditions]
-
- UPDATE [[database.]owner.]{table_name | view_name}
- SET [[[database.]owner.]{table_name. | view_name.}]
- column_name1 = {expression1 | NULL}
- [, column_name2 = {expression2 | NULL}...]
- [FROM [[database.]owner.]{table_name | view_name}
- [, [[database.]owner.]{table_name | view_name}]...]
- [WHERE search_conditions]
-
-
- Examples
-
- A. update authors
- set au_lname = "MacBadden"
- where au_lname = "McBadden"
-
- Example A changes all the McBaddens in the authors table to MacBaddens.
-
- B. update titles
- set ytd_sales = ytd_sales + qty
- from titles, sales
- where titles.title_id = sales.title_id
- and sales.date in (select max(sales.date) from sales)
-
- Example B modifies ytd_sales column to reflect the most recent sales
- recorded in the sales table. This assumes that only one set of sales is
- recorded for a given title on a given date and that updates are up-to-date.
-
-
-
- Options
-
- SET
- Specifies the value for a particular column name. The value can be an
- expression or a null value. When more than one column name and value pair
- is listed, they must be separated by commas.
-
- FROM
- Is required to pull data from other tables or views to modify rows in the
- table or view specified in the UPDATE clause. A standard FROM clause lists
- the tables and views referenced in the WHERE clause.
-
- WHERE
- A standard WHERE clause.
-
-
- Comments
-
- Use UPDATE to change values in rows that have already been inserted. Use
- INSERT to add full or partial new rows.
-
- UPDATE interacts with the IGNORE_DUP_KEY, IGNORE_DUP_ROW, and ALLOW_DUP_ROW
- statements set with the CREATE INDEX statement. (See "CREATE INDEX" for more
- information.)
-
- A rule can be created and bound to a column to restrict the domain of legal
- values that can be entered into it. Rules are created with CREATE RULE and
- bound with the sp_bindrule system procedure.
-
- You can define a trigger that takes a specified action when an UPDATE
- statement is executed on a specified table or on a specified column of a
- table.
-
-
- Permissions
-
- UPDATE permission defaults to the table or view owner, who can transfer it
- to other users.
-
-
- See Also
-
- CREATE INDEX, CREATE RULE, CREATE TRIGGER, INSERT, WHERE Clause,
- sp_bindefault, sp_bindrule, sp_unbindefault, sp_unbindrule
-
-
- UPDATE STATISTICS
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Updates information about the distribution of key values in specified
- indexes.
-
-
- Syntax
-
- UPDATE STATISTICS table_name [[database.]owner.][index_name]
-
-
- Examples
-
- A. update statistics authors
-
- B. update statistics authors au_id_ind
-
-
- Comments
-
- SQL Server keeps statistics about the distribution of the key values in each
- index and uses these statistics in its decisions about which index(es) to
- use in query processing. Use the UPDATE STATISTICS statement when you create
- an index on already existing data or if a great deal of data in an indexed
- column has been added, changed, or removed (that is, if you suspect that the
- distribution of key values has changed).
-
- If you do not specify an index name, the statement updates the distribution
- statistics for all the indexes in the specified table.
-
- 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.
-
-
- Permissions
-
- UPDATE STATISTICS permission defaults to the table owner and is not
- transferable.
-
-
- See Also
-
- CREATE INDEX, sp_helpindex
-
-
- USE
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Changes the current database.
-
-
- Syntax
-
- USE database_name
-
-
- Examples
-
- use pubs
-
- This example changes the current database to pubs.
-
-
- Comments
-
- USE must be in a batch by itself for you to reference objects in that
- database.
-
- An alias permits a user to use a database by an alias name. Use the
- sp_addalias system procedure.
-
-
- Permissions
-
- Permission for the USE statement is assigned when the Database Owner assigns
- permission by executing the sp_adduser system procedure.
-
-
- See Also
-
- CREATE DATABASE, DROP DATABASE, sp_addalias, sp_adduser, sp_defaultdb
-
-
- Variables (Local and Global)
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Defined entities that are assigned values. A local variable is defined with
- a DECLARE statement and assigned an initial value within the statement batch
- where it is declared with a SELECT statement. Global variables are
- predefined.
-
-
- Syntax
-
- Local variable declaration:
-
- DECLARE @variable_name datatype
- [, @variable_name datatype...]
-
- Assignment of values to a local variable:
-
- SELECT @variable_name = expression [, @variable_name = expression...]
- [FROM clause] [WHERE clause]
- [GROUP BY clause] [HAVING clause]
- [ORDER BY clause] [COMPUTE clause]
-
-
- Examples
-
- A. declare @veryhigh money
- select @veryhigh = max(price)
- from titles
- if @veryhigh > $20
- print "Ouch!"
-
- B. declare @one varchar(18), @two varchar(18)
- select @one = "this is one", @two = "this is two"
- if @one = "this is one"
- print "you got one"
- if @two = "this is two"
- print "you got two"
- else print "nope"
-
-
- Options
-
- @variable_name
- The name of a variable. Variable names must be preceded by the "at" symbol
- (@). The variable name conforms to the rules for identifiers except that
- it can contain only 29 characters. Variables can be used only in place of
- constants. They cannot be used in place of the names of tables, columns,
- other database objects, or keywords.
-
- datatype
- A system datatype or a user datatype.
-
-
- Comments
-
- Variables cannot be of the text or image datatype.
-
- Local variables are declared in the body of a procedure or query with the
- DECLARE keyword and given values with a SELECT statement.
-
- The "@" denotes a local variable name.
-
- Local variables are often used in a batch or procedure as counters for WHILE
- loops or IF...ELSE blocks.
-
- The SELECT statement that assigns a value to the local variable usually
- returns a single value. If the SELECT variable assignment statement returns
- more than one value, the variable is assigned the last value returned.
-
- The SELECT statement that assigns values to variables cannot be used to
- retrieve data. For example, the following is not legal:
-
- /* ILLEGAL STATEMENT
- ** declare @veryhigh money
- ** select @veryhigh = max(price), title_id
- ** from titles */
-
- In addition to local variables, there are predefined global variables that
- can be used without being declared. Global variables are distinguished from
- local variables by having two @ signs preceding their names, for example,
- @ERROR, @ROWCOUNT. Many of the global variables report on system activity.
- Their reports refer to activity since the last time SQL Server was started.
- The global variables are as follows:
-
- @@CONNECTIONS
- The number of logins or attempted logins since SQL Server was last
- started.
-
- @@CPU_BUSY
- The amount of time, in ticks, that the CPU has spent doing SQL Server work
- since the last time SQL Server was started.
-
- @@ERROR
- The last error number generated by the system.
-
- @@IDLE
- The amount of time, in ticks, that SQL Server has been idle since it was
- last started.
-
- @@IO_BUSY
- The amount of time, in ticks, that SQL Server has spent doing input and
- output operations since it was last started.
-
- @@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.
-
- @@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.
-
- @@PACK_RECEIVED
- The number of input packets read by SQL Server since it was last started.
-
- @@PACKET_ERRORS
- The number of errors that have occurred while SQL Server was sending and
- receiving packets.
-
- @@PACK_SENT
- The number of output packets written by SQL Server since it was last
- started.
-
- @@PROCID
- The stored procedure ID of the currently executing procedure.
-
- @@ROWCOUNT
- The number of rows affected by the last statement (includes SELECT,
- INSERT, UPDATE, DELETE, the CREATE statements, and so on).
-
- @@TEXTSIZE
- The current value of the TEXTSIZE option of the SET statement, which
- specifies the length in bytes of text to be returned with a SELECT
- statement.
-
- @@TIMETICKS
- The number of microseconds per tick. The amount of time per tick is
- machine dependent. Each tick on the operating system is 21.25 milliseconds
- (1/32 second).
-
- @@TOTAL_ERRORS
- The number of errors that have occurred while SQL Server was reading or
- writing.
-
- @@TOTAL_READ
- The number of disk reads by SQL Server since it was last started (this
- includes disk reads only, not cache reads).
-
- @@TOTAL_WRITE
- The number of writes by SQL Server since it was last started.
-
- @@TRANCOUNT
- The number of currently active transactions for the current user.
-
- @@VERSION
- The date of the current version of SQL Server.
-
- 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" causes an exit if an error had occurred.
-
- For information on the contents of many of these global variables, execute
- the sp_monitor system procedure. See Chapter 2, "System Procedures," for
- details.
-
-
- See Also
-
- DECLARE, Datatypes, PRINT, RAISERROR, sp_monitor
-
-
- Views
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Provide an alternate way of looking at data in one or more tables.
-
-
- Syntax
-
- CREATE VIEW [owner.]view_name
- [(column_name [, column_name]...)]
- AS SELECT_statement
-
-
- Comments
-
- See "CREATE VIEW" for syntax, examples, explanations of keywords, and
- comments on creating a view.
-
- You cannot create a trigger on a view.
-
- If a view depends on a table (or view) that has been dropped, SQL Server
- produces an error message if anyone tries to use the view. If a new table
- (or view) is created to replace the one that has been dropped, the view
- becomes usable again.
-
- There are no restrictions on querying through views, but there are some
- restrictions on data update through views.
-
- Data update statements may not change any column in the view that is a
- computation.
-
- Data update statements referring to a view that includes aggregate functions
- (a built-in function and a GROUP BY or COMPUTE BY clause) are not allowed.
- INSERT statements are not allowed unless all NOT NULL columns in the
- underlying table or view are included in the view through which you are
- inserting new rows. (SQL Server has no way to supply values for NOT NULL
- columns in the underlying table or view.) INSERT and UPDATE statements are
- not allowed unless the columns being updated all belong to the same base
- table. (It's illegal in SQL to use data update statements on more than one
- table in a single statement.) However, if a view contains columns from more
- than one table but the data update statement references columns from only
- one of the tables, the statement is legal.
-
- When you query through a view, SQL Server checks to make sure that all the
- database objects referenced anywhere in the statement exist, that they are
- valid in the context of the statement, and that data update statements do
- not violate data integrity rules. If any of these checks fail, you get an
- error message. If the checks are successful, it "translates" the view into
- an action on the underlying table(s).
-
-
- Permissions
-
- You can use views as security mechanisms by granting permission on a view
- but not on one or more of its underlying tables.
-
-
- See Also
-
- CREATE VIEW, DROP VIEW, sp_depends, sp_help, sp_helptext, sp_rename
-
-
- WAITFOR
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Specifies a specific time, a time interval, or an event for the execution of
- a statement block, stored procedure, or transaction.
-
-
- Syntax
-
- WAITFOR {DELAY "time" | TIME "time" | ERROREXIT | PROCESSEXIT}
-
-
- Examples
-
- A. begin
- waitfor time "14:20"
- insert chess(next_move)
- values('Q-KR5')
- execute sendmail 'judy'
- end
-
- At 2:20 p.m., the chess table will be updated with my next move, and a
- procedure called sendmail will insert a row in a table owned by Judy and
- notifies her that a new move now exists in the chess table.
-
- B. begin
- waitfor delay "00:00:10"
- print "Ten seconds have passed. Your time is up."
- end
-
-
- Options
-
- DELAY
- Instructs SQL Server to wait until the specified amount of time has
- passed, up to a maximum of 24 hours.
-
- TIME
- Instructs SQL Server to wait until the specified time.
-
- time
- A time in one of the acceptable formats for datetime data. You cannot
- specify dates─the date portion of the datetime value is not allowed.
-
- ERROREXIT
- Instructs SQL Server to wait until a kernel or user process terminates
- abnormally.
-
- PROCESSEXIT
- Instructs SQL Server to wait until a kernel or user process terminates for
- any reason.
-
-
- Comments
-
- After executing the WAITFOR statement, you cannot use your connection to SQL
- Server until the time or event that you specified occurs.
-
- You can use WAITFOR ERROREXIT with a procedure that kills the abnormally
- terminated process to free system resources that would otherwise be taken up
- by an infected process.
-
- To find out which process terminated, check the sysprocesses table with the
- sp_who system procedure.
-
- The time you specify with WAITFOR TIME or WAITFOR DELAY can include hours,
- minutes, and seconds. Use the format "hh:mi:ss", as described in
- "Datatypes."
-
- For example, WAITFOR TIME "16:23" instructs SQL Server to wait for 4:23 pm.
- The statement WAITFOR DELAY "01:30" instructs SQL Server to wait 1 hour and
- 30 minutes.
-
- For details on acceptable time formats, see "Datatypes."
-
-
- See Also
-
- BEGIN...END, Datatypes, sp_who
-
-
- WHERE Clause
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Sets the conditions in a WHERE clause. (Joins and subqueries are specified
- in the search conditions; see the "Joins" and "Subqueries" sections for full
- details.)
-
-
- Syntax
-
- Search conditions immediately follow the keywords WHERE or HAVING in a
- SELECT, INSERT, UPDATE, or DELETE statement. (HAVING search conditions
- differ from WHERE search conditions only in that aggregate functions are not
- allowed in WHERE conditions.) If you use more than one of the search
- conditions in a single statement, connect the conditions with AND or OR.
-
- WHERE [NOT] expression comparison_operator expression
- WHERE [NOT] column_name [NOT] LIKE "match_string"
- WHERE [NOT] column_name IS [NOT] NULL
- WHERE [NOT] expression [NOT] BETWEEN expression AND expression
- WHERE [NOT] expression [NOT] IN ({value_list | subquery})
- WHERE [NOT] EXISTS (subquery)
- WHERE [NOT] expression comparison_operator {ANY | ALL} (subquery)
- WHERE [NOT] column_name join_operator column_name
- WHERE [NOT] boolean_expression
- WHERE [NOT] expression {AND | OR} [NOT] expression
-
-
- Examples
-
- A. where advance * $2 > ytd_sales * price
-
- B. where phone not like '415%'
-
- Example B finds all the rows in which the phone number does not begin with
- 415.
-
- C. where au_lname like "[CK]ars[eo]n"
-
- Example C finds the rows for authors named Carson, Carsen, Karsen, and
- Karson.
-
- D. where advance < $5000 or advance is null
-
- E. where (type = "business" or type = "psychology")
- and advance > $5500
-
- F. where ytd_sales between 4095 and 12000
-
- G. where state in ('CA', 'IN', 'MD')
-
- Example G finds the rows in which the state is one of the three in the list.
-
-
-
- Options
-
- expression
- A column name; a constant; a function; any combination of column names,
- constants, and functions connected by arithmetic or bitwise operators; or
- a subquery. The arithmetic operators are as follows:
-
- Symbol Meaning
- ────────────────────────────────────────────────────────────────────────────
- + Addition
- - Subtraction
- * Multiplication
- / Division
- % Modulo
-
- ────────────────────────────────────────────────────────────────────────────
-
-
- Addition, subtraction, division, and multiplication can be used on int,
- smallint, tinyint, float, and money columns. The modulo operator cannot be
- used with money or float columns. A modulo is the integer remainder after
- a division involving two integers. For example, 21 % 9 = 3 because 21
- divided by 9 equals 2 with a remainder of 3. The bitwise operators are as
- follows:
-
- Symbol Meaning
- ────────────────────────────────────────────────────────────────────────────
- & Bitwise and (two operands)
- | Bitwise or (two operands)
- ^ Bitwise exclusive or (two operands)
- ~ Bitwise not (one operand)
-
- ────────────────────────────────────────────────────────────────────────────
-
-
- The bitwise operators can be used on int, smallint, and tinyint columns
- only. All the bitwise operators translate the integer parameters into
- binary representation before evaluating them. (See "Expressions" for more
- information.)
-
- comparison_operator
- One of the following:
-
- Symbol Meaning
- ────────────────────────────────────────────────────────────────────────────
- = Equal to
- > Greater than
- < Less than
- >= Greater than or equal to
- <= Less than or equal to
- != Not equal to
- !> Not greater than
- !< Not less than
-
- ────────────────────────────────────────────────────────────────────────────
-
-
- In comparing char and varchar data, < means closer to the beginning of the
- alphabet and > means closer to the end of the alphabet. Case and special
- character evaluations depend on the collating sequence of the operating
- system on the machine on which SQL Server is located. On ASCII machines,
- for example, lowercase letters are greater than uppercase letters, and
- uppercase letters are greater than numbers. Trailing blanks are ignored
- for the purposes of comparison. So, for example, "Dirk" is the same as
- "Dirk ". In comparing dates, < means earlier and > means later. Put
- quotation marks around all character and datetime data used with a
- comparison operator. For example, = "Bennet", > "94609". (See
- "Datatypes.")
-
- column_name
- The name of a column used in the comparison. Qualify the column name with
- its table or view name if there is any ambiguity.
-
- NOT
- Negates any boolean expression and keywords, such as LIKE, NULL, BETWEEN,
- IN, and EXISTS.
-
- LIKE
- Indicates that the following character string (enclosed by single or
- double quotation marks) is a matching pattern. LIKE is available for char,
- varchar, and datetime columns (but not to search for seconds or
- milliseconds). You can use the LIKE keyword and wildcard characters with
- datetime data as well as with char and varchar. When you use LIKE with
- datetime values, SQL Server converts the dates to the standard datetime
- format and then to varchar. Since the standard storage format doesn't
- include seconds or milliseconds, you cannot search for seconds or
- milliseconds with LIKE and a pattern. It is a good idea to use LIKE when
- you search for datetime values, since datetime entries can contain a
- variety of date parts. For example, if you insert the value "9:20" into a
- column named arrival_time, the clause WHERE arrival_time = "9:20" would
- not find it because SQL Server converts the entry into "Jan 1, 1900
- 9:20AM." However, the clause WHERE arrival_time LIKE "%9:20%" would find
- it.
-
- match_string
- A string of characters and wildcards enclosed in quotation marks. For
- complete information, see "Wildcard Characters." The wildcards are as
- follows:
-
- Symbol Meaning
- ────────────────────────────────────────────────────────────────────────────
- % Any string of 0 or more characters
-
- _ (underscore) Any single character
-
- [ ] Any single character within the
- specified range ([a-f]) or set ([abcdef])
-
- [^] Any single character not within the
- specified range ([^a-f]) or set
- ([^abcdef])
-
- ────────────────────────────────────────────────────────────────────────────
-
-
- IS NULL
- Searches for null values. (=NULL is allowed in UPDATE statements. Outside
- of this one exception, NULL returns only NULL when used with arithmetic,
- bitwise, or comparison operators. NULL is essentially useless as an
- operand with any of these operators.)
-
- BETWEEN
- The range-start keyword. Use AND for the range-end value. A range of
- BETWEEN x AND y, unlike a range of > x < y, is inclusive.
-
- IN
- Allows you to select values that match any one of a list of values. The
- comparator can be a constant or a column name, and the list can be a set
- of constants or, more commonly, a subquery. (See "Subqueries" for
- information on using IN with a subquery.) Enclose the list of values in
- parentheses.
-
- value_list
- A list of values. Put single or double quotation marks around character
- values, and separate each value from the following one with a comma. (See
- example E, earlier in this section.)
-
- EXISTS
- Is used with a subquery to test for the existence of some result from the
- subquery. (See "Subqueries" for more information.)
-
- subquery
- A restricted SELECT statement (ORDER BY and COMPUTE clauses and the INTO
- keyword are not allowed) inside the WHERE or HAVING clause of a SELECT,
- INSERT, DELETE, UPDATE, or subquery. (See "Subqueries" for more
- information.)
-
- ANY
- Is used with >, <, or = and a subquery. It returns results when any value
- retrieved in the subquery matches the value in the WHERE or HAVING clause
- of the outer statement. (See "Subqueries" for more information.)
-
- ALL
- Is used with > or < and a subquery. It returns results when all values
- retrieved in the subquery match the value in the WHERE or HAVING clause of
- the outer statement. (See "Subqueries" for more information.)
-
- join_operator
- A comparison operator, =*, or *= . (See "Joins" for more information.)
-
- boolean_expression
- An expression that returns true or false. (See "Expressions" for a full
- definition.)
-
- AND
- Joins two conditions and returns results when both of the conditions are
- true. When more than one logical operator is used in a statement, AND
- operators are normally evaluated first. However, you can change the order
- of execution with parentheses.
-
- OR
- Joins two conditions and returns results when either of the conditions is
- true. When more than one logical operator is used in a statement, OR
- operators are normally evaluated after AND operators. However, you can
- change the order of execution with parentheses.
-
-
- Comments
-
- WHERE and HAVING search conditions are identical, except that aggregate
- functions are not permitted in WHERE clauses ("HAVING avg(price) > 20" is
- legal; "WHERE avg(price) > 20" is not). See "Aggregate Functions" for
- information on the use of aggregate functions.
-
- If there are columns in the select list that neither have aggregate
- functions applied to them nor are included in the query's GROUP BY clause
- (illegal in standard SQL), the meanings of HAVING and WHERE are somewhat
- different.
-
- In this situation, a WHERE clause restricts the rows that are included in
- the calculation of the aggregate function but does not restrict the rows
- returned by the query. Conversely, a HAVING clause restricts the rows
- returned by the query but does not affect the calculation of the aggregate
- function. See "GROUP BY and HAVING Clauses" for examples.
-
- There are two ways to specify literal quotation marks within a char or
- varchar entry. The first method is to use two quotation marks. For example,
- if you have begun a character entry with a single quotation mark and wish to
- include a single quotation mark as part of the entry, use two single
- quotation marks:
-
- 'I don"t understand.'
-
- With double quotation marks:
-
- "He said, ""It's not really confusing."""
-
- The second method is to enclose a quote in the opposite kind of quotation
- mark. In other words, surround an entry containing a double quotation mark
- with single quotation marks (or vice versa). Here are some examples:
-
- 'George said, "There must be a better way."'
- "Isn't there a better way?"
- 'George asked, "Isn"t there a better way?"'
-
- To enter a character string longer than the width of your screen, enter a
- backslash (\) before going to the next line.
-
-
- See Also
-
- Datatypes, DELETE, EXECUTE, Expressions, Functions, INSERT, Joins, Search
- Conditions, SELECT, Subqueries, UPDATE, Wildcard Characters, sp_helpjoins
-
-
- WHILE
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Sets a condition for the repeated execution of a statement or statement
- block. The statement(s) is executed repeatedly as long as the specified
- condition is true.
-
-
- Syntax
-
- WHILE
- boolean_expression
- statement
-
-
- Examples
-
- while (select avg(price) from titles) < $30
- begin
- update titles
- set price = price * $2
- select max(price) from titles
- if (select max(price) from titles) > $50
- break
- else
- continue
- end
- begin
- select title_id, price from titles
- print "Too much for the market to bear"
- end
-
- If the average price is less than $30, double the prices. Then select the
- maximum price. If it is less than or equal to $50, restart the WHILE loop
- and double the prices again. If the maximum price is more than $50, exit the
- WHILE loop, select the title_ids and the too-high prices, and print a
- message.
-
-
- Comments
-
- The execution of statements in the WHILE loop can be controlled from inside
- the loop with the BREAK and CONTINUE statements.
-
- CONTINUE causes the WHILE loop to restart, skipping any statements after
- CONTINUE. BREAK causes an exit from the WHILE loop, and any statements that
- appear after the END keyword that marks the end of the loop are executed.
- BREAK and CONTINUE are often (but not always) activated by IF tests.
-
- If two or more WHILE loops are nested, BREAK exits to the next outermost
- loop. First all the statements after the end of the inner loop run, and then
- the next outermost loop restarts.
-
-
- See Also
-
- BEGIN...END, BREAK, CONTINUE, CREATE PROCEDURE, GOTO
-
-
- Wildcard Characters
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Used with the LIKE keyword to represent any character in a string when
- searching for a char, varchar, or datetime value.
-
-
- Syntax
-
- {WHERE | HAVING} [NOT] expression [NOT] LIKE "string"
-
- The string can include these wildcard characters:
-
- Wildcard Meaning
- ────────────────────────────────────────────────────────────────────────────
- % Any string of 0 or more characters
-
- _ (underscore) Any single character
-
- [ ] Any single character within the
- specified range ([a-f]) or set ([abcdef])
-
- [^] Any single character not within the
- specified range ([^a-f]) or set
- ([^abcdef])
-
- ────────────────────────────────────────────────────────────────────────────
-
-
-
- Examples
-
- A. select phone
- from authors
- where phone like "415%"
-
- Example A finds all the phone numbers in the authors table that begin with
- the 415 area code.
-
- B. select phone
- from authors
- where phone not like "415%"
-
- select phone
- from authors
- where not phone like "415%"
-
- These two queries are equivalent: they find all the phone numbers in the
- authors table that do not begin with the 415 area code.
-
- C. select au_lname
- from authors
- where au_lname like "%en%"
-
- Example C finds names that have the characters "en" in them (Bennet, Green,
- McBadden).
-
- D. select au_fname
- from authors
- where au_fname like "_heryl"
-
- Example D finds six-letter names that end with "heryl" (Cheryl).
-
- E. select au_lname
- from authors
- where au_lname like "[M-Z]inger"
-
- Example E finds names ending with "inger" and beginning with any single
- character between "M" and "Z".
-
- F. select au_lname
- from authors
- where au_lname like "[dD]eFrance"
-
- Example F finds both DeFrance and deFrance.
-
- G. select au_lname
- from authors
- where au_lname like "M[^c]%"
-
- Example G finds names beginning with "M" whose second letter is not "c".
-
-
- Comments
-
- The string with wildcard characters must always be enclosed by single or
- double quotation marks.
-
- LIKE and the wildcard characters can be used for searching char, varchar,
- and datetime columns (but not to search for seconds or milliseconds).
-
- Wildcards used without LIKE have no special meaning. For example, this query
- finds any phone numbers that start with the four characters "415%":
-
- select phone
- from authors
- where phone = "415%"
-
- You can use the LIKE keyword and wildcard characters with datetime data as
- well as with char and varchar. When you use LIKE with datetime values, SQL
- Server converts the dates to the standard datetime format and then to
- varchar. Since the standard storage format doesn't include seconds or
- milliseconds, you cannot search for seconds or milliseconds with LIKE and a
- pattern. It is a good idea to use LIKE when you search for datetime values,
- since datetime entries can contain a variety of date parts. For example, if
- you insert the value "9:20" into a column named arrival_time, the clause
- WHERE arrival_time = "9:20" would not find it because SQL Server converts
- the entry into "Jan 1, 1900 9:20AM". However, the clause WHERE arrival_time
- LIKE "%9:20%" would find it.
-
- To use %, _, [ ], or [^ ] as literal characters in a LIKE string rather than
- as wildcards, use square brackets around the percent sign, the underscore,
- and the open bracket. Use the close bracket by itself. Use the dash as the
- first character inside a set of square brackets.
-
- ╓┌─────────────────┌─────────────────────────────────────────────────────────╖
- Symbol Meaning
- ────────────────────────────────────────────────────────────────────────────
- LIKE "5%" 5 followed by any string of 0 or more characters
- LIKE "5[%]" 5%
- LIKE "_n" an, in, on, and so on
- LIKE "[_]n" _n
- LIKE "[a-cdf]" a, b, c, d, or f
- LIKE "[-acdf]" -, a, c, d, or f
- LIKE "[[]" [
- Symbol Meaning
- ────────────────────────────────────────────────────────────────────────────
- LIKE "[[]" [
- LIKE "]" ]
- ────────────────────────────────────────────────────────────────────────────
-
-
- You can't always duplicate NOT LIKE patterns with LIKE and the negative
- wildcard [^] because NOT LIKE finds the items that do not match the entire
- LIKE pattern, while LIKE with negative wildcards is evaluated one character
- at a time.
-
- For example, to see all the system tables in a database, use this query
- since all system tables begin with these three letters:
-
- select name
- from sysobjects
- where name LIKE "sys%"
-
- To see all the objects that are not system tables, use NOT LIKE "sys%". If
- you have a total of 32 objects and the LIKE finds 13 names that match the
- pattern, the NOT LIKE will find exactly the 19 objects that do not match the
- LIKE pattern.
-
- You won't always find the same names with a pattern such as LIKE
- "[^s][^y][^s]%". Instead of 19, you might get only 14, with all the names
- that begin with "s" or have "y" as the second letter or have "s" as the
- third letter eliminated from the results as well as the system table names.
- This is because matchstrings with negative wildcards are evaluated in steps,
- one wildcard at a time. If the match fails at any point in the evaluation,
- it is eliminated.
-
-
- See Also
-
- CREATE PROCEDURE, EXECUTE, Expressions, Search Conditions, WHERE Clause
-
-
- WRITETEXT
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Permits nonlogged, interactive updating of an existing text field.
-
-
- Syntax
-
- WRITETEXT [[database.]owner.]table_name.column_name text_ptr
- [WITH LOG] data
-
-
- Examples
-
- declare @val varbinary(30)
- select @val = textptr(blurb) from texttest
- where title_id = "BU7832"
- writetext texttest.blurb @val "hello world"
-
-
- Options
-
- table_name.column_name
- The name of the text column and the table name, which must be included.
- The database name and owner name are optional.
-
- WITH LOG
- Logs the inserted text or image data. This option aids media recovery, but
- text data quickly increases the size of the transaction log. Make sure
- that the transaction log resides in a separate database device. (See
- "sp_logdevice" in Chapter 2 and the SQL Server Administrator's Guide for
- details.)
-
-
- Comments
-
- By default, WRITETEXT is a nonlogged operation. This means that text or
- image data is not logged when it is written into the database. To use
- WRITETEXT in its default, nonlogged state, the System Administrator must use
- sp_dboption to set select into/bulkcopy. This permits the insertion of
- nonlogged data.
-
- WRITETEXT updates text data in an existing row. The update completely
- replaces existing text. For a valid text pointer to exist, a text column
- must contain either text data or a null value that has been explicitly
- entered with INSERT or UPDATE. Given a table textnull with columns key and
- x, where x is a text column that permits nulls:
-
- This insert assigns a valid text pointer:
-
- insert textnull
- values (1, null)
- go
-
- This insert does not assign a pointer:
-
- insert textnull (key)
- values (2)
- go
-
- You can update a null text column to get a valid text pointer or insert
- entirely new rows with INSERT (which is a logged operation) or bcp.
-
- The maximum length of text that can be inserted interactively with WRITETEXT
- is approximately 120K bytes for text data and 60K bytes for image data.
-
- You cannot use WRITETEXT on text and image columns in views.
-
-
- See Also
-
- READTEXT, Text/Image Datatypes, Text/Image Functions
-
-
-
-
-
-
- Chapter 2 System Procedures
- ────────────────────────────────────────────────────────────────────────────
-
- This chapter consists of reference pages, in alphabetical order, for system
- procedures (SQL-Server-supplied stored procedures). Note that system
- procedure names always begin with "sp_".
-
- Each system procedure and its function is listed below:
-
- ────────────────────────────────────────────────────────────────────────────
- sp_addalias
- Maps one user to another in a database.
-
- sp_addgroup
- Adds a group to a database.
-
- sp_addlogin
- Authorizes a new SQL Server user by adding an entry to
- master.dbo.syslogins.
-
- sp_addtype
- Creates a user-defined datatype.
-
- sp_addumpdevice
- Adds a dump device to SQL Server.
-
- sp_adduser
- Adds a new user to the current database.
-
- sp_bindefault
- Binds a default to a column or to a user-defined datatype.
-
- sp_bindrule
- Binds a rule to a column or user datatype.
-
- sp_changedbowner
- Changes the owner of a database.
-
- sp_changegroup
- Changes a user's group.
-
- sp_commonkey
- Defines a common key between two tables or views.
-
- sp_configure
- Displays or changes configuration options.
-
- sp_dboption
- Displays or changes database options.
-
- sp_defaultdb
- Changes a user's default database.
-
- sp_depends
- Displays information about database object dependencies.
-
- sp_diskdefault
- Sets a database device's status to defaulton or defaultoff.
-
- sp_dropalias
- Removes the alias username identity that had been established with
- sp_addalias.
-
- sp_dropdevice
- Drops an SQL Server database device or dump device.
-
- sp_dropgroup
- Drops a group from a database.
-
- sp_dropkey
- Removes a key from the syskeys table that had been defined using
- sp_primarykey, sp_foreignkey, or sp_commonkey.
-
- sp_droplogin
- Drops an SQL Server user by deleting his or her entry in
- master.dbo.syslogins.
-
- sp_droptype
- Drops a user-defined datatype by deleting the type from systypes.
-
- sp_dropuser
- Drops a user from the current database by deleting the entry from
- sysusers.
-
- sp_foreignkey
- Defines a foreign key on a table or view.
-
- sp_help
- Reports information about a database object (any object listed in
- sysobjects) or about an SQL Server-supplied or user-defined datatype.
-
- sp_helpdb
- Reports information about a database or about all databases.
-
- sp_helpdevice
- Reports information about SQL Server's database devices and dump devices.
-
- sp_helpgroup
- Reports information on a group or on all groups in the current database.
-
- sp_helpindex
- Reports index information on a table.
-
- sp_helpjoins
- Lists the columns in two tables or views that are likely to be joined.
-
- sp_helpkey
- Reports information on primary, foreign, and common keys.
-
- sp_helprotect
- Reports permissions by database object and optionally by user for that
- object.
-
- sp_helpsql
- Provides syntax for SQL statements and system procedures.
-
- sp_helptext
- Prints the text of a stored procedure, trigger, view, default, or rule.
-
- sp_helpuser
- Reports information on users of a database.
-
- sp_lock
- Reports information on locks.
-
- sp_logdevice
- Puts the syslogs system table, which contains the transaction log, on a
- separate database device.
-
- sp_monitor
- Displays statistics about SQL Server.
-
- sp_password
- Adds or changes a password for an SQL Server login ID.
-
- sp_primarykey
- Defines a primary key on a table or view.
-
- sp_rename
- Changes the name of a user-created object in the current database.
-
- sp_renamedb
- Changes the name of a database.
-
- sp_spaceused
- Displays the number of rows, the number of data pages, and the disk space
- used by an object or by each object in a database.
-
- sp_unbindefault
- Unbinds a default value from a column or from a user-defined datatype.
-
- sp_unbindrule
- Unbinds a rule from a column or user-defined datatype.
-
- sp_who
- Reports information on current SQL Server users and processes.
-
- ────────────────────────────────────────────────────────────────────────────
- There are additional system procedures that are called by other system
- procedures; users cannot call them directly.
-
-
-
-
-
- sp_addalias
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Maps one user to another in a database.
-
-
- Syntax
-
- sp_addalias login_id, username
-
-
- Examples
-
- sp_addalias victoria, albert
-
- There is a user named albert in the database's sysusers table and a login ID
- for a user named victoria in master.dbo.syslogins. This system procedure
- allows victoria to use the current database and to be known as albert in
- this database.
-
-
- Options
-
- login_id
- The master.dbo.syslogins name of the user who wants an alternate identity
- in the current database. An alias allows an SQL Server user to be known in
- a database as another user. If the user with login_id exists in the
- database's sysusers table, SQL Server won't find the user's alias
- identity, since it checks sysusers before checking sysalternates.
-
- username
- The name of the database user to whom the first user wishes to be linked.
- The name must exist in both master.dbo.syslogins and in the sysusers table
- of the current database
-
-
- Comments
-
- Executing sp_addalias maps one user (login_id) to another (username) in the
- current database. The mapping is shown in sysalternates, where the two
- users' suids are connected.
-
- A report on any users mapped to a specified user can be generated with
- sp_helpuser if you give the specified user's name as a parameter.
-
- When a user tries to use a database, SQL Server checks sysusers to see if
- the username is listed there. If the username is not there, it then checks
- sysalternates. If an entry (the user's suid) is found there, mapped to a
- database user's suid (altsuid in sysalternates table), the first user is
- treated as the second user while using the database.
-
- There are three ways that you can be authorized to use a database (assuming
- you are listed in master.dbo.syslogins). First, you can be listed in the
- sysusers table of that database. (New database users are added by the
- Database Owner with the sp_adduser system procedure.)
-
- Second, you can have an alias in the database, which has been added by the
- Database Owner with the sp_addalias system procedure.
-
- Third, you can use the database as guest if there is a guest entry in the
- database's sysusers table.
-
-
- Messages
-
- Alias user added.
-
- The procedure was successful. Now the user with login_id can use the current
- database. When doing so, he or she will be known as username.
-
- No login exists with the specified login name.
-
- There is no entry in master.dbo.syslogins for login_id. Everyone using SQL
- Server, whether aliased or not, must have a login ID.
-
- No user with the specified name exists in the current database.
-
- Since username is not a user in the database, login_id can't be aliased to
- it.
-
- The specified user name is already aliased.
-
- The login_id is already aliased to a user in the current database. A
- login_id may be aliased to only one database user at a time. To change an
- alias, first drop the current alias using sp_dropalias, then add the new
- alias.
-
-
- Permissions
-
- Execute permission defaults to the Database Owner.
-
-
- Tables Used
-
- master.dbo.syslogins, sysalternates, sysusers
-
-
- See Also
-
- sp_addlogin, sp_adduser, sp_dropalias, sp_helpuser, USE
-
-
- sp_addgroup
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Adds a group to a database. Groups are used as collective names in granting
- and revoking permissions.
-
-
- Syntax
-
- sp_addgroup grpname
-
-
- Examples
-
- sp_addgroup accounting
-
- This example creates an accounting group.
-
-
- Options
-
- grpname
- The name of the group. Groupnames must follow the rules for identifiers.
-
-
- Comments
-
- Groups are used as collective names for granting and revoking permissions.
-
- The sp_addgroup system procedure adds an entry for the new group to a
- database's sysusers table. Each group's uid is a number greater than or
- equal to 16,384 (except the uid of the public group, which is always 0).
-
- Once a group has been created, you can use the groupname as an optional
- parameter to sp_adduser to add the new user to a group at the same time. To
- add an already existing user to a group, use sp_changegroup.
-
- A user can be a member of only one group.
-
- Every database is created with a public group. If a user is not explicitly
- added to another group, he or she is a member of the public group.
-
-
- Messages
-
- New group added.
-
- An entry for the group has been added to the current database's sysusers
- table. Users may now be made members of the group with the sp_adduser or
- sp_changegroup system procedures.
-
- A user with the specified group name already exists.
-
- The groupname you supplied is already being used as a username. Choose
- another name to use as the grpname parameter.
-
- A group with the specified name already exists.
-
- The groupname you supplied is already being used as a groupname. Choose
- another name to use as the grpname parameter.
-
-
- Permissions
-
- Execute permission defaults to the Database Owner.
-
-
- Tables Used
-
- sysusers
-
-
- See Also
-
- sp_adduser, sp_changegroup, sp_dropgroup, sp_helpgroup, GRANT, REVOKE
-
-
- sp_addlogin
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Authorizes a new SQL Server user by adding an entry to master.dbo.syslogins.
-
-
-
- Syntax
-
- sp_addlogin login_id [, passwd [, defdb]]
-
-
- Examples
-
- A. sp_addlogin victoria
-
- Example A creates an SQL Server login for the user victoria. Since the
- passwd and defdb parameters are not included, victoria's password is the
- null value and her default database is master.
-
- B. sp_addlogin albert, food, corporate
-
- Example B creates an SQL Server login ID for the user albert. His password
- is food and his default database is corporate.
-
-
- Options
-
- login_id
- The login ID of the user. Login IDs normally follow the rules for
- identifiers. (However, numeric login IDs of up to 30 digits are also
- allowed.)
-
- passwd
- The user's password. If no password is given, the default password is the
- null value.
-
- defdb
- The name of the user's default, or "home," database─the database to which
- the user is connected when he or she logs in. If no defdb is given, the
- default is master.
-
-
- Comments
-
- After sp_addlogin is executed, the user can log in to SQL Server.
-
- The user can change his or her own password at any time with sp_password.
- The System Administrator can change any user's password with sp_password.
-
- If a third parameter (the name of a default database) is supplied, the user
- is connected to the specified database without the USE statement and without
- passing through master. However, the user cannot use the default database
- until he or she is given access to that database by its Database Owner
- (using the sp_adduser or sp_addalias system procedures).
-
- The user can change his or her own default database at any time with
- sp_defaultdb. The System Administrator can change any user's default
- database with sp_defaultdb.
-
-
- Messages
-
- New login created.
-
- An SQL Server login ID for login_id has been created successfully.
-
- Only the System Administrator may execute this procedure.
-
- Someone other than the System Administrator tried to execute the system
- procedure. Only the System Administrator can add login IDs to SQL Server.
-
- A user with the specified login name already exists.
-
- A user with that login ID has already been added. Choose another login_id.
-
- Database name not valid -- login not added.
-
- The specified default database does not exist. Create the database first or
- choose a database that already exists as defdb.
-
-
- Permissions
-
- Execute permission defaults to the System Administrator.
-
-
- Tables Used
-
- master.dbo.sysdatabases, master.dbo.syslogins
-
-
- See Also
-
- sp_addalias, sp_adduser, sp_defaultdb, sp_droplogin, sp_password, USE
-
-
- sp_addtype
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Creates a user-defined datatype.
-
-
- Syntax
-
- sp_addtype typename, phystype[(length)] [, nulltype]
-
-
- Examples
-
- A. sp_addtype ssn, "varchar(11)"
-
- Example A creates a user-defined datatype called ssn to be used for columns
- that hold social security numbers. Since no nulltype parameter is specified,
- no null values are allowed. Notice that "varchar(11)" is enclosed in
- quotation marks because it contains punctuation (parentheses).
-
- B. sp_addtype birthday, datetime, null
-
- Example B creates a user-defined datatype called birthday that allows null
- values.
-
-
- Options
-
- typename
- The name of the user datatype. Type names must follow the rules for
- identifiers and must be unique for each owner in each database.
-
- phystype[(length)]
- The physical or SQL-Server-supplied type (char, int, and so on) on which
- the user datatype is based. Length must be specified for char, varchar,
- binary, and varbinary. If a length is given, the phystype parameter must
- be enclosed in single or double quotation marks. (Quotation marks are
- required around all parameters with embedded blank spaces or punctuation
- marks.)
-
- nulltype
- A variable that indicates how the user datatype handles null value
- entries. The default (if this optional parameter is omitted) is NOT NULL
- (disallow null values and require an explicit entry). Acceptable values
- for this parameter are NULL, NONULL, and NOT NULL. You can override the
- user datatype's nulltype condition in a CREATE TABLE statement.
-
-
- Comments
-
- Executing sp_addtype creates a user-defined datatype and adds it to the
- systypes system table. Once a user datatype is created, you can use it in
- CREATE TABLE statements and bind defaults and rules to it.
-
- Define each user datatype in terms of one of the physical
- (SQL-Server-supplied) datatypes, optionally specifying NULL (allow null
- entries) or NONULL (disallow them). The default, if you give no third
- parameter, is nonull.
-
- A user-defined datatype name must be unique in the database, but
- user-defined datatypes with different names can have the same definitions.
-
-
- Messages
-
- Type added.
-
- The new user datatype was created and can now be used in CREATE TABLE
- statements or to bind rules and defaults.
-
- Usage: sp_addtype name, 'datatype' [,null | nonull]
-
- Syntax summary. The nulltype parameter can be null, NULL, nonull, NONULL,
- not null, or NOT NULL.
-
- A type with the specified name already exists.
-
- The typename parameter is already a user-defined datatype. Choose a
- different name.
-
- Illegal length specified -- must be between 1 and 255.
-
- The length of a datatype must be between 1 and 255.
-
- Physical datatype does not exist.
-
- The phystype you gave is not an SQL Server datatype.
-
- Physical datatype does not allow null values.
-
- The bit datatype doesn't allow null values, and you specified with the
- nulltype parameter that you wanted to allow null values.
-
- Physical type is fixed length. You cannot specify the length.
-
- The physical datatypes that take length specifications are char, varchar,
- binary, and varbinary. Other physical datatypes have fixed lengths that
- cannot be changed.
-
- You must specify a length with this physical type.
-
- You used a phystype ─char, varchar, binary, or varbinary─that requires a
- length. For example, "char(10)" is acceptable, but char is not.
-
-
- Permissions
-
- Execute permission defaults to the public group.
-
-
- Tables Used
-
- systypes
-
-
- See Also
-
- sp_bindefault, sp_bindrule, sp_droptype, sp_rename, sp_unbindefault,
- sp_unbindrule, CREATE DEFAULT, CREATE RULE, CREATE TABLE
-
-
- sp_addumpdevice
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Adds a dump device to SQL Server.
-
-
- Syntax
-
- sp_addumpdevice {"disk | diskette"}, logical_name,
- physical_name, cntrltype [, noskip | skip [, media_capacity]]
-
-
- Examples
-
- sp_addumpdevice "diskette", "diskettedumpf",
- "f:\sqlserver\dump\dsk.dat", 3, noskip, .36
-
-
- Options
-
- 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-1/4 inch or 3-1/2 inch diskette
- drive file as a dump device. These options must be enclosed in quotation
- marks.
-
- logical_name
- The logical name of the dump device, which is used in the LOAD and DUMP
- SQL statements. This name must follow the rules for identifiers.
-
- When you add a dump device with a logical name longer than 30 characters,
- the dump device is created but the name is truncated to 30 characters.
-
- physical_name
- The physical name of the dump device. This name must follow the rules for
- operating system 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. Different numbers are necessary
- only if you want to use more than one device simultaneously. For hard disk
- dump devices, the controller number parameter 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.
-
- skip, noskip
- 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
- Diskette size in megabytes. For diskette devices, 1.2 megabytes is the
- default. If you specify media_capacity, you must also specify the noskip
- option. The console program prompts the operator to change diskettes when
- a database dump reaches the specified capacity of the diskette.
-
-
- Comments
-
- The sp_addumpdevice system procedure adds a dump device to the
- master.dbo.sysdevices table. It can then be referred to logically in the
- DUMP DATABASE, DUMP TRANSACTION, LOAD DATABASE, and LOAD TRANSACTION
- statements.
-
- To add database devices to sysdevices, use the DISK INIT statement.
-
- ────────────────────────────────────────────────────────────────────────────
- Warning
-
- 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 changed to diskdump.
- ────────────────────────────────────────────────────────────────────────────
-
-
- Messages
-
- Unknown device type. Use 'disk' or 'diskette'.
-
- The value supplied for the first parameter isn't a known dump device type.
-
- Device with same logical name already exists.
-
- All SQL Server dump devices must have unique logical names. There is already
- a dump device with the name supplied for the logical_name parameter.
-
- Diskette device added.
-
- The diskette dump device was added successfully.
-
- Disk device added.
-
- The disk dump device was added successfully.
-
- For disk devices, controller number parameter must be 2.
-
- When you are adding a disk dump device, the value for the fourth parameter,
- cntrltype, must be 2.
-
- For diskette devices, controller number parameter must be 3
- or 4.
-
- When you are adding a diskette dump device, the value for the fourth
- parameter, cntrltype, must be 3 or 4.
-
- Please specify media capacity in megabytes (1 megabytes minimum).
-
- For diskette dump devices, enter the size in megabytes. The default is 1.2
- megabytes. The console program prompts the operator to change diskettes when
- a database dump reaches the specified capacity of the diskette.
-
-
- Permissions
-
- Execute permission defaults to the System Administrator.
-
-
- Tables Used
-
- master.dbo.sysdevices
-
-
- See Also
-
- sp_helpdevice, sp_dropdevice, DISK INIT, DUMP DATABASE, DUMP TRANSACTION,
- LOAD DATABASE, LOAD TRANSACTION, console
-
-
- sp_adduser
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Adds a new user to the current database.
-
-
- Syntax
-
- sp_adduser login_id [, username [, grpname]]
-
-
- Examples
-
- A. sp_adduser victoria, victoria, fort_mudge
-
- SQL Server login ID victoria has already been added to SQL Server with
- sp_addlogin. In example A we add her to the database. Victoria will be known
- in the current database by the username victoria and belong to the group
- fort_mudge (which has previously been created with sp_addgroup).
-
- B. sp_adduser margaret
-
- Example B adds margaret to the database. Her database username is the same
- as her SQL Server login ID, and she belongs to the default group public.
-
- C. sp_adduser haroldq, harold, fort_mudge
-
- Example C adds haroldq to the database. When haroldq uses the current
- database, his name is harold. He belongs to the fort_mudge group.
-
-
- Options
-
- login_id
- The user's login ID as found in master.dbo.syslogins.
-
- 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. If you want
- to add a user to a group, you must supply a value for the username
- parameter. It can be the same as login_id.
-
-
- Comments
-
- The Database Owner executes sp_adduser to add a username to the sysusers
- table of the current database, enabling the user to access the current
- database under his or her own name.
-
- Specifying a username parameter gives the new user a name in the database
- different from his or her login ID on SQL Server. The ability to assign a
- user a different name on SQL Server and in a database is provided as a
- convenience. This is not an alias as provided by sp_addalias: the user is
- simply given a different name and is not mapped to the identity and
- permissions of another user.
-
- You can also supply a grpname for the user. The group must already exist in
- the database.
-
- A user can be a member of only one group. Every user is a member of the
- default group, public, if he or she has not been explicitly added to some
- other group with sp_adduser or sp_changegroup.
-
- To access a database, a user must be listed in sysusers (with sp_adduser) or
- mapped to another user in sysalternates (with sp_addalias), or there must be
- a guest entry in sysusers.
-
-
- Messages
-
- New user added.
-
- The system procedure was successful. The user is now known in the current
- database.
-
- No login with the specified name exists.
-
- The login_id you gave is unknown to SQL Server. Each user must have a login
- ID on SQL Server before he or she can be added to a database.
-
- A user with the same name already exists in the database.
-
- The username is already a user in the database. Choose another name.
-
- User already has alias access to the database.
-
- The login_id is already known to the database by an alias. If you still want
- to add the user, drop the alias with the sp_dropalias system procedure and
- then re-execute sp_adduser.
-
- User already has a login under a different name.
-
- The user with the login_id you supplied is listed in the current database's
- sysusers table with a name different from the one supplied as the username
- parameter.
-
- No group with the specified name exists.
-
- The groupname you supplied does not exist in this database. Either omit the
- grpname parameter or create the group with sp_addgroup first.
-
-
- Permissions
-
- Execute permission defaults to the Database Owner.
-
-
- Tables Used
-
- master.dbo.syslogins, sysalternates, sysusers,
-
-
- See Also
-
- sp_addalias, sp_addgroup, sp_changegroup, sp_dropalias, sp_dropgroup,
- sp_helpuser, GRANT, REVOKE, USE
-
-
- sp_bindefault
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Binds a default to a column or to a user-defined datatype.
-
-
- Syntax
-
- sp_bindefault defname, objname [, futureonly]
-
-
- Examples
-
- A. sp_bindefault today, "employees.startdate"
-
- Assuming that a default named today has been defined in the current database
- with CREATE DEFAULT, the system procedure in example A binds it to the
- startdate column of the employees table. Whenever a row is added to the
- employees table and data for the startdate column is not supplied, the
- column gets the value of the default today.
-
- B. sp_bindefault def_ssn, ssn
-
- Assuming that a default named def_ssn and a user-defined datatype named ssn
- exist, the system procedure in example B binds def_ssn to ssn. The default
- is inherited by all columns that are assigned the user datatype ssn when a
- table is created. Existing columns of type ssn also inherit the default
- def_ssn unless you use the optional third parameter, futureonly (which
- prevents existing columns of that user datatype from inheriting the
- default), or unless the column's default has previously been changed (in
- which case the changed default is maintained).
-
- C. sp_bindefault def_ssn, ssn, futureonly
-
- Example C binds the default def_ssn to the user datatype ssn. Because the
- futureonly parameter is included, no existing columns of type ssn are
- affected.
-
-
- Options
-
- defname
- The name of a default. Defaults are created with CREATE DEFAULT statements
- and then bound to specific columns or user-defined datatypes with
- sp_bindefault.
-
- objname
- The name of the table and column or user-defined datatype to which the
- default is to be bound. If the objname is not of the form "table.column",
- it is assumed to be a user datatype. (Quotation marks are required around
- all system procedure parameters that have embedded blanks or punctuation.)
- By default, existing columns of the user datatype inherit the default
- defname unless the column's default has previously been changed.
-
- futureonly
- Prevents existing columns of a user datatype from inheriting the new
- default. This parameter is optional when binding a default to a
- user-defined datatype. It is never used when binding a default to a
- column.
-
-
- Comments
-
- First use the CREATE DEFAULT statement to create a default. Then execute
- sp_bindefault to bind it to a column or user datatype in the current
- database.
-
- You cannot bind a default to an SQL-Server-supplied datatype.
-
- If binding to a column, the objname parameter must be of the form
- "table.column". Any other format is taken to be the name of a user datatype.
-
-
- You can bind a new default to a column or user datatype using sp_bindefault
- without unbinding an existing default. The old default is overridden.
-
- Existing columns of the user-defined datatype inherit the new default unless
- their default has previously been changed or the value of the optional third
- parameter is futureonly. New columns of the user-defined datatype always
- inherit the default.
-
- The default must be compatible with the datatype of the column. You cannot
- use "N/A", for example, as a default for a numeric column. If the default is
- not compatible with the column to which you've bound it, SQL Server will
- generate an error message when it tries to insert the default value (not
- when you bind it).
-
-
- Messages
-
- Default bound to column.
-
- The default was successfully bound to the specified column in the specified
- table.
-
- Default bound to datatype.
-
- The default was successfully bound to the specified user-defined datatype.
-
- Default and table or usertype must be in 'current' database.
-
- The objname parameter supplied with the system procedure contained a
- reference to another database. Defaults can be bound to objects in the
- current database only.
-
- No such default exists. You must create the default first.
-
- First create the default in the current database with CREATE DEFAULT. Then
- execute sp_bindefault.
-
- You do not own a column of that name.
-
- Only the owner of a table can bind a default to any of its columns. You are
- not the owner.
-
- You do not own a datatype of that name.
-
- Only the owner of a user-defined datatype can bind a default to it. You are
- not the owner.
-
- The new default has been bound to column(s) of the specified
- user datatype.
-
- Existing columns of the user-defined datatype specified now have the new
- default bound to them (unless their defaults were previously changed).
-
-
- Permissions
-
- Execute permission defaults to the object owner.
-
-
- Tables Used
-
- syscolumns, sysobjects, systypes
-
-
- See Also
-
- sp_bindrule, sp_unbindefault, sp_unbindrule, CREATE DEFAULT, DROP DEFAULT
-
-
- sp_bindrule
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Binds a rule to a column or user datatype.
-
-
- Syntax
-
- sp_bindrule rulename, objname [, futureonly]
-
-
- Examples
-
- A. sp_bindrule today, "employees.startdate"
-
- Assuming that a rule named today has been created in the current database
- with CREATE RULE, the system procedure in example A binds it to the
- startdate column of the employees table. When a row is added to employees,
- the data for the startdate column is checked against the today rule.
-
- B. sp_bindrule rule_ssn, ssn
-
- Assuming the existence of a rule named rule_ssn and a user datatype named
- ssn, the system procedure in example B binds rule_ssn to ssn. In a CREATE
- TABLE statement, columns of type ssn inherit the rule_ssn rule. Existing
- columns of type ssn also inherit the rule_ssn rule unless you use the
- optional third parameter, futureonly (which prevents existing columns of
- type ssn from inheriting the rule) or ssn's rule has previously been changed
- (in which case the changed rule is maintained).
-
- C. sp_bindrule rule_ssn, ssn, futureonly
-
- The rule_ssn rule is bound to the user type ssn, but no existing columns of
- type ssn are affected (example C).
-
-
- Options
-
- rulename
- The name of a rule. Rules are created with CREATE RULE statements and then
- bound to specific columns or user datatypes with sp_bindrule.
-
- objname
- The name of the table and column or user datatype to which the rule is to
- be bound. If the parameter is not of the form "table.column", it is
- assumed to be a user datatype. (Quotation marks are required around all
- system procedure parameters that have embedded blanks or punctuation.)
-
- futureonly
- Prevents existing columns of a user datatype from inheriting the new rule.
- This parameter is optional when binding a rule to a user datatype. It is
- never used when binding a rule to a column.
-
-
- Comments
-
- The rule is enforced when an INSERT is attempted, not at binding. You can
- bind a character rule to a column of numeric datatype, even though such an
- INSERT is illegal.
-
- First use the CREATE RULE statement to create a rule. Then execute
- sp_bindrule to bind it to a column or user datatype in the current database.
-
-
- You cannot bind a rule to an SQL-Server-supplied datatype.
-
- If binding to a column, the objname parameter must be of the form
- "table.column". Any other format is taken to be the name of a user datatype.
-
-
- You can bind a new rule to a column or user datatype using sp_bindrule
- without unbinding an existing rule. The old rule is overridden.
-
- Existing columns of the user datatype inherit the new rule unless their rule
- has previously been changed or the value of the optional third parameter is
- futureonly. New columns of the user datatype always inherit the rule.
-
-
- Messages
-
- Rule bound to table column.
-
- The rule was successfully bound to the specified column in the specified
- table.
-
- Rule bound to datatype.
-
- The rule was successfully bound to the specified user datatype.
-
- Rule and table or usertype must be in 'current' database.
-
- The objname parameter supplied with the procedure contained a reference to
- another database. Rules can be bound to objects in the current database
- only.
-
- No such rule exists. You must create the rule first.
-
- First create the rule in the current database with CREATE RULE. Then execute
- sp_bindrule.
-
- You do not own a column of that name.
-
- Only the owner of a table can bind a rule to any of its columns. You are not
- the owner.
-
- You do not own a datatype of that name.
-
- Only the owner of a user datatype can bind a rule to it. You are not the
- owner.
-
- The new rule has been bound to column(s) of the specified
- user datatype.
-
- Existing columns of the specified user datatype now have the new rule bound
- to them (unless their rules were previously changed).
-
-
- Permissions
-
- Execute permission defaults to the object owner.
-
-
- Tables Used
-
- syscolumns, sysobjects, systypes
-
-
- See Also
-
- sp_bindefault, sp_unbindefault, sp_unbindrule, CREATE RULE, DROP RULE
-
-
- sp_changedbowner
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Changes the owner of a database.
-
-
- Syntax
-
- sp_changedbowner login_id
-
-
- Examples
-
- sp_changedbowner albert
-
- This example makes the user albert the owner of the current database.
-
-
- Options
-
- login_id
- The login ID of the new owner of the current database. The new owner must
- not already be known as either a user or alias (that is, the new owner
- must not already be listed in sysusers or sysalternates).
-
-
- Comments
-
- The sp_changedbowner system procedure makes login_id the owner of the
- current database.
-
- The new owner must already have a login ID on SQL Server but must not have a
- database name or alias name in the database. If you want to assign database
- ownership to such a user, drop his or her database name and alias entries
- before executing sp_changedbowner.
-
- After the sp_changedbowner system procedure is executed, the new owner is
- known as Database Owner inside the database.
-
- If you (as System Administrator) want to grant permissions to this new
- owner, grant them to Database Owner because the user is no longer known
- inside the database under any other name.
-
-
- Messages
-
- Only the System Administrator can change the owner of a database.
-
- You are not the System Administrator, so you can't change the owner of the
- current database.
-
- You can't change the owner of the Master Database.
-
- The owner of the master database cannot be changed by anyone.
-
- No login with the specified name exists.
-
- The proposed new Database Owner must have a login ID on SQL Server.
-
- The proposed new db owner already is a user in the database.
-
- The specified login_id is already a user in the current database. To make
- him or her the Database Owner, first drop his or her user entry from the
- current database's sysusers table.
-
- The proposed new db owner already is aliased in the database.
-
- The specified login_id is already aliased in the current database. To make
- him or her the Database Owner, first drop his or her user alias entry from
- the current database's sysalternates table.
-
- Database owner changed.
-
- The Database Owner was successfully changed.
-
-
- Permissions
-
- Execute permission defaults to the Database Owner.
-
-
- Tables Used
-
- master.dbo.sysdatabases, master.dbo.syslogins, sysalternates, sysusers
-
-
- See Also
-
- sp_addlogin, sp_dropalias, sp_dropuser, sp_helpdb, CREATE DATABASE
-
-
- sp_changegroup
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Changes a user's group.
-
-
- Syntax
-
- sp_changegroup grpname, username
-
-
- Examples
-
- sp_changegroup fort_mudge, albert
-
- The user albert is now a member of the fort_mudge group. It doesn't matter
- what group albert belonged to before.
-
-
- Options
-
- grpname
- The name of the group. The group must already exist in the current
- database.
-
- username
- The name of the user to add to the group. The user must already exist in
- the current database.
-
-
- Comments
-
- Executing sp_changegroup adds the specified user to the specified group. The
- user is dropped from the group he or she belongs to and is added to the one
- specified by grpname.
-
- New database users can be added to groups at the same time they are given
- access to the database with sp_adduser.
-
- Every user is a member of the default group, public, if he or she has not
- been explicitly added to some other group with sp_adduser or sp_changegroup.
-
-
- A user can be a member of only one group.
-
- Groups are used as a collective name for granting and revoking permissions.
-
-
- If you use public as the grpname parameter, it must be enclosed in quotation
- marks because it is an SQL keyword.
-
-
- Messages
-
- Group changed.
-
- The user now belongs to the specified group.
-
- No such group exists.
-
- The specified group doesn't exist in the current database.
-
- No such user exists.
-
- The specified user doesn't exist in the current database.
-
-
- Permissions
-
- Execute permission defaults to the Database Owner.
-
-
- Tables Used
-
- sysusers
-
-
- See Also
-
- sp_addgroup, sp_adduser, sp_dropgroup, sp_helpgroup, GRANT, REVOKE
-
-
- sp_commonkey
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Defines a common key between two tables or views.
-
-
- Syntax
-
- sp_commonkey tabaname, tabbname, col1a, col1b
- [, col2a, col2b, ..., col8a, col8b]
-
-
- Examples
-
- sp_commonkey projects, departments, empid, empid
-
- Assume two tables, projects and departments, each with a column named empid.
- This statement defines a frequently used join on the two columns.
-
-
- Options
-
- tabaname
- The name of the first table or view to be joined.
-
- tabbname
- The name of the second table or view to be joined.
-
- col1a
- The name of the first column in the tabaname table or view that makes up
- the common key. At least one pair of columns (one column from the first
- table or view and one from the second table or view) must be specified.
-
- col1b
- The name of the partner column in the tabbname table or view that is
- joined with col1a in the tabaname table or view.
-
-
- Comments
-
- Common keys are created to make explicit a logical relationship that is
- implicit in your database design. The information can be used by an
- application.
-
- Executing sp_commonkey adds the key to the syskeys system table. To display
- a report on the common keys that have been defined, execute sp_helpkey.
-
- You must be the owner of at least one of the two tables or views to define a
- common key between them.
-
- The number of columns from the first table or view must be the same as the
- number of columns from the second table or view. Up to eight columns from
- each table or view can participate in the common key.
-
- The datatypes of the common columns must agree, but the length
- specification, if applicable, and nulltypes need not agree. Common keys have
- been assigned within the master and model databases.
-
-
- Messages
-
- New common key added.
-
- The common key between the specified tables or views has been added to
- syskeys.
-
- First table in the common key doesn't exist.
-
- The table or view you gave as tabaname doesn't exist in the current
- database.
-
- Second table in the common key doesn't exist.
-
- The table or view you gave as tabbname doesn't exist in the current
- database.
-
- Only the table owner may define its common key.
-
- You aren't the owner of the tabaname table or view.
-
- The tables or views have no such first column or the columns
-
- are of different types.
-
- Two cases generate this message: either the column pair that you specified
- doesn't exist or the columns in the pair are different types.
-
-
- Permissions
-
- Execute permission defaults to the owner of tabaname or tabbname.
-
-
- Tables Used
-
- syscolumns, syskeys, sysobjects
-
-
- See Also
-
- sp_dropkey, sp_foreignkey, sp_helpjoins, sp_helpkey, sp_primarykey, Joins
-
-
- sp_configure
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Displays or changes configuration options.
-
-
- Syntax
-
- sp_configure [configname [, configvalue]]
-
-
- Examples
-
- A. sp_configure
-
- Example A displays a list of all the configuration options with their
- current and permissible range of values, similar to the following:
-
- ╓┌─┌───────────────────┌─────────┌─────────┌─────────────┌───────────────────╖
- ────────────────────────────────────────────────────────────────────────────
- name minimum maximum config_value run_value
- ----------------- -------- -------- ------------ ---------
- recovery interval 1 32767 4 3
- allow updates 0 1 0 0
- user connections* 5 35 0 25
- memory 1000 14000 0 1700
- open databases 5 100 0 10
- locks 5000 50000 0 5000
- open objects 100 10000 0 500
- procedure cache 1 99 0 20
- fill factor 0 100 0 0
- time slice 50 1000 0 100
- database size 2 10000 0 2
- media retention 0 365 0 0
- recovery flags 0 1 0 0
- ────────────────────────────────────────────────────────────────────────────
- recovery flags 0 1 0 0
- serial number 1 999999 0 0
- (14 rows affected)
-
-
- * SQL Server maximum is 250; the effective number is based upon your system
- configuration. The maximum number of connections in your computer
- environment is stored in the @MAX_CONNECTIONS global variable. The
- config_value column of the report contains the value to which the
- configuration option has been set with sp_configure. It changes after you
- execute sp_configure. (This is the value in sysconfigures.value.) The
- run_value column contains the value SQL Server is using. It changes after
- you execute the RECONFIGURE statement. (This is the value in
- syscurconfigs.value.)
-
-
- B. sp_configure "recovery interval", 3
-
- Example B sets the system recovery interval to 3 minutes.
-
-
- Options
-
- configname
- The name of the configuration option. SQL Server understands any unique
- string that is part of the configuration name.
-
- configvalue
- The value for the configuration option.
-
-
- Comments
-
- All users can execute sp_configure with no parameters (SQL Server displays a
- list of all the configuration options and their current values) or with one
- parameter, the name of the configuration options (SQL Server displays the
- value for that variable).
-
- The System Administrator can execute sp_configure with both parameters to
- change the value of one of the configuration options. The second parameter
- is the new config_value. After sp_configure has been executed, the System
- Administrator must execute the RECONFIGURE statement to install the changed
- value. Then, for all variables except allow updates and recovery interval,
- the System Administrator must restart SQL Server.
-
- Use RECONFIGURE WITH OVERRIDE when you set allow updates on or when you set
- a configuration option to a value that SQL Server considers less than
- optimal.
-
- To instruct SQL Server to supply a default configuration option, give the
- value 0 as the config_value.
-
- See the SQL Server System Administrator's Guide for details.
-
-
- Messages
-
- Configuration option changed. Run the RECONFIGURE statement
-
- to install.
-
- After changing a configuration option with sp_configure, the change does not
- take effect until the RECONFIGURE statement is executed and (for all but
- allow updates and recovery interval) SQL Server is restarted.
-
- Configuration option doesn't exist.
-
- The name supplied as the config_name parameter is unknown.
-
- Configuration option is not unique.
-
- The name supplied as the config_name parameter is not unique. No
- configuration option was changed. For example, two of the configuration
- options are recovery interval and recovery flags. Using recovery for the
- config_name parameter generates this message because it matches both names.
- The complete names that match the string supplied are printed out so that
- you can see how to make the config_name more specific.
-
- Only the System Administrator may change configuration parameters.
-
- Although any user can examine the state of the configuration options, only
- the System Administrator can change them.
-
- Configuration option value is not legal.
-
- The config_value supplied is not in the range of permissible values for the
- specified configuration option. For a display of the range of permissible
- values, rerun sp_configure with the name of the configuration option as the
- only parameter. A config_value of 0 is always legal. It instructs SQL Server
- to set the configuration value to its default.
-
-
- Permissions
-
- Execute permission for no parameters or the first parameter defaults to all
- users. Execute permission for both parameters defaults to the System
- Administrator.
-
-
- Tables Used
-
- sysconfigures, syscurconfigs, spt_values
-
-
- See Also
-
- sp_dboption, RECONFIGURE
-
-
-
-
-
- sp_dboption
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Displays or changes database options.
-
-
- Syntax
-
- sp_dboption [dbname, optname, {true | false}]
-
-
- Examples
-
- A. sp_dboption
-
- Example A displays a list of the database options:
-
- 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)
-
- B. use master
- go
- sp_dboption pubs, read, true
- use pubs
- go
- checkpoint
-
- Example B makes the pubs database read only.
-
- C. use master
- go
- sp_dboption pubs, read, false
- use pubs
- go
- checkpoint
-
- Example C makes the pubs database writable again.
-
-
- Options
-
- 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 the master database option settings.
-
- optname
- The name of the option you want to set or unset. 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.
-
-
- Comments
-
- You cannot change any of the database option settings for the master
- database.
-
- To display a list of the database options the user can set, execute
- sp_dboption with no parameters from inside the master database.
-
- For a report on which database options are set in a particular database,
- execute sp_helpdb.
-
- The Database Owner or System Administrator can set or unset particular
- database options for all new databases by executing sp_dboption on the model
- database.
-
- After sp_dboption has been executed, the change does not take effect until
- the CHECKPOINT statement is executed in the database for which the option
- was changed.
-
- 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 for the change to take effect. Here's an example:
-
- begin tran
- use master
- go
- sp_dboption orderentry, single, true
- go
- use orderentry
- go
- checkpoint
- go
- rollback tran
- go
- /*
- ** If the following CHECKPOINT is not executed,
- ** the orderentry
- ** database remains single-user.
- */
- checkpoint
- go
-
- While the dbo use only option is set (or true), only the Database Owner can
- use the database.
-
- The read only option means that users can retrieve data from the database
- but can't modify anything.
-
- When single user is set to true, only one user at a time can access the
- database.
-
- The trunc. log on chkpt. option means that 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 turn
- this option on while doing development work, to prevent the log from
- growing. While the trunc. log on chkpt. option is set, you cannot use DUMP
- TRANSACTION, since dumps from the truncated transaction log dumps cannot be
- used to recover from a media failure. Issuing the DUMP TRANSACTION statement
- produces an error message instructing you to use DUMP DATABASE instead.
-
- The select into/bulkcopy option must be set if you want to use SELECT INTO
- on a permanent table or do a "fast" bulk copy into a table that has no
- indexes. The fast version of bulk copy (using bcp) copies data into tables
- that have no indexes. Since these operations are not logged, DUMP
- TRANSACTION is prohibited when this option is set. The user is instructed to
- use DUMP DATABASE instead. You do not have to set the select into/bulkcopy
- option to use SELECT INTO on a temporary table since the temporary database
- is never recovered. The option need not be set to run bcp on a table that
- has indexes because tables with indexes are always copied with the slower
- version and are logged. By default, the select into/bulkcopy option is off
- in newly created databases. To change the default situation, set this option
- in the model database.
-
- The no chkpt on recovery option is set (true) when 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 dumped and loaded into the secondary database.
-
- If this option is off (false), the default condition, a checkpoint record is
- added to a database after it is recovered due to restarting SQL Server. This
- checkpoint, which insures that the recovery mechanism won't unnecessarily be
- rerun, changes the sequence number and causes a subsequent load of the
- transaction log from the primary database to fail.
-
- If this option is on (true), no checkpoint record is added to a database
- after it is recovered, so that subsequent transaction log dumps from the
- primary database can be loaded into it.
-
- See the SQL Server System Administrator's Guide for additional details on
- database options.
-
-
- Messages
-
- No such database -- run sp_helpdb to list databases.
-
- No database with the supplied name exists. Run sp_helpdb to get a list of
- databases.
-
- The `master' database's options cannot be changed.
-
- No one can change any of master database option settings.
-
- Settable database options.
-
- Executing sp_dboption with no parameters displays a list of the options the
- user can set.
-
- Database option doesn't exist or can't be set by user.
-
- Run sp_dboption with no parameters to see options. This message is generated
- in two cases: either the option doesn't exist or the user does not have
- permission to set or unset it. Run the system procedure with no parameters
- to display a list of the options the user can set.
-
- Database option is not unique.
-
- The name supplied as the optname parameter is not unique. No database option
- value was changed. For example, two of the database options are dbo use only
- and read only. Using only for the optname parameter generates this 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.
-
- Only the System Administrator or the owner of the database
-
- may set db options.
-
- Although all users can look at a list of the settable database options, only
- the System Administrator or Database Owner can set or unset them. You aren't
- the System Administrator or the Database Owner.
-
- You must be in the `master' database to change database options.
-
- To change a database option (of any database other than master), execute the
- sp_dboption system procedure with the appropriate parameters, while using
- master.
-
- usage: sp_dboption [dbname, optname, {true | false}]
-
- Either the optname parameter was omitted or the optvalue parameter was
- something other than true or false.
-
- Run the CHECKPOINT command in the database that was changed.
-
- The change in the database option takes effect after the CHECKPOINT
- statement is run.
-
-
- Permissions
-
- Execute permission for no parameters (display options only) defaults to all
- users. Execute permission for parameters (change an option) defaults to the
- System Administrator and Database Owner of the database for which the option
- is to be changed.
-
-
- Tables Used
-
- master.dbo.spt_values, master.dbo.sysdatabases
-
-
- See Also
-
- sp_configure, sp_helpdb, sp_helpjoins, CHECKPOINT, SELECT
-
-
- sp_defaultdb
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Changes a user's default database.
-
-
- Syntax
-
- sp_defaultdb login_id, defdb
-
-
- Examples
-
- sp_defaultdb victoria, pubs
-
- This example sets the default database for victoria to pubs.
-
-
- Options
-
- login_id
- The login ID of the user.
-
- defdb
- The name of the user's default, or "home," database (the database to which
- the user is connected when he or she logs in).
-
-
- Comments
-
- A default database can be set either with sp_defaultdb or with sp_addlogin
- when the user's login ID is first added to SQL Server.
-
- The database to which users are connected if no default database has been
- specified, either with sp_defaultdb or sp_addlogin, is master.
-
- After sp_defaultdb is executed, the user is connected to the new defdb the
- next time he or she logs in. However, this system procedure does not
- automatically give the user access to that database. The Database Owner must
- give the user database access through sp_adduser or sp_addalias, or there
- must be a guest user in the database's sysusers table. If the user does not
- have access to the database by any of these means, she or he is connected to
- master, and an error message is displayed.
-
- If a user's default database is dropped, the user is connected to master on
- his or her next login, and an error message is displayed.
-
- The System Administrator can change anyone's default database with this
- system procedure. All others can change only their own default database.
-
-
- Messages
-
- Default database changed.
-
- The default database for login_id has been changed successfully.
-
- No such account exists.
-
- There is no login ID for login_id. Nothing was changed.
-
- Database name not valid -- default not changed.
-
- There is no database with the specified name.
-
- You can't change someone else's default database.
-
- Every user can change his or her own default database, but only the System
- Administrator can change other users' default databases. You aren't the
- System Administrator.
-
-
- Permissions
-
- Execute permission defaults to public for his or her own login ID only.
- Execute permission defaults to the System Administrator for any login ID.
-
-
- Tables Used
-
- master.dbo.sysdatabases, master.dbo.syslogins
-
-
- See Also
-
- sp_addlogin, sp_droplogin, sp_password, USE
-
-
- sp_depends
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Displays information about database object dependencies─the views and
- procedures that depend on the table or view specified, and the tables and
- views that are depended on by the view or procedure specified.
-
-
- Syntax
-
- sp_depends objname
-
-
- Examples
-
- A. sp_depends sysobjects
-
- Example A lists the database objects that depend on the sysobjects table.
-
- B. sp_depends titleview
-
- Things the object references in the current database.
-
- object type updated selected
- -------------------- ---------------- ------- --------
- dbo.authors user table no no
- dbo.titleauthor user table no no
- dbo.titles user table no no
-
- Things inside the current database that reference the object.
-
- object type
- ------------------ ---------------
- dbo.tview2 view
-
-
- Options
-
- objname
- The name of the database object that you want to examine for dependencies.
- It can be a table, view, stored procedure, or trigger.
-
-
- Comments
-
- Executing sp_depends lists all the objects, if any, that depend on objname
- and all the objects, if any, that objname depends on. For example, views
- depend on one or more tables and can have procedures or other views that
- depend on them.
-
- The sp_depends system procedure determines the dependencies by looking at
- sysdepends.
-
- An object that references another object is considered dependent on that
- object.
-
- The updated and selected columns in the report from sp_depends are
- meaningful if the object being reported on is a stored procedure or trigger.
- The values in these columns indicate whether the stored procedure or trigger
- updates or selects from that object.
-
- References to objects outside the current database are not reported.
-
-
- Messages
-
- No such object in the current database.
-
- The object name supplied for the objname parameter does not exist in the
- current database.
-
- Things the object references in the current database.
-
- These are the objects in the current database that objname depends on.
-
- Things inside the current database that reference the object.
-
- These are the objects in the current database that reference objname.
-
- Object doesn't reference any object and no objects reference
- it.
-
- Nothing depends upon objname, and objname doesn't reference any objects.
-
-
- Permissions
-
- Execute permission defaults to the public group.
-
-
- Tables Used
-
- master.dbo.spt_values, master.dbo.sysdatabases, sysdepends, sysobjects
-
-
- See Also
-
- sp_help, CREATE PROCEDURE, CREATE TABLE, CREATE VIEW, EXECUTE, Views
-
-
- sp_diskdefault
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Sets a database device's status to defaulton or defaultoff. This status
- indicates whether a database device can be used for database storage when
- the user does not specify a database device, or specifies DEFAULT with
- CREATE DATABASE or ALTER DATABASE statements.
-
-
- Syntax
-
- sp_diskdefault database_device, {defaulton | defaultoff}
-
-
- Examples
-
- sp_diskdefault master, defaultoff
-
- The master database device is no longer used by CREATE DATABASE or ALTER
- DATABASE for default storage of a database.
-
-
- Options
-
- database_device
- The logical name of the database device. It must be a database device
- rather than a dump device.
-
- 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).
-
-
- Comments
-
- A default database device is one that is used for database storage by CREATE
- DATABASE or ALTER DATABASE if the user does not specify a database
- devicename or if the user gives the DEFAULT keyword.
-
- When you first install SQL Server, the master database device is the only
- default database device.
-
- To find out which database devices are default database devices, execute the
- sp_helpdevice system procedure.
-
-
- Messages
-
- No such device exists.
-
- The database devicename supplied for the database_device doesn't exist on
- SQL Server. Run the sp_helpdevice system procedure without a parameter to
- see a list of all database devices. To add a new database device to the
- system, use the DISK INIT statement.
-
- The device name supplied is not a database disk.
-
- The database devicename supplied is in sysdevices, but it is a dump device
- rather than a database device. Run the sp_helpdevice system procedure
- without a parameter to see a list of all database devices. To add a new
- database device to the system, use the DISK INIT statement.
-
- Only the System Administrator may execute this procedure.
-
- Only the System Administrator can change the default status of database
- devices.
-
- Usage: sp_diskdefault logical_name {defaulton | defaultoff}.
-
- The second parameter must be either defaulton or defaultoff.
-
-
- Permissions
-
- Execute permission defaults to the System Administrator.
-
-
- Tables Used
-
- master.dbo.sysdevices
-
-
- See Also
-
- sp_helpdevice, ALTER DATABASE, CREATE DATABASE, DISK INIT
-
-
- sp_dropalias
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Removes the alias username identity that had been established with
- sp_addalias.
-
-
- Syntax
-
- sp_dropalias login_id
-
-
- Examples
-
- sp_dropalias victoria
-
- Assuming that victoria had an alias (for example, to the Database Owner) in
- the current database, this statement drops victoria's alias from the
- database.
-
-
- Options
-
- login_id
- The name (in master.dbo.syslogins) of the user who has an alias.
-
-
- Comments
-
- Executing the sp_dropalias system procedure deletes an alternate suid
- mapping for a user from the sysalternates table.
-
- When a user's alias is dropped, he or she no longer has access to the
- database for which the alias was created.
-
-
- Messages
-
- Alias user dropped.
-
- The user no longer has an alias in the current database. He or she cannot
- use the database until the Database Owner reinstates him or her using
- sp_adduser or sp_addalias.
-
- No alias for specified user exists.
-
- The named user doesn't have an alias in the current database.
-
- No login with the specified name exists.
-
- The login_id you supplied has no account on SQL Server. No action was taken.
-
-
-
- Permissions
-
- Execute permission defaults to the Database Owner.
-
-
- Tables Used
-
- sysalternates
-
-
- See Also
-
- sp_addalias, sp_adduser, sp_changedbowner, sp_droplogin, sp_dropuser,
- sp_helpuser, USE
-
-
- sp_dropdevice
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Drops an SQL Server database device or dump device.
-
-
- Syntax
-
- sp_dropdevice logical_name
-
-
- Examples
-
- A. sp_dropdevice disk5
-
- Example A drops the disk5 dump device from SQL Server.
-
- B. sp_dropdevice fredsdata
-
- Example B drops the fredsdata database device from SQL Server. This database
- device must not be in use by any databases.
-
-
- Options
-
- logical_name
- The logical name of the database device or dump device as listed in
- master.dbo.sysdevices.name.
-
-
- Comments
-
- The sp_dropdevice system procedure drops a database device or dump device
- from SQL Server, deleting the entry from master.dbo.sysdevices.
-
- ────────────────────────────────────────────────────────────────────────────
- WARNING
-
- After executing sp_dropdevice, you must restart SQL Server because the
- kernel has a process that is accessing the dropped database device; there is
- no way to kill the process. Failure to restart SQL Server can cause errors.
- Also, restarting SQL Server frees up the database device or dump device.
- ────────────────────────────────────────────────────────────────────────────
-
-
- Messages
-
- Device dropped.
-
- The database device or dump device has been dropped from the
- master.dbo.sysdevices table.
-
- No device with specified logical name exists.
-
- You tried to drop a database device or dump device that doesn't exist on SQL
- Server.
-
- Only the System Administrator may execute this procedure.
-
- Only the System Administrator can add or drop database devices or dump
- devices.
-
- Device is being used by a database. You can't drop it.
-
- Only database devices that are not in use can be dropped. You must drop all
- the databases associated with the database device before dropping the
- database device.
-
-
- Permissions
-
- Execute permission defaults to the System Administrator.
-
-
- Tables Used
-
- master.dbo.sysdevices
-
-
- See Also
-
- sp_addumpdevice, sp_helpdb, sp_helpdevice, DROP DATABASE
-
-
- sp_dropgroup
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Drops a group from a database.
-
-
- Syntax
-
- sp_dropgroup grpname
-
-
- Examples
-
- sp_changegroup accounting, martha
- sp_changegroup "public", george
- sp_dropgroup purchasing
-
- The purchasing group has merged with the accounting group. Members of the
- purchasing group, martha and george, are moved to the accounting group and
- the public group, respectively. Then the purchasing group is dropped. The
- groupname "public" is in quotation marks because public is a reserved word.
-
-
-
- Options
-
- grpname
- The name of a group in the current database.
-
-
- Comments
-
- Executing sp_dropgroup drops a groupname from a database's sysusers table.
-
- You can't drop a group if it has members. You must execute sp_changegroup
- for each member before you can drop the group.
-
-
- Messages
-
- Group has been dropped.
-
- The group no longer exists in the current database.
-
- No group with the specified name exists.
-
- The specified group doesn't exist.
-
- Can't drop the group 'public'.
-
- The public group exists in every database. It is the group that all users
- belong to by default and cannot be dropped.
-
- Group has members. It must be empty before it can be dropped.
-
- Groups with members can't be dropped. Reassign the members of the group to
- another group using sp_changegroup. When this error message is generated, a
- list of the group members is displayed.
-
-
- Permissions
-
- Execute permission defaults to the Database Owner.
-
-
- Tables Used
-
- sysobjects, sysusers
-
-
- See Also
-
- sp_addgroup, sp_adduser, sp_changegroup, sp_dropuser, sp_helpgroup, GRANT,
- REVOKE, USE
-
-
- sp_dropkey
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Removes a key from the syskeys table that had been defined using
- sp_primarykey, sp_foreignkey, or sp_commonkey.
-
-
- Syntax
-
- sp_dropkey keytype, tabname [, deptabname]
-
-
- Examples
-
- A. sp_dropkey primary, employees
-
- Example A drops the primary key for the employees table. Any foreign keys
- that were dependent on the primary key on employees are also dropped.
-
- B. sp_dropkey common, employees, projects
-
- Example B drops the common keys between the employees and projects tables.
-
-
- Options
-
- keytype
- The type of key to be dropped. The keytype must be primary, foreign, or
- common.
-
- tabname
- The name of the table that contains the key to be dropped.
-
- deptabname
- The name of the dependent table in the key to be dropped. Use this option
- only if the keytype is foreign. The deptabname is the table that contains
- the foreign key. If the keytype is primary, this parameter is ignored
- since primary keys have no dependent table.
-
-
- Comments
-
- Executing sp_dropkey deletes the specified key from syskeys.
-
- Only the owner of a table can drop a key on that table.
-
- Dropping a primary key automatically drops any foreign keys associated with
- it, but dropping a foreign key has no effect on a primary key specified on
- that table.
-
- Keys are created to make explicit a logical relationship that is implicit in
- your database design. This information can be used by an application
- program.
-
- Executing sp_commonkey, sp_primarykey, or sp_foreignkey adds the key to the
- syskeys system table. To display a report on the keys that have been
- defined, execute sp_helpkey.
-
-
- Messages
-
- Usage: sp_dropkey {primary | foreign | common}, tabname
- [,deptabname]. Type must be 'primary', 'foreign', or 'common'.
-
- The keytype should specify the type of key to drop.
-
- Table or view name must be in 'current' database and owned
- by you.
-
- You can't drop keys on tables in other databases.
-
- The table named doesn't exist in the current database.
-
- The tabname supplied isn't a table or view in the current database.
-
- You must be the owner of the table to drop its key.
-
- You aren't the owner of tabname, so you can't drop the key.
-
- No primary key for the table exists.
-
- The tabname has no primary key defined.
-
- Primary key for the table dropped.
-
- The primary key was successfully dropped. It has been deleted from syskeys.
-
-
- Dependent foreign keys were also dropped.
-
- When a primary key is dropped, any foreign keys that depend on it are also
- dropped.
-
- You need to supply the dependent table as the third parameter.
-
- When dropping a foreign or common key, both the tabname and deptabname
- tables must be named.
-
- The dependent table doesn't exist in the current database.
-
- The name supplied for the deptabname parameter isn't a table or view in the
- current database.
-
- No foreign key for the table exists.
-
- The tabname has no foreign key defined.
-
- Foreign key dropped.
-
- The foreign key has been successfully dropped. It has been deleted from
- syskeys.
-
- No common keys exist between the two tables supplied.
-
- There are no common keys between the tabname and deptabname tables. No
- action was taken.
-
- Common keys dropped.
-
- The common keys were successfully dropped. They have been deleted from
- syskeys.
-
-
- Permissions
-
- Execute permission defaults to the owner of tabname.
-
-
- Tables Used
-
- syskeys, sysobjects
-
-
- See Also
-
- sp_commonkey, sp_foreignkey, sp_helpkey, sp_primarykey
-
-
- sp_droplogin
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Drops an SQL Server user by deleting the user's entry in
- master.dbo.syslogins.
-
-
- Syntax
-
- sp_droplogin login_id
-
-
- Examples
-
- sp_droplogin victoria
-
- The user victoria has been dropped from SQL Server.
-
-
- Options
-
- login_id
- The name of the user as listed in master.dbo.syslogins.
-
-
- Comments
-
- Executing sp_droplogin drops a user login ID from SQL Server, deleting the
- user's entry from master.dbo.syslogins.
-
- The sp_droplogin procedure checks the current database (but no others) to
- see if the login ID to be dropped is a user there. You cannot execute
- sp_droplogin if the user exists in the current database.
-
-
- Messages
-
- Login dropped.
-
- The user's entry in master.dbo.syslogins has been deleted. The user no
- longer has access to SQL Server.
-
- No login exists with supplied name.
-
- The specified login ID does not exist.
-
- Only the System Administrator may execute this procedure.
-
- Only the System Administrator can add or drop login IDs. You aren't the
- System Administrator.
-
- User exists in current database. Drop user before dropping
- login.
-
- The specified login ID is a user in the current database. Drop the user from
- the current database with the sp_dropuser procedure. When this error message
- is generated, the database name, user's login ID, and user's name in the
- database are displayed.
-
-
- Permissions
-
- Execute permission defaults to the System Administrator.
-
-
- Tables Used
-
- master.dbo.syslogins, sysusers
-
-
- See Also
-
- sp_addlogin, sp_changedbowner, sp_dropuser, sp_helpuser
-
-
- sp_droptype
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Drops a user-defined datatype by deleting the type from systypes.
-
-
- Syntax
-
- sp_droptype typename
-
-
- Examples
-
- sp_droptype birthday
-
- This example drops the user-defined datatype named birthday.
-
-
- Options
-
- typename
- The name of a user-defined datatype that you own.
-
-
- Comments
-
- Executing sp_droptype deletes a user-defined datatype from systypes.
-
- A user datatype cannot be dropped if tables or other database objects
- reference it.
-
-
- Messages
-
- Type has been dropped.
-
- The user-defined type no longer exists in the current database.
-
- The type doesn't exist or you don't own it.
-
- You do not own a user datatype with that name.
-
- Type is being used. You cannot drop it.
-
- A user datatype referenced by a table or other database object cannot be
- dropped. Drop the tables and/or procedures first.
-
-
- Permissions
-
- Execute permission defaults to the Database Owner and datatype owner.
-
-
- Tables Used
-
- syscolumns, sysobjects, systypes, sysusers
-
-
- See Also
-
- sp_addtype, sp_rename
-
-
- sp_dropuser
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Drops a user from the current database by deleting the entry from sysusers.
-
-
-
- Syntax
-
- sp_dropuser username
-
-
- Examples
-
- sp_dropuser albert
-
- This statement drops the user albert from the current database. The user
- albert may no longer use the database.
-
-
- Options
-
- username
- The user's name in the current database's sysusers table.
-
-
- Comments
-
- Executing sp_dropuser deletes a user from the current database by deleting
- the user's row from sysusers.
-
- ────────────────────────────────────────────────────────────────────────────
- 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.
- ────────────────────────────────────────────────────────────────────────────
-
- The Database Owner of a database cannot be dropped.
-
- If other users have an alias to the user being dropped, their aliases are
- dropped. They are no longer able to access the database.
-
-
- Messages
-
- User has been dropped from current database.
-
- The specified user is no longer known to the database.
-
- Dependent aliases were also dropped.
-
- Other users had an alias to the user being dropped. Their aliases have been
- dropped, and they can no longer access the database.
-
- No user exists with the supplied name.
-
- The specified user doesn't exist in the current database.
-
- You cannot drop the 'Database Owner'.
-
- The Database Owner cannot be dropped, even by the System Administrator.
-
- You cannot drop user because he or she owns objects in database.
-
- Users who own objects in the current database cannot be dropped. Drop the
- owned objects first. When this error message is generated, a list of objects
- and their owners is displayed.
-
- You cannot drop user because he or she owns types in database.
-
- Users who own user datatypes in the current database cannot be dropped. Drop
- the owned datatypes first. When this error message is generated, a list of
- datatypes and their owners is displayed.
-
-
- Permissions
-
- Execute permission defaults to the Database Owner.
-
-
- Tables Used
-
- sysalternates, sysobjects, systypes, sysusers
-
-
- See Also
-
- sp_adduser, sp_droplogin, GRANT, REVOKE, USE
-
-
- sp_foreignkey
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Defines a foreign key on a table or view.
-
-
- Syntax
-
- sp_foreignkey tabname, pktabname, col1 [, col2, col3, ...,
- col8]
-
-
- Examples
-
- A. sp_foreignkey titles, publishers, pub_id
-
- The primary key of the publishers table is the pub_id column. The titles
- table also contains a pub_id column, which is a foreign key of publishers.
-
- B. sp_foreignkey orders, parts, part, subpart
-
- The primary key of the parts table has been defined with sp_primarykey as
- the partnumber and subpartnumber columns. The orders table contains the
- columns part and subpart, which make up a foreign key of parts.
-
-
- Options
-
- tabname
- The name of the table or view that contains the foreign key.
-
- pktabname
- The name of the table or view that has the primary key to which the
- foreign key applies.
-
- col1
- The name of the first column that makes up the foreign key. The foreign
- key must consist of at least one column and can have a maximum of eight
- columns.
-
-
- Comments
-
- Executing sp_foreignkey adds the key to the syskeys table.
-
- Keys are created to make explicit a logical relationship that is implicit in
- your database design.
-
- To display a report on the keys that have been defined, execute sp_helpkey.
-
-
- You must be the owner of the table or view to define its foreign key.
-
- The primary key of pktabname table or view must already be defined.
-
- The number and order of columns that make up the foreign key must be the
- same as the number and order of columns that make up the primary key. The
- datatypes of the primary and foreign keys must agree, but the lengths and
- nulltypes need not agree.
-
- When you define a foreign key, a common key is automatically defined between
- the pktabname and tabname tables or views, and added to syskeys.
-
- Foreign keys have been assigned within the master and model databases.
-
-
- Messages
-
- Foreign key table doesn't exist.
-
- The table or view specified with the tabname parameter doesn't exist in the
- current database.
-
- Primary key table doesn't exist.
-
- The table or view specified with the pktabname parameter doesn't exist in
- the current database or doesn't have a primary key defined.
-
- Only the owner of the table may define a foreign key.
-
- You are not the owner of the table or view.
-
- The table has no such first column.
-
- The table or view specified with the tabname parameter does not have a
- column of the specified name.
-
- Primary key does not exist with the same number of columns
-
- as the foreign key.
-
- The number of columns in the foreign key of tabname must be the same as the
- number of columns in the primary key of pktabname.
-
- Datatypes of the first column in the keys are different.
-
- The datatypes of the columns of the foreign key of tabname and the primary
- key of pktabname must be the same.
-
- New foreign key and common join added.
-
- The foreign key has been defined and added to syskeys. A common key has also
- been added to syskeys.
-
-
- Permissions
-
- Execute permission defaults to the tabname owner.
-
-
- Tables Used
-
- syscolumns, syskeys, sysobjects
-
-
- See Also
-
- sp_commonkey, sp_dropkey, sp_helpjoins, sp_helpkey, sp_primarykey, CREATE
- TRIGGER
-
-
- sp_help
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Reports information about a database object (any object listed in
- sysobjects) or about an SQL-Server-supplied or user-defined datatype.
-
-
- Syntax
-
- sp_help [objname]
-
-
- Examples
-
- A. sp_help
-
- Example A displays a brief listing of each object in sysobjects, giving its
- name, owner, and object type, and of each user-defined datatype in systypes,
- giving its name, storage type, case sensitivity, length, nulltype, default
- name, and rule name. The nulltype is 0 if null values are not allowed and 1
- if null values are allowed.
-
- B. sp_help publishers
-
- Example B displays information about the publishers table:
-
- Name Owner Type
- ----------- ----------- - ------------
- publishers dbo user table
-
- (0 rows affected)
-
- Data_located_on_segment When_created
- ----------------------- --------------------
- default Sep 15 1987 2:03PM
-
- (0 rows affected)
-
- ╓┌───────┌────────────┌────────────────┌───────┌────────────┌─────────────┌──
- ─────────────────────────────────────────────────────────────────────────────
- ─────────────────────────────────────────────────────────────────────────────
- Column_name Type Length Null values Rule
- Default_name
-
- ----------- --------------- ------ ----------- ---
- ------------
-
- pub_id char nocase 4 0 NULL pub_
-
- pub_name varchar nocase 40 1 NULL NULL
-
- city varchar nocase 20 1 NULL NULL
-
- state char nocase 2 1 NULL NULL
-
- (9 rows
- affected)
-
-
-
- index_name index_description index_keys
- ---------------- -------------------- -----------
- pubind clustered, unique pub_id
-
- (1 row affected)
-
- No defined keys for this object.
-
-
-
-
- Options
-
- objname
- The name of any object in sysobjects or any user-defined datatype in
- systypes. Database names are not acceptable.
-
-
- Comments
-
- The procedure looks for an object in the current database only.
-
- System procedures do not work on temporary tables because a procedure cannot
- access a temporary object unless it created the object itself during the
- current session.
-
- If sp_help prints "nocase" after char and varchar datatypes, the server is
- not case sensitive.
-
-
- Messages
-
- Object must be in your current database.
-
- The procedure gives information about objects in the current database only.
- You have included the database name in the objname parameter.
-
- Object does not exist in this database.
-
- The specified object does not exist in the current database.
-
- No defined keys for this object.
-
- The table or view has no defined keys.
-
-
- Tables Used
-
- master.dbo.spt_values, syscolumns, sysobjects, systypes
-
-
- Permissions
-
- Execute permission defaults to the public group.
-
-
- See Also
-
- sp_helpgroup, sp_helpindex, sp_helprotect, sp_helpuser
-
-
- sp_helpdb
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Reports information about a database or about all databases.
-
-
- Syntax
-
- sp_helpdb [dbname]
-
-
- Examples
-
- A. sp_helpdb pubs
-
- Example A displays information about the pubs database:
-
- name db_size owner dbid created status
- ------ -------- -------- ------ ----------- ----------------
- pubs 2 MB sa 4 Sep 15 1987 no options set
-
- (1 row affected)
-
- device size usage
- --------------------- ------------ ----------------
- master 2 MB data and log
-
- (1 row affected)
-
- B. sp_helpdb
-
- Example B displays information about all the databases on SQL Server.
-
-
- Options
-
- dbname
- The name of the database you want information on. Omitting this optional
- parameter results in a report on all databases.
-
-
- Comments
-
- Executing sp_helpdb reports on the specified database when the dbname is
- supplied or on all databases in master.dbo.sysdatabases when no parameter is
- supplied.
-
-
- Messages
-
- No such database exists.
-
- The specified database doesn't exist on SQL Server. Run the procedure
- without the dbname parameter to see a list of all the databases.
-
-
- Permissions
-
- Execute permission defaults to the public group.
-
-
- Tables Used
-
- #spdbdesc, master.dbo.spt_values, master.dbo.sysdatabases,
- master.dbo.sysdevices, master.dbo.syslogins, master.dbo.sysusages
-
-
- See Also
-
- sp_configure, sp_dboption, sp_renamedb, ALTER DATABASE, CREATE DATABASE
-
-
- sp_helpdevice
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Reports information about SQL Server's database devices and dump devices.
-
-
- Syntax
-
- sp_helpdevice [logical_name]
-
-
- Examples
-
- A. 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)
-
- Example A reports information about all database devices and dump devices on
- SQL Server.
-
- B. sp_helpdevice diskdump
-
- Example B reports information about the device named diskdump.
-
-
- Options
-
- logical_name
- The logical name of the database device or dump device you want
- information on. If you omit this parameter, information on all the
- database files and dump devices is displayed.
-
-
- Comments
-
- Executing sp_helpdevice displays information on the specified database
- device or dump device when logical_name is given or on all database devices
- and dump devices in master.dbo.sysdevices when no parameter is given.
-
- The sysdevices table contains database devices and dump devices. Database
- devices can be designated default database devices, which means that they
- can be used for database storage when a user executes the CREATE DATABASE or
- ALTER DATABASE statement and does not specify a database devicename, or
- gives the keyword DEFAULT. To make a database device a default database
- device, execute the sp_diskdefault system procedure.
-
- Database devices are added to the system with the DISK INIT statement. Dump
- devices are added to the system with the sp_addumpdevice system procedure.
-
- The status column in the report from sp_helpdevice contains a number that
- corresponds to the status description in the description column.
-
- The cntrltype column specifies the controller number of the device. For hard
- disk dump devices, the controller number is 2; for diskette dump devices,
- the controller number is 3 or 4. For database devices, it is almost always 0
- (unless your installation has a special type of disk controller).
-
- The device_number column is 0 for dump devices, 0 for the master database
- device, and between 1 and 9 for other database devices.
-
- The low and high columns represent virtual page numbers for database devices
- devices and disk dump devices.
-
- The high and low columns represent media capacity for diskette dump devices
- (high - low = number of 62K blocks).
-
-
- Messages
-
- No such i/o device exists.
-
- The database device or dump device name supplied for the logical_name
- parameter doesn't exist on SQL Server. Run the procedure without the
- logical_name parameter to see a list of all devices.
-
-
- Permissions
-
- Execute permission defaults to the public group.
-
-
- Tables Used
-
- #spdevtab, master.dbo.spt_values, master.dbo.sysdevices
-
-
- See Also
-
- sp_addumpdevice, sp_configure, sp_diskdefault, sp_dropdevice, sp_helpdb,
- sp_logdevice, sp_who, DISK INIT, DUMP DATABASE, DUMP TRANSACTION, LOAD
- DATABASE, LOAD TRANSACTION
-
-
- sp_helpgroup
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Reports information on a group or on all groups in the current database.
-
-
- Syntax
-
- sp_helpgroup [grpname]
-
-
- Examples
-
- A. sp_helpgroup hackers
-
- Example A displays information about the hackers group:
-
- Group_name Group_id Users_in_group Userid
- -------------- ---------- ------------- ------
- hackers 16384 ann 4
- hackers 16384 judy 3
-
- (3 rows affected)
-
- B. sp_helpgroup
-
- Example B displays information about all the groups in the current database:
-
-
- ────────────────────────────────────────────────────────────────────────────
- Group_name Group_id
- ------------ --------
- hackers 16384
- public 0
- (2 rows affected)
-
-
- Options
-
- grpname
- The name of a group in the database that has been created with
- sp_addgroup.
-
-
- Comments
-
- Executing sp_helpgroup reports on the specified group or, if no parameter is
- supplied, on all groups in the database.
-
-
- Messages
-
- No such group exists in the current database.
-
- The specified group does not exist in the current database. Execute the
- procedure without the grpname parameter to see a list of all the groups in
- the database.
-
-
- Permissions
-
- Execute permission defaults to the public group.
-
-
- Tables Used
-
- sysusers
-
-
- See Also
-
- sp_addgroup, sp_changegroup, sp_dropgroup, sp_helprotect, sp_helpuser,
- GRANT, REVOKE
-
-
- sp_helpindex
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Reports index information on a table.
-
-
- Syntax
-
- sp_helpindex tabname
-
-
- Examples
-
- sp_helpindex sysobjects
-
- This statement reports on the types of indexes on the sysobjects table:
-
- index_name index_description index_keys
- -------------------- -------------------- ---------------
- sysobjects clustered, unique id
- ncsysobjects nonclustered, unique name, uid
-
- (2 rows affected)
-
-
- Options
-
- tabname
- The name of a table in the current database.
-
-
- Comments
-
- Executing sp_helpindex lists up to eight indexes on a table.
-
- ────────────────────────────────────────────────────────────────────────────
- WARNING
-
- Only eight indexes are displayed when you execute sp_helpindex. The
- sysindexes system table contains information on all indexes.
- ────────────────────────────────────────────────────────────────────────────
-
-
- Messages
-
- Table does not exist.
-
- The name you gave for the tabname parameter does not exist in the current
- database.
-
- Table does not have any indexes.
-
- The table you named has no indexes.
-
- Table name must be in 'current' database.
-
- The name you gave for the tabname parameter includes a database reference.
- Name references must be local to the current database.
-
-
- Permissions
-
- Execute permission defaults to the public group.
-
-
- Tables Used
-
- #spindtab, master.dbo.spt_values, sysindexes
-
-
- See Also
-
- sp_help, sp_helpkey, CREATE INDEX, DROP INDEX, UPDATE STATISTICS
-
-
- sp_helpjoins
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Lists the columns in two tables or views that are likely to be joined.
-
-
- Syntax
-
- sp_helpjoins lefttab, righttab
-
-
- Examples
-
- sp_helpjoins sysobjects, syscolumns
-
- This statement displays a list of columns that are likely to be joined in
- the sysobjects and syscolumns tables:
-
- a1 a2 b1
- b2 c1 c2
- d1 d2 e1
- -------- -------- -------- -------- -------- -------
- -------- -------- -------- -------- -------- -------
- -------- -------- -------- -------- -------- -------
- id id NULL NULL NULL NULL
- NULL NULL NULL NULL NULL NULL
- NULL NULL NULL NULL NULL NULL
-
- (1 row affected)
-
-
- Options
-
- lefttab
- The first table or view.
-
- righttab
- The second table or view. The order of the parameters does not matter.
-
-
- Comments
-
- The column pairs that sp_helpjoins displays come from two sources. First,
- sp_helpjoins checks the syskeys table in the current database to see if any
- common keys have been defined on the two tables with sp_commonkey. If it
- doesn't find any common keys there, the procedure applies less restrictive
- criteria to come up with any keys that may be reasonably joined: it checks
- for keys with the same user datatypes and if that fails, for columns with
- the same name and datatype.
-
- The sp_helpjoins procedure does not create any joins.
-
-
- Messages
-
- First table doesn't exist.
-
- The table specified as the lefttab parameter is not a table or view in the
- current database.
-
- Second table doesn't exist.
-
- The table specified as the righttab parameter is not a table or view in the
- current database.
-
-
- Permissions
-
- Execute permission defaults to the public group.
-
-
- Tables Used
-
- syscolumns, syskeys, sysobjects
-
-
- See Also
-
- sp_commonkey, sp_foreignkey, sp_help, sp_helpkey, sp_primarykey, Joins
-
-
- sp_helpkey
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Reports information on primary, foreign, and common keys.
-
-
- Syntax
-
- sp_helpkey [objname]
-
-
- Examples
-
- sp_helpkey
-
- This statement displays information on the keys that have been defined in
- the database:
-
- keytype object related_object object_keys related_keys
- ------- ------- -------------- ---------- -----------------
- primary authors none au_id, *, * *, *, *, *, *, *
- foreign titleauthor authors au_id, *, * au_id, *, *, *, *
-
- (2 rows affected)
-
-
- Options
-
- objname
- The name of a table or view in the current database. If you don't specify
- a name, the procedure reports on all keys that have been defined in the
- current database.
-
-
- Comments
-
- Executing sp_helpkey lists information about all the primary, foreign, or
- common key definitions that reference the objname table, or about all the
- keys in the database. The object_keys and related_keys columns in the report
- refer to the names of the columns that make up the key.
-
- Keys are created to make explicit a logical relationship that is implicit in
- your database design. The information can be used by an application program.
-
-
-
- Messages
-
- Table or view name must be in 'current' database.
-
- The name supplied for the objname parameter included a database reference.
- You can get key information about local tables or views only.
-
- No such table or view in the current database.
-
- The name supplied for the objname parameter is not a table or view in the
- current database.
-
-
- Permissions
-
- Execute permission defaults to the public group.
-
-
- Tables Used
-
- master.dbo.spt_values, syskeys
-
-
- See Also
-
- sp_commonkey, sp_foreignkey, sp_help, sp_primarykey, CREATE TRIGGER
-
-
- sp_helprotect
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Reports permissions by database object and, optionally, by user for that
- object.
-
-
- Syntax
-
- sp_helprotect name [, username]
-
-
- Examples
-
- A. grant select on titles to judy
- grant update on titles to judy
- revoke update on titles(price) from judy
- sp_helprotect titles
-
- After the series of GRANT and REVOKE statements in example A, executing
- sp_helprotect titles results in this display:
-
- 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)
-
- B. sp_helprotect judy
-
- Example B displays all the permissions that judy has in the database.
-
-
- Options
-
- name
- The name of a table, view, or stored procedure; or the name of a user or
- group in the current database.
-
- username
- A user's name in the current database.
-
-
- Comments
-
- Executing sp_helprotect reports permissions on a database object. If the
- username parameter is supplied, only those users' permissions on the
- database object are reported. If name is not an object and username is also
- supplied, the permissions for the user or group are listed.
-
- The procedure looks for objects and users in the current database only.
-
-
- Messages
-
- Name must be in 'current' database.
-
- The name supplied for the name parameter included a reference to a database.
- The name must be local to the database.
-
- No such user exists in the database.
-
- The name supplied for username is not a user or group in the current
- database.
-
- No such object or user exists in the database.
-
- The name supplied for the name parameter is not an object, user, or group in
- the current database.
-
-
- Permissions
-
- Execute permission defaults to the public group.
-
-
- Tables Used
-
- master.dbo.spt_values, syscolumns, sysobjects, sysprotects, sysusers
-
-
- See Also
-
- sp_help, GRANT, REVOKE
-
-
- sp_helpsql
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Provides syntax for SQL statements, system procedures, and other special
- topics.
-
-
- Syntax
-
- sp_helpsql ["topic"]
-
-
- Examples
-
- A. sp_helpsql "disk init"
-
- Example A displays a brief definition of the DISK INIT statement along with
- its syntax.
-
- B. sp_helpsql functions
-
- Example B displays information on SQL Server functions.
-
- C. sp_helpsql "cre"
-
- Example C displays a list of all statements starting with the letters "CRE"
- (such as CREATE DATABASE, CREATE DEFAULT, and so on).
-
-
- Options
-
- topic
- The topic on which you want help. Help is available for all SQL
- statements, all system procedures, and the following special topics:
- datatypes, expressions, functions, wildcard characters, mathematical
- functions, and text functions. Be sure to include quotation marks around
- "topic".
-
-
- Comments
-
- You can enter just the first few letters of a topic. If these letters are
- enough to identify the topic, then help on the topic is displayed. For
- example, to get help on LOAD DATABASE, you could execute
-
- sp_helpsql "load d"
-
- To get help on all topics starting with "LOAD," execute
-
- sp_helpsql "load"
-
-
- Messages
-
- sp_helpsql supplies help on SQL statements, system procedures,
- and
- special topics:
-
- Syntax: sp_helpsql [topic]
-
- You executed sp_helpsql without specifying a topic. Supply a topic and
- re-execute sp_helpsql.
-
- You have entered a non-unique topic. More information can
- be obtained for the following topics:
-
- You have not entered enough letters to identify a unique topic. Supply the
- complete topic name. For example, enter "DISK INIT" rather than just "DISK".
-
-
- No help available for topic.
-
- There is no help available for the topic you entered.
-
-
- Permissions
-
- Execute permission defaults to the public group.
-
-
- sp_helptext
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Prints the text of a stored procedure, trigger, view, default, or rule.
-
-
- Syntax
-
- sp_helptext objname
-
-
- Examples
-
- A. sp_helptext ziprule
-
- ---------
- 1
-
- (1 row affected)
-
- text
- -------------------------------------------------
- create rule ziprule
- as @zip like "[0-9][0-9][0-9][0-9][0-9]"
-
- (1 row affected)
-
- Example A displays the text of ziprule. Since this rule is in the pubs
- database, this system procedure must be executed from pubs.
-
- B. sp_helptext sp_helptext
-
- ---------
- 3
-
- (1 row affected)
-
- text
- -------------------------------------------------------
-
- /* helptext 1.5 5/4/87 */
- create procedure sp_helptext
- @OBJNAME varchar(92)
- as
- /*
- **, Make sure the @objname is local to the current database. */
- if @objname like "%.%.%" and
- substring(@objname,, 1,, charindex(".",, @objname) - 1) != db_name()
-
- begin
- print
-
- "Object must be in your current database."
- return
- end
-
- /*
- **, Find out how many lines of text are coming back. */
- select count(*)
- from syscomments
- where id = object_id(@objname)
-
- /*
- **, Now get the text. */
- select text
- from syscomments
- where id = object_id(@objname)
-
- return
- (3 rows affected)
-
- Example B displays the text of sp_helptext. Since system procedures are
- stored in master, this system procedure must be executed from master.
-
-
- Options
-
- objname
- The name of the object for which you wish to see the CREATE text. It must
- be in the current database.
-
-
- Comments
-
- Executing sp_helptext prints out the number of rows in syscomments (255
- characters long each) that the object occupies, followed by the CREATE text
- of the object.
-
- The system procedure looks for the text in the syscomments table of the
- current database only.
-
-
- Messages
-
- Object must be in your current database.
-
- The objname parameter included a database name reference. The objname must
- be in the current database.
-
-
- Permissions
-
- Execute permission defaults to the public group.
-
-
- Tables Used
-
- syscomments
-
-
- See Also
-
- sp_help, CREATE DEFAULT, CREATE PROCEDURE, CREATE RULE, CREATE TRIGGER,
- CREATE VIEW
-
-
- sp_helpuser
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Reports information on users of a database.
-
-
- Syntax
-
- sp_helpuser [username]
-
-
- Examples
-
- A. sp_helpuser
-
- Example A displays information about all users in the current database:
-
- Users_name ID_in_db Group_name Login_id Default_db
- ----------- -------- ------------ ---------- ------------
- ann 4 hackers ann master
- dbo 1 public sa master
- guest 2 public NULL NULL
- judy 3 hackers judy master
-
- (4 rows affected)
-
- B. sp_helpuser dbo
-
- Example B displays information about the user Database Owner:
-
- Users_name ID_in_db Group_name Login_id Default_db
- ---------- -------- ---------- -------- ------------
- dbo 1 public sa master
-
- Users aliased to user.
- Login_id
- -------------------------------
- andy
- christa
- howard
- linda
-
-
- Options
-
- 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.
-
-
- Comments
-
- Executing sp_helpuser reports information on a specified user or on all
- users of the database.
-
- If the specified user is not listed in the current database's sysusers
- table, the procedure checks to see if the user has an alias to another user
- or is a groupname.
-
-
- Messages
-
- The name supplied is a group name.
-
- The name specified for the username parameter is a groupname.
-
- Users aliased to user.
-
- If the user has other users that have an alias to him or her, the names of
- the other users are listed.
-
- The name supplied is aliased to another user.
-
- The name supplied is not a user in the database, but has an alias to a user
- in the database.
-
- The name supplied is not a user, group, or aliased.
-
- The name supplied is unknown in the database as a login ID, user, or group.
-
-
-
- Permissions
-
- Execute permission defaults to the public group.
-
-
- Tables Used
-
- master.dbo.syslogins, sysalternates, sysusers
-
-
- See Also
-
- sp_adduser, sp_dropuser, sp_help, sp_helpgroup, GRANT, REVOKE, USE
-
-
-
-
-
- sp_lock
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Reports information on locks.
-
-
- Syntax
-
- sp_lock [spid1 [, spid2]]
-
-
- Examples
-
- A. 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)
-
-
- Example A displays information on all locks currently held in SQL Server.
-
- B. sp_lock 1
-
- ────────────────────────────────────────────────────────────────────────────
- spid locktype table_id page dbname
- ----- --------- --------- ----- ------
- 1 Sh_intent 16003088 0 master
-
- Example B displays information on locks currently held on spid 1.
-
-
- Options
-
- spid1
- The SQL Server process ID number from master.dbo.sysprocesses. Execute
- sp_who to get the spid of the lock. The parameter is optional. If it is
- not supplied, information on all locks is displayed.
-
- spid2
- Another SQL Server process ID number to check for locks. The parameter is
- optional.
-
-
- Comments
-
- Executing sp_lock reports information on processes that currently hold
- locks.
-
- Use the OBJECT_ID function to get a table's name from its ID number.
-
- If the system procedure is executed without parameters, it displays a list
- of the current locks.
-
- 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
- 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 running, or while
- an INSERT statement 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 then have to wait for the write transaction to finish.
-
-
- Permissions
-
- Execute permission defaults to the public group.
-
-
- Tables Used
-
- master.dbo.spt_values, master.dbo.syslocks
-
-
- See Also
-
- sp_who, KILL
-
-
- sp_logdevice
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Puts the syslogs system table, which contains the transaction log, on a
- separate database device.
-
-
- Syntax
-
- sp_logdevice dbname, database_device
-
-
- Examples
-
- create database products on default = 10, logs = 2
- <execute>
- sp_logdevice products, logs
- <execute>
-
-
- Options
-
- dbname
- The name of the database whose syslogs table you want to put on a specific
- logical device.
-
- database_device
- The logical name of the database device you want to put the syslogs table
- on. This database device must be listed in sysdevices (run sp_helpdevice
- for a report on the existing database devices) and have been named in the
- CREATE DATABASE statement that the database dbname was defined in.
-
-
- Comments
-
- Whenever you create a database larger than about 4 megabytes, you must
- assign it to at least two separate logical database devices with the CREATE
- DATABASE statement and then use sp_logdevice to put the database's syslogs
- table on one of these database devices. This is essential to guarantee that
- SQL Server's automatic recovery mechanism works correctly. Putting the
- transaction log on a database device different from the rest of the database
- also improves performance.
-
- A smaller database can be created on a single database device, and the
- transaction log can be stored together with the rest of the database if you
- use only the DUMP DATABASE statement and never DUMP TRANSACTION for backups.
-
-
- The size of the database device required for the transaction log varies
- according to the amount of update activity and the frequency of transaction
- log dumps. As a rule of thumb, allocate to the log device 10 percent to 25
- percent of the space you allocate to the database itself. It is best to
- start small, since space allocated to a transaction log device cannot be
- reclaimed.
-
- To increase the amount of allocated storage space on the transaction log
- database device, give the logical name of the log database device in the ON
- clause when you execute the ALTER DATABASE statement. Then execute
- sp_logdevice to cause the newly allocated space to be made available for the
- log.
-
- The database device on which you put syslogs is used only for the syslogs
- table. If you want to increase the amount of storage space allocated for the
- rest of the database, specify any database device other than the log
- database device when you execute the ALTER DATABASE statement.
-
- Use the DISK INIT statement to format a new physical database device to
- store databases and transaction logs on.
-
- If you run the DBCC CHECKALLOC statement after executing sp_logdevice, you
- will still see some pages for syslogs allocated on the database device.
- These pages are released for general database use only after they have been
- used by the transaction log and then dumped with DUMP TRANSACTION. After
- that, the transaction log will have been completely transferred to the
- database device named when you executed sp_logdevice.
-
- Only the owner of the database affected by sp_logdevice can execute it, but
- it can be executed in any database.
-
- See the SQL Server System Administrator's Guide for details.
-
-
- Messages
-
- No such database -- run sp_helpdb to list databases.
-
- No database with the supplied name exists. Run sp_helpdb to get a list of
- databases.
-
- No such device -- run sp_helpdevice to list SQL Server devices.
-
- The logical_name database device doesn't exist on SQL Server.
-
- Only the owner of the database may move the syslogs table.
-
- You aren't the owner of the dbname database.
-
- The specified device is not used by the database.
-
- The dbname database has no space allocated on the specified database device.
-
-
- Syslogs moved.
-
- The system procedure was successful, and the syslogs table is now located on
- the devname device.
-
-
- Permissions
-
- Execute permission defaults to the Database Owner of the named database.
-
-
- Tables Used
-
- master.dbo.sysdatabases, master.dbo.sysdevices, master.dbo.sysusages
-
-
- See Also
-
- sp_helpdevice, ALTER DATABASE, CREATE DATABASE, DISK INIT, DUMP DATABASE,
- DUMP TRANSACTION
-
-
- sp_monitor
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Displays statistics about SQL Server.
-
-
- Syntax
-
- sp_monitor
-
-
- Examples
-
- sp_monitor
-
- This statement reports information about how busy SQL Server has been:
-
- last_run current_run seconds
- ------------------ -------------------- -----------
- Sep 16 1987 4:52PM Sep 16 1987 4:53PM 55
-
- (0 rows affected)
-
- cpu_busy io_busy idle
- ----------------- --------------- -------------------
- 138(0)-0% 4(0)-0% 0(0)-0%
-
- (0 rows affected)
-
- ╓┌─┌──────────────────┌──────────────────┌──────────────────┌────────────────╖
- ────────────────────────────────────────────────────────────────────────────
- packets_received packets_sent packet_errors
- ----------------- ----------------- -----------------
- 720(3) 806(4) 3(0)
- (0 rows affected)
- total_read total_write total_errors connections
- ----------------- ----------------- ----------------- ------------
- ────────────────────────────────────────────────────────────────────────────
- ----------------- ----------------- ----------------- ------------
- 702(1) 23275(6) 0(0) 74(2)
- (0 rows affected)
-
-
-
- Options
-
- This system procedure has no options.
-
-
- Comments
-
- SQL Server keeps track of how much work it has done in a series of global
- variables. Executing sp_monitor displays the current values of these global
- variables and how much they have changed since the last time the procedure
- was run.
-
- 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 run.
- The percentage is the percent of time since sp_monitor was last run. For
- example, if the report showed cpu_busy as 4250(215)-68%, this would mean
- that the CPU had been busy 4250 seconds since SQL Server was last started
- up, 215 seconds since sp_monitor was last run, and 68% of the total time
- since sp_monitor was last run.
-
- The following are the columns in the sp_monitor report and their meanings:
-
- last_run
- The time the sp_monitor system procedure was last run.
-
- current_run
- The time the sp_monitor system procedure is being run.
-
- seconds
- The number of elapsed seconds since the sp_monitor system procedure was
- run.
-
- cpu_busy
- The number of seconds that SQL Server's CPU was doing SQL Server work.
-
- io_busy
- The number of seconds that SQL Server has spent doing input and output
- operations.
-
- idle
- The number of seconds 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 encountered by SQL Server while reading and writing
- packets.
-
- total_read
- The number of reads by SQL Server.
-
- total_write
- The number of writes by SQL Server.
-
- rdwr_errors
- The number of errors encountered by SQL Server while reading and writing.
-
- connections
- The number of logins or attempted logins to SQL Server.
-
-
- Permissions
-
- Execute permission defaults to the System Administrator.
-
-
- Tables Used
-
- master.dbo.spt_monitor
-
-
- See Also
-
- sp_who, Variables (Local and Global)
-
-
- sp_password
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Adds or changes a password for an SQL Server login ID.
-
-
- Syntax
-
- sp_password old, new [, login_id]
-
-
- Examples
-
- A. sp_password null, ok, victoria
-
- The System Administrator has changed victoria's password from the default
- (NULL) to ok. Notice that NULL is not enclosed in quotation marks.
-
- B. sp_password ok, mediumhot
-
- The user victoria has changed her password from ok to mediumhot.
-
-
- Options
-
- old
- The user's old password, which is listed in master.dbo.syslogins. In the
- usual installation, only the System Administrator has SELECT permission on
- this field. The default password for all users is NULL. The System
- Administrator can give NULL for this parameter no matter what the user's
- old password was. However, if the System Administrator gives any value
- besides NULL, SQL Server checks it against master.dbo.syslogins and
- rejects it if it is wrong.
-
- new
- The user's new password.
-
- login_id
- An option that only the System Administrator can use to change any user's
- password.
-
-
- Comments
-
- Any user can change his or her password with sp_password.
-
- Only the System Administrator can use the login_id parameter and change
- someone else's password.
-
- The old parameter is checked against the existing password for the user
- login_id (unless the user executing the procedure is the System
- Administrator and the old parameter is NULL) and must match for the password
- to be changed. Passwords are listed in master.dbo.syslogins.password. As
- permissions are set up on the SQL Server distribution media, only the System
- Administrator has SELECT permission on this field.
-
- To give the NULL password in response to the Password: prompt, press ENTER.
- To give the NULL password with isql and the /P option, use isql /P.
-
-
- Messages
-
- Password changed.
-
- The password was successfully changed. The new password will be required the
- next time the user logs in to SQL Server.
-
- Only System Administrator can use loginame option
- -- password not changed.
-
- Any user can change his or her own password, but only the System
- Administrator can change another user's password. You aren't the System
- Administrator.
-
- No such login -- no password changed.
-
- The name supplied for the login_id parameter does not exist on SQL Server.
-
- Old (current) password incorrect for user -- password not changed.
-
- The password supplied as the old parameter is not the current password.
-
-
- Permissions
-
- Execute permission defaults to the public group. Each member of the public
- group has permission to change only his or her own password. The System
- Administrator can change any user's password.
-
-
- Tables Used
-
- master.dbo.syslogins
-
-
- See Also
-
- sp_addlogin, sp_adduser, sp_defaultdb
-
-
- sp_primarykey
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Defines a primary key on a table or view.
-
-
- Syntax
-
- sp_primarykey tabname, col1 [, col2, col3, ..., col8]
-
-
- Examples
-
- A. sp_primarykey authors, au_id
-
- Example A makes the au_id field the primary key of authors.
-
- B. sp_primarykey employees, lastname, firstname
-
- Example B makes the combination of the fields lastname and firstname the
- primary key of the employees table.
-
-
- Options
-
- tabname
- The name of the table or view on which to define the primary key.
-
- col1
- The name of the first column that makes up the primary key. The primary
- key can consist of between one and eight columns.
-
-
- Comments
-
- Executing sp_primarykey adds the key to the syskeys table.
-
- Keys are created to make explicit a logical relationship that is implicit in
- your database design. The information can be used by an application program.
-
-
- To display a report on the keys that have been defined, execute sp_helpkey.
-
-
- Only the owner of a table or view can define its primary key.
-
- A table or view can have only one primary key.
-
- Primary keys have been assigned within the master and model databases.
-
-
- Messages
-
- No table exists with the supplied name.
-
- The table or view supplied as the tabname parameter doesn't exist in the
- current database.
-
- Only the owner of the table may define a primary key.
-
- You aren't the owner of the table or view and therefore cannot define its
- primary key.
-
- Primary key already exists on table -- drop key first.
-
- A table or view can have only have one primary key; one already exists on
- the table or view supplied as the tabname parameter.
-
- The table has no such first column.
-
- The column name supplied as one of the column names isn't a column in
- tabname.
-
- New primary key added.
-
- The primary key has been added to the syskeys table.
-
-
- Permissions
-
- Execute permission defaults to the tabname owner.
-
-
- Tables Used
-
- syscolumns, syskeys, sysobjects
-
-
- See Also
-
- sp_commonkey, sp_dropkey, sp_foreignkey, sp_helpjoins, sp_helpkey, CREATE
- TRIGGER
-
-
- sp_rename
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Changes the name of a user-created object in the current database.
-
-
- Syntax
-
- sp_rename objname, newname
-
-
- Examples
-
- A. sp_rename titles, books
-
- Example A renames the titles table to books.
-
- B. sp_rename "books.title", name
-
- Example B renames the title column in the books table to name.
-
- C. sp_rename tid, bookid
-
- Example C renames the user-defined datatype tid to bookid.
-
-
- Options
-
- objname
- The original name of the user object (table, view, column, stored
- procedure, trigger, default, or rule) or datatype. If the object to be
- renamed is a column in a table, objname must be in the form
- "table.column". You can rename an object in the current database only, and
- only if you own it. This rule holds for the Database Owner and System
- Administrator as well as for other users.
-
- newname
- The new name of the object or datatype. Names of objects and datatypes
- must follow the rules for identifiers.
-
-
- Comments
-
- Executing sp_rename changes the name of a user-created object or datatype.
-
- The names of most system datatypes and system objects cannot be changed.
-
- ────────────────────────────────────────────────────────────────────────────
- WARNING
-
- Although it is possible to rename system procedures and the model and master
- databases, doing so will cause serious system problems.
- ────────────────────────────────────────────────────────────────────────────
-
- You can change the name of an object or datatype in the current database
- only.
-
- A user can change the names only of those objects he or she owns. The
- Database Owner can change the name of any user's objects.
-
- ────────────────────────────────────────────────────────────────────────────
- WARNING
-
- Procedures, triggers, and views that depend on an object whose name has been
- changed work fine until they are recompiled. However, recompilation takes
- place for many reasons and without notification to the user. When the
- procedure, trigger, or view is recompiled by SQL Server, it will no longer
- work. The user must change its text to reflect the new name of the object on
- which it depends. The safest course is to change the definitions of any
- dependent objects when you execute sp_rename. You can find dependent objects
- with sp_depends.
- ────────────────────────────────────────────────────────────────────────────
-
-
- Messages
-
- Object must be in the current database.
-
- The name supplied for the objname parameter included a reference to a
- database. The object must be in the current database.
-
- Object name cannot be changed either because it does not
- exist in this database, or you don't own it, or it is a system name.
-
- The specified object is not an object or user-defined datatype, or you don't
- own the object.
-
- You do not own a table or column of that name in the
- current database.
-
- No column of the specified name exists in the specified table, or you don't
- own the table.
-
- Column name has been changed.
-
- The specified column name has been renamed to newname.
-
- Name of user-defined type name changed.
-
- The specified user-defined datatype has been renamed to newname.
-
- Newname already exists in sysobjects.
-
- The newname you specified is an existing name in the sysobjects table. Use a
- different newname.
-
- Object name has been changed.
-
- The specified object has been renamed to newname.
-
-
- Permissions
-
- Execute permission defaults to the object owners for their own objects.
- Execute permission defaults to the Database Owner for all objects.
-
-
- Tables Used
-
- syscolumns, sysobjects, systypes
-
-
- See Also
-
- sp_addtype, sp_depends, sp_renamedb, ALTER TABLE, CREATE DEFAULT, CREATE
- PROCEDURE, CREATE RULE, CREATE TABLE, CREATE TRIGGER, CREATE VIEW
-
-
- sp_renamedb
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Changes the name of a database.
-
-
- Syntax
-
- sp_renamedb oldname, newname
-
-
- Examples
-
- sp_renamedb accounting, financial
-
- Renames the accounting database to financial.
-
-
- Options
-
- oldname
- The original name of the database.
-
- newname
- The new name of the database. Names of objects and datatypes must follow
- the rules for identifiers.
-
-
- Comments
-
- Executing sp_renamedb changes the name of a database.
-
- Only the System Administrator can change the name of a database.
-
- ────────────────────────────────────────────────────────────────────────────
- WARNING
-
- Procedures, triggers, and views that depend on a database whose name has
- been changed work fine until they are recompiled. However, recompilation
- takes place for many reasons and without notification to the user. When the
- procedure, trigger, or view is recompiled by SQL Server, it will no longer
- work. The user must change its text to reflect the new name of the database
- on which it depends. The safest course is to change the definitions of any
- dependent objects when you execute sp_renamedb.
- ────────────────────────────────────────────────────────────────────────────
-
-
- Messages
-
- Only the System Administrator can change the name of a database.
-
- Only the System Administrator can change database names, and you aren't the
- System Administrator.
-
- No specified database currently exists.
-
- The database you specified for the oldname parameter is not currently a
- database.
-
- A database with the new name already exists.
-
- The database you specified for the newname parameter is already a database.
- Database names must be unique, so you must use another name.
-
- Database name changed.
-
- The database name was successfully changed.
-
-
- Permissions
-
- Execute permission defaults to the object owners for their own objects.
- Execute permission defaults to the Database Owner for all objects.
-
-
- Tables Used
-
- master.dbo.sysdatabases
-
-
- See Also
-
- sp_changedbowner, sp_depends, sp_helpdb, sp_rename, CREATE DATABASE
-
-
- sp_spaceused
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Displays the number of rows, the number of data pages, and the disk space
- used by an object or by each object in a database.
-
-
- Syntax
-
- sp_spaceused [objname]
-
-
- Examples
-
- A. sp_spaceused titles
-
- Example A reports on the amount of space allocated (reserved) for the titles
- table, the amount used for data, the amount used for index(es), and the
- available (unused) space:
-
- name rows reserved data index_size unused
- ------ ---- -------- ---- ---------- -------
- titles 18 48 KB 6 KB 4 KB 38 KB
-
- B. sp_spaceused
-
- Example B prints a summary of space used in the database:
-
- database_name database_size
- ------------- --------------------
- master 5 MB
-
- reserved data index_size unused
- --------- -------- ---------- -------
- 2176 KB 1374 KB 72 KB 730 KB
-
-
- Options
-
- objname
- The name of the table or index under being examined. If the parameter is
- omitted, a summary of space used in the database is displayed.
-
-
- Comments
-
- Executing sp_spaceused computes the number of rows, the number of data
- pages, and the disk space used by the object or by each object in the
- database.
-
- The system procedure looks for an object in the current database.
-
- After you drop an index, sp_spaceused does not report accurate information.
- This is a known problem.
-
-
- Messages
-
- Object does not exist.
-
- The name supplied for the objname parameter is not an object in the current
- database.
-
-
- Permissions
-
- Execute permission defaults to the public group.
-
-
- Tables Used
-
- master..sysusages, sysindexes
-
-
- See Also
-
- sp_help, CREATE INDEX, CREATE TABLE, DROP INDEX, DROP TABLE
-
-
- sp_unbindefault
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Unbinds a default value from a column or from a user-defined datatype.
-
-
- Syntax
-
- sp_unbindefault objname [, futureonly]
-
-
- Examples
-
- A. sp_unbindefault "employees.startdate"
-
- Example A unbinds the default from the startdate column of the employees
- table.
-
- B. sp_unbindefault ssn
-
- Example B unbinds the default from the user-defined datatype named ssn and
- all columns of that type.
-
- C. sp_unbindefault ssn, futureonly
-
- If you don't want to unbind defaults from existing ssn columns, use the
- string futureonly as an optional second parameter. Now the user datatype
- named ssn no longer has a default, but existing columns of type ssn are
- unaffected.
-
-
- Options
-
- objname
- The name of the table and column or datatype from which the default is to
- be unbound. If the parameter is not of the form "table.column", then
- objname is taken to be a usertype. When unbinding a default from a user
- datatype, any columns of that type that have the same default as the user
- datatype are also unbound. Columns of that type whose default has been
- changed are unaffected.
-
- futureonly
- Prevents existing columns of the specified user datatype from losing their
- defaults.
-
-
- Comments
-
- Executing sp_unbindefault removes a default from a column or from a user
- datatype in the current database.
-
- Columns of the user-defined datatype lose their current default unless their
- default has previously been changed or the value of the optional second
- parameter is futureonly.
-
-
- Messages
-
- Default unbound from table column.
-
- The table column supplied for the objname parameter no longer has any
- default.
-
- Default unbound from datatype.
-
- The user-defined datatype supplied for the objname parameter no longer has
- any default.
-
- You do not own a table with a column of that name.
-
- The table name supplied for the objname parameter either doesn't exist in
- the database or you don't own it. You can only bind or unbind defaults from
- columns in tables that you own.
-
- You do not own a user datatype of that name.
-
- The user-defined datatype supplied for the objname parameter either doesn't
- exist in the database or you don't own it. You can only bind or unbind
- defaults from datatypes that you own.
-
- Columns of the user datatype specified had their defaults unbound.
-
- Defaults on other columns of the user datatype specified were unbound unless
- their defaults had previously been changed.
-
- Column or user datatype must be in 'current' database.
-
- The objname parameter cannot include a database reference.
-
-
- Permissions
-
- Execute permission defaults to the object owner.
-
-
- Tables Used
-
- syscolumns, sysobjects, systypes
-
-
- See Also
-
- sp_bindefault, sp_bindrule, sp_unbindrule, CREATE DEFAULT, DROP DEFAULT
-
-
- sp_unbindrule
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Unbinds a rule from a column or user-defined datatype.
-
-
- Syntax
-
- sp_unbindrule objname [, futureonly]
-
-
- Examples
-
- A. sp_unbindrule "employees.startdate"
-
- Example A unbinds the rule from the startdate column of the employees table.
-
-
- B. sp_unbindrule ssn
-
- Example B unbinds the rule from the user-defined datatype named ssn. If you
- don't want to unbind the rule from existing ssn columns, use the string
- futureonly as an optional second parameter.
-
- C. sp_unbindrule ssn, futureonly
-
- The user datatype ssn no longer has a rule, but no existing ssn columns are
- affected.
-
-
- Options
-
- objname
- The name of the table and column or user-defined datatype from which the
- rule is to be unbound. If the parameter is not of the form "table.column",
- then objname is taken to be a usertype. When unbinding a rule from a user
- datatype, any columns of that type that have the same rule as the user
- datatype are also unbound. Columns of that type whose rule has been
- changed are unaffected.
-
- futureonly
- Prevents existing columns of the specified user datatype from losing their
- rule.
-
-
- Comments
-
- Executing sp_unbindrule removes a rule from a column or user datatype in the
- current database.
-
- If unbinding a rule from a table column, the objname parameter must be of
- the form "table.column".
-
- The rule is unbound from all existing columns of the user-defined datatype
- unless their default has previously been changed or the value of the
- optional second parameter is futureonly.
-
-
- Messages
-
- Rule unbound from table column.
-
- The table column supplied for the objname parameter no longer has any rule.
-
-
- Rule unbound from datatype.
-
- The user-defined datatype supplied for the objname parameter no longer has
- any rule.
-
- You do not own a table with a column of that name.
-
- The table name supplied for the objname parameter either doesn't exist in
- the database or you don't own it. You can only bind or unbind rules on
- tables that you own.
-
- You do not own a user datatype of that name.
-
- The user-defined datatype supplied for the objname parameter either doesn't
- exist in the database or you don't own it. You can only bind or unbind rules
- from datatypes that you own.
-
- Columns of the user datatype specified had their rules unbound.
-
- Rules on other columns of the user datatype specified were unbound unless
- their rules had previously been changed.
-
- Column or user datatype must be in 'current' database.
-
- The objname parameter cannot include a database reference.
-
-
- Permissions
-
- Execute permission defaults to the object owner.
-
-
- Tables Used
-
- syscolumns, sysobjects, systypes
-
-
- See Also
-
- sp_bindefault, sp_bindrule, sp_unbindefault, CREATE RULE, DROP RULE
-
-
- sp_who
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Reports information on current SQL Server users and processes.
-
-
- Syntax
-
- sp_who [login_id | "spid"]
-
-
- Examples
-
- A. sp_who
-
- Example A reports on the processes that are running on SQL Server:
-
- ╓┌───────┌──────────┌──────────┌──────────┌──────────┌───────┌──────────┌────
- ─────────────────────────────────────────────────────────────────────────────
- spid status login_id hostname blk dbname cmd
-
- ----- --------- -------- -------- --- ------- ------
-
- 1 sleeping sa plum 0 pubs AWAITI
-
- 2 sleeping sa 0 master NETWOR
-
- 3 sleeping sa 0 master CHECKP
- ─────────────────────────────────────────────────────────────────────────────
- 3 sleeping sa 0 master CHECKP
-
- 4 sleeping karenp plum 1 pubs SELECT
-
- 5 runnable karenp plum 0 pubs SELECT
-
- (5 rows
- affected)
-
-
-
- The spid column contains process identification numbers used in the
- TRANSACT-SQL KILL statement. The blk column contains the process IDs of the
- blocking process, if there is one. A blocking process (which can be infected
- or have an exclusive lock) is one that is holding resources that another
- process needs. In the previous example, process 4 (a SELECT on a table) is
- blocked by process 1 (a BEGIN TRANSACTION followed by an INSERT on the same
- table).
-
- B. sp_who victoria
-
- Example B reports on the processes the user victoria is running.
-
- C. sp_who "17"
-
- Example C reports on what SQL Server process number 17 is doing.
-
-
- Options
-
- login_id
- The user's login ID on SQL Server. If no name is specified, the procedure
- reports on all active users of SQL Server.
-
- spid
- The number of a specific process. You can supply a process number as a
- parameter if you enclose it in quotation marks (SQL Server is expecting a
- char type).
-
-
- Comments
-
- Executing sp_who reports information on a specified user, on a specified SQL
- Server process, or on all users currently running a process on SQL Server.
-
- Without parameters, the procedure reports which users are running what
- processes in all databases.
-
- The System Administrator can remove infected processes with the KILL
- statement.
-
-
- Messages
-
- No login exists with the supplied name.
-
- The name supplied for the login_id parameter does not exist on SQL Server.
-
-
- Permissions
-
- Execute permission defaults to the public group.
-
-
- Tables Used
-
- sysprocesses
-
-
- See Also
-
- sp_lock, KILL
-
-
-
-
-
-
- Chapter 3 Utility Programs
- ────────────────────────────────────────────────────────────────────────────
-
- This chapter consists of reference pages, in alphabetical order, for the SQL
- Server utility programs.
-
- Each utility program and its function is listed below:
-
- ────────────────────────────────────────────────────────────────────────────
- bcp
- Copies a database table to or from an operating system file in a
- user-specified format.
-
- bldmastr
- Builds the master database.
-
- console
- Dumps (or backs up) or loads (or restores) from a diskette drive.
-
- defncopy
- Copies definitions for specified views, rules, defaults, triggers,
- procedures, or reports from a database to an operating system file or from
- an operating system file to a database.
-
- isql
- Allows you to enter SQL statements and system procedures.
-
- sqlservr
- Starts SQL Server.
-
- ────────────────────────────────────────────────────────────────────────────
- Also, the startsql utility program is called by DB-LIBRARY; users cannot
- call it directly.
-
-
-
-
-
- bcp
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Copies a database table to or from an operating system file in a
- user-specified format.
-
-
- Syntax
-
- bcp /U login_id [[database_name.]owner.]table_name {in | out}
- datafile
- [/m maxerrors] [/f formatfile] [/e errfile]
- [/F firstrow] [/L lastrow] [/b batchsize]
- [/n] [/c]
- [/t field_term] [/r row_term]
- [/i inputfile] [/o outputfile]
- [/P password] [/S servername] [/v]
-
-
- Options
-
- /U login_id
- Allows the user to specify a login ID.
-
- 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 program will not execute.
-
- 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 when copying a table to or
- from a hard disk file or a single diskette. The pathname can be from 1 to
- 255 characters in length. To copy a table to or from multiple diskettes,
- datafile is a drive specifier only (such as a:).
-
- /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
- Performs the copy operation using the data's native (database) datatypes
- as the default. This option does not prompt for each field; it uses the
- default values.
-
- /c
- 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 inputfile
- Allows the user to specify the name of a file that redirects input to bcp.
-
- /o outputfile
- Allows the user to specify the name of a file that receives output
- redirected from bcp.
-
- /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).
-
- /S servername
- Allows the user to specify the name of the SQL Server to connect to. The
- servername is the name of the server computer on the network. This option
- is required when you are executing bcp from a remote computer on the
- network.
-
- /v
- Reports the current version of the bcp program.
-
- For more information and examples of how to use bcp see the SQL Server
- System Administrator's Guide.
-
-
- bldmastr
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Builds the master database.
-
-
- Syntax
-
- bldmastr [ /d database_device ] [ /c cntrltype ]
- [ /s size ] [ /C ] [ /r ] [ /m ]
-
-
- Options
-
- /d database_device
- The master database device to be configured.
-
- /c cntrltype
- The controller number for the master database device. Together, cntrltype
- and disk specify the device. By default, a master database device always
- sets the cntrltype to 0.
-
- /s size
- The size of the master database device in 2K blocks. The bldmastr program
- verifies that the master database device has at least 2K blocks unless the
- /m or /r option is used. The default size is 10 megabytes (or 5120 2K
- blocks).
-
- /C
- Tells bldmastr to build a master database device that is not case
- sensitive. The default is case sensitive. See "Identifiers" in Chapter 1
- for more information.
-
- /r
- Rewrites the configuration block that contains the system startup
- parameters with the default values without disturbing anything else
- contained on the disk. This option increments the version number without
- rebuilding the master database.
-
- /m
- Rewrites the master database only without changing the configuration block
- or reinitializing the master database device. If the /r and /m options are
- both used, then both the configuration block that contains the system
- start parameters (as derived from the system tables sysconfigures and
- syscurconfigs) and the master database are rewritten without initializing
- the rest of the disk.
-
-
- Comments
-
- The bldmastr program initializes the specified database device as an SQL
- Server master database device and builds the master and model databases on
- it. The bldmastr program also provides options for recovery from
- configuration errors and other disasters.
-
- The bldmastr program prompts for options that are not provided on the
- command line. If you don't supply any options, bldmastr prompts for each
- option as follows:
-
- master database name?
- master device controller number?
- master database size?
- master database starting offset?
- configuration only? (y or n) (same as /r)
- databases only? (y or n) (same as /m)
- case insensitive database? (y or n)
-
- In most cases, it is best to specify all bldmastr options on the command
- line rather than using bldmastr prompts. If you do not specify all options
- on the command line, be aware of the following limitations:
-
-
- ■ If you use the /d option only, the bldmastr program does not prompt
- you for other options, and it uses default values for /c, /s, and /C.
-
- ■ If you omit the /s option, the default size value is used, and you are
- not prompted for size.
-
-
-
- Files
-
- The bldmastr program contains all of the data needed to build the master and
- model databases. However, it does not include stored procedures,
- permissions, and so on. These are loaded during installation.
-
-
- console
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Dumps or loads from a diskette drive. The console program is used by the
- person responsible for dumping and loading a database.
-
- ────────────────────────────────────────────────────────────────────────────
- NOTE
- The console utility program is not available under Microsoft(R) Disk
- Operating System (MS-DOS(R)).
- ────────────────────────────────────────────────────────────────────────────
-
-
- Syntax
-
- console [/S servername]
-
- The console program must be running before a DUMP DATABASE or LOAD DATABASE
- statement can proceed. See the "Comments" section.
-
-
- Options
-
- /S servername
- Allows the user to specify the name of the SQL Server to connect to. The
- servername is the name of the server computer on the network. This option
- is required when you are executing console from a remote computer on the
- network.
-
-
- Messages
-
- The following are the console's prompts when writing to a diskette (dumping
- a database or transaction log) and their explanations:
-
-
- ■ Prompt to mount diskette when writing:
-
- Mount first diskette: mount diskette on drive device_name.
- Type n to quit, press ENTER when mounted.
-
-
- device_name Physical name of the diskette dump device
-
- ■ Prompt to change diskette when writing (only when a diskette has been
- filled):
-
- Change diskette: mount diskette on
- drive device_name.
- Type n to quit, otherwise press ENTER when mounted.
-
-
- device_name Physical name of the diskette dump device
-
- ■ Prompt to remove the last diskette:
-
- Remove the diskette - press ENTER when done.
-
-
-
- The following are console's prompts when reading from diskette (loading a
- database or transaction log) and their explanations:
-
-
- ■ Prompt to mount diskette when reading:
-
- Mount first diskette: mount diskette_name volume_number on
- drive device_name.
- Type n if no diskettes are available, otherwise press ENTER
- when mounted.
-
-
- ■ Prompt to change diskette when reading:
-
- Change diskette: mount database_name volume_number
- on drive device_name.
- Type n if no diskettes are available, otherwise press
- ENTER when mounted.
-
-
- diskette_name Usually name of the dump, first 17 characters of
- database_name
-
- volume_number Diskette volume sequence number
-
- device_name Physical diskette dump device name, for example,
- a:\sqltable.dat
-
- ■ Prompt for operator override when reading:
-
- Diskette diskette_nameM volume_number mounted instead of
- diskette_name volume_number.
- Type n if you want to change diskette, otherwise
- press ENTER to use this one.
-
-
-
- The first diskette name and volume number are read from the diskette that
- was mounted. The second diskette name and volume number refer to the
- diskette that was expected to be mounted. Mounting a diskette out of
- sequence or with a different diskette name is usually an error, but an
- operator might have a good reason to override this error and use the
- diskettes in the order mounted.
-
- Mounting diskettes that were made on different days as part of the same load
- is usually an error, but an operator might have a good reason to do so.
-
-
- Comments
-
- The console program is a process that supports DUMP and LOAD for diskette
- drives. Relevant statements include DUMP DATABASE, DUMP TRANSACTION, LOAD
- DATABASE, and LOAD TRANSACTION.
-
- The console program prompts the operator for information relating to
- mounting and unmounting diskettes.
-
- The console program can be started each time SQL Server is started and left
- running in another screen group continuously.
-
- If the console program stops for any reason, the operator is prompted to
- restart it. Do not attempt to stop the console program with CONTROL+C or any
- other interrupt signal from the operating system. If SQL Server stops,
- console automatically stops.
-
- Since the console workstation (which can be any screen group) prints prompts
- and messages for the operator, you may want to run it in a window on a
- Microsoft Operating System/2 (MS(R) OS/2) workstation located close to the
- diskette unit.
-
- Most of the console program's messages are self-explanatory. To stop a dump
- or load to a diskette, type n in response to any prompt to mount a new
- diskette.
-
- If two diskettes (that is, two dumps/loads) are being used at once, only one
- console is needed. The program prints messages one at a time, waiting for a
- response before going to the next prompt. For this reason, the messages
- include the name of the physical drive to which they pertain.
-
- Make sure that the diskette you are using is formatted and not
- write-protected.
-
- The console program is not available under MS-DOS.
-
- ────────────────────────────────────────────────────────────────────────────
- WARNING
-
- If the console utility program has been started and appears to be unusable,
- wait for up to one minute and try to use it again. (SQL Server may be in the
- process of fixing a broken console connection.)
- ────────────────────────────────────────────────────────────────────────────
-
-
- defncopy
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Copies definitions for specified views, rules, defaults, triggers, or
- procedures from a database to an operating system file or from an operating
- system file to a database.
-
- ────────────────────────────────────────────────────────────────────────────
- NOTE
-
- The defncopy program cannot copy table definitions.
- ────────────────────────────────────────────────────────────────────────────
-
-
- Syntax
-
- defncopy /U login_id [ /P password ] [ /S servername]
- { in filename dbname |
- out filename dbname [owner.]objectname [[owner.]objectname]...}
-
-
- Options
-
- /U login_id
-
- Allows the user to specify a login ID.
-
- /P password
- Allows the user to specify a password. If /P has no parameter, defncopy
- uses the default password (NULL); put /P by itself at the end of the
- command line. If /P is not used, the user is prompted for a password.
-
- /S servername
- Allows the user to specify the name of SQL Server to connect to. The
- servername is the name of the server computer on the network. This option
- is required if you are executing defncopy from a remote computer on the
- network.
-
- in, out
- Options that specify the direction of definition copy.
-
- filename
- The name of the operating system file destination or source for the
- definition copy. The copy out will overwrite an existing file.
-
- dbname
- The name of the database from or to which the definitions are being
- copied.
-
- objectname
- The name(s) of the database object(s) for defncopy to copy out. This
- parameter is not used when definitions are copied in.
-
-
- Comments
-
- The defncopy program is invoked directly from the operating system. It
- provides a noninteractive way of copying out definitions (CREATE statements)
- for views, rules, defaults, triggers, or procedures from a database to an
- operating system file. Alternatively, it will copy in all the definitions in
- a specified file.
-
- The infile or outfile name and the database name are required and must be
- unambiguous. For copying out, use filenames that reflect both the object's
- name and its owner.
-
- The defncopy program cannot be used to copy table definitions.
-
- You can copy out objects' definitions even if you do not have SELECT
- permission on these objects. (However, you do need SELECT permission on the
- sysobjects and syscomments tables for the relevant database.)
-
- You must have the appropriate CREATE permission for the type of object you
- are copying in. Objects copied in belong to the copier. A System
- Administrator copying in definitions on behalf of a user should be logged in
- as that user for that user to have proper access to the reconstructed
- database objects.
-
- A comment with more than 125 characters placed before a CREATE statement can
- cause defncopy to fail.
-
-
- isql
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Allows you to enter SQL statements and system procedures.
-
-
- Syntax
-
- isql /U login_id [/e] [/p] [/i] [/n]
- [ /c cmdend] [ /h headers] [ /w columnwidth] [ /s colseparator]
- [ /t timeout] [ /m errorlevel]
- [ /H wksta_name] [ /P password]
- [/S servername] [/i inputfile] [/o outputfile]
-
- When using isql, you can use the following commands:
-
- go
-
- Terminates a command.
-
- reset
- Clears any statements you have entered.
-
- ed
- Calls the editor.
-
- !! command
- Executes an operating system command.
-
- quit, exit, or CONTROL+C
- Exits from isql.
-
-
- Options
-
- /U login_id
-
- Allows the user to specify a login ID. Login IDs are case sensitive.
-
- /e
- Echos input.
-
- /p
- Prints out performance statistics.
-
- /n
- Removes numbering and the prompt symbol (>) from input lines.
-
- /c cmdend
- Allows the user to reset the command terminator. By default, commands are
- terminated and sent to SQL Server by entering go on a line by itself. When
- you reset the command terminator, do not use SQL reserved words or
- characters that have special meaning to the operating system, whether
- preceded by a backslash or not.
-
- /h headers
- Allows the user to specify how many rows to print between column headings.
- The default is to print headings only once for each set of query results.
-
- /w columnwidth
- Allows the user to set the screen width for output. The default is 80
- characters. When an output line has reached its maximum screen width, it
- is broken into multiple lines.
-
- /s colseparator
- Allows the user to reset the column separator character, which is blank by
- default. To use characters that have special meaning to the operating
- system (for example, |, ;, &, <, >), precede them with a backslash (\).
-
- /t timeout
- Allows the user to specify the number of seconds before a command times
- out. If no timeout is specified, a command runs indefinitely; however, the
- default timeout for logging in to isql is 60 seconds.
-
- /m errorlevel
- Allows the user to customize the display of error messages. The message
- number, state, and error level are displayed for errors of the specified
- severity level or higher. Nothing is displayed for errors of levels lower
- than the specified level.
-
- /H wksta_name
- Allows the user to specify a workstation name, changing the value in the
- dynamic system table sysprocesses, if he or she logs in from a different
- computer than usual. If no workstation name is specified, the current
- computer name is assumed.
-
- /P password
- Allows the user to specify a password. If the /P option is not used, isql
- prompts for a password. If the /P option is used at the end of the command
- line without any password, isql uses the default password (NULL).
- Passwords are case sensitive.
-
- /S servername
- Allows the user to specify the name of the SQL Server to connect to. The
- servername is the name of the server computer on the network. This option
- is required if you are executing isql from a remote computer on the
- network.
-
- /i inputfile
- Allows the user to specify the name of the file that contains a batch of
- SQL statements or stored procedures. The less-than symbol (<) can be used
- in place of /I.
-
- /o outputfile
- Allows the user to specify the name of the file that receives output from
- isql. The greater-than symbol (>) can be used in place of /o.
-
-
- Examples
-
- A. isql /p /s#
-
- B. isql /U joe
-
- Password:
-
- 1>select *
- 2>from authors
- 3>where city = "Oakland"
- 4>go
-
- Examples A and B execute the command.
-
- C. isql /U joe /P abracadabra
-
- 1>select *
- 2>from authors
- 3>where city = "Oakland"
- 4>ed
-
- Example C puts you in a text file where you can edit the query. When you
- save the file, you are returned to isql. The query is displayed. Type go to
- execute it.
-
- D. isql /U alma /P
-
- 1>select *
- 2>from authors
- 3>where city = "Oakland"
- 4>reset
- 1>quit
- %
-
- In example D, the reset command clears any statements you have entered. The
- quit command returns you to the operating system.
-
-
- Comments
-
- The isql program is started directly from the operating system. It accepts
- SQL commands and sends them to SQL Server. The results are formatted and
- printed on standard output. The isql program exits with quit or exit.
-
- Terminate a command by typing a line beginning with the command terminator.
- The default command terminator is go. You can follow the command terminator
- with an integer to specify how many times the command should be run. For
- example, to cause this command to be executed 100 times, type
-
- select x = 1
- go 100
-
- The results are printed once, at the end of execution.
-
- The user can call an editor on the current query buffer by entering ed as
- the first word on a line. Operating system commands can also be executed by
- starting a line with two exclamation points (!!) followed by the command.
- The editor is defined in the EDITOR environment variable. The default is
- "edlin".
-
- The existing query buffer can be cleared by typing reset on a line by
- itself. It causes any pending input to be discarded.
-
- The command terminator (go by default), reset, ed, !!, exit, quit, and
- CONTROL+C are recognized only if they appear at the very beginning of a
- line, immediately following the isql prompt. Anything entered on that line
- after these keywords is disregarded by isql.
-
- To use isql interactively, give the isql command (and any of the options) at
- your operating system prompt.
-
- You can read in a file containing a query for execution by isql by typing a
- command similar to the one shown below:
-
- isql /U alma /P /i stores.qry
-
- The file must include a command terminator. The results are displayed on the
- user's workstation.
-
- You can read in a file containing a query and direct the results to another
- file by typing a command similar to the one shown below:
-
- isql /U alma /P /i titles.qry /o titles.res
-
- Case is significant for isql options.
-
- When using isql interactively, you can read an operating system file into
- the command buffer with :r filename. Do not include a command terminator in
- the file; enter the terminator interactively once you have finished editing.
-
-
- You can include comments in a TRANSACT-SQL statement submitted to SQL Server
- by isql. Open a comment with "/*". Close it with "*/". Comments can be
- nested.
-
- For example:
-
- select au_lname, au_fname
- /*retrieve authors' last and first names*/
- from authors, titles, titleauthor
- where authors.au_id = titleauthor.au_id
- and titles.title_id = titleauthor.title_id
- /*this is a three-way join that links authors
- **to the books they have written.*/
-
- ────────────────────────────────────────────────────────────────────────────
- NOTE
-
- Do not include a go command within a comment. A go command within a comment
- produces an error message.
- ────────────────────────────────────────────────────────────────────────────
-
-
- sqlservr
- ────────────────────────────────────────────────────────────────────────────
-
-
- Function
-
- Starts SQL Server.
-
-
- Syntax
-
- sqlservr /dmaster_phys_name [/eerror_log_phys_name] [/m]
-
-
- Options
-
- /dmaster_phys_name
- The full pathname of the master database device.
-
- /eerror_log_phys_name
- The full pathname of the error log file for SQL Server system-level error
- messages.
-
- /m
- Starts SQL Server in single user mode.
-
-
- Comments
-
- Note that the names of the master database device and the error log file
- cannot be preceded with a blank.
-
- This program should only be used to start SQL Server in single-user mode.
-
-
-
-
-
-
- Appendix A 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
- 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
-
- 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
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- 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
-
- ────────────────────────────────────────────────────────────────────────────
-
-
-
-
- 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
- that describe an object or column)
-
- language smallint reserved
-
- text varchar(255) Actual text of SQL definition statement
-
- ────────────────────────────────────────────────────────────────────────────
-
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
-
-
-
- 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
-
- 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 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
-
- 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
- ────────────────────────────────────────────────────────────────────────────
- 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
- 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
- ────────────────────────────────────────────────────────────────────────────
- 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 666666 Serial Number 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
-
- 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
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- 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
- 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
- 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)
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- 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:
- 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
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- 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
-
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- 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)
-
- 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
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- 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:
- 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
-
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- 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
-
- 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
- ────────────────────────────────────────────────────────────────────────────
- 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
- 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
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- 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
- ────────────────────────────────────────────────────────────────────────────
- 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
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- 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
- 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
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- suid smallint Server user ID
-
- status smallint reserved
-
- accdate datetime reserved
-
- totcpu int reserved
-
- 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
-
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- 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
-
- 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
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- 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)
-
- 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
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- 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
-
- 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
-
- 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
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- kpid smallint Kernel process ID
-
- status char(10) Process ID status (for example, runnable, sleeping,
- and so on)
-
- 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
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- command
-
- memusage int Amount of memory allocated to process
-
- 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
-
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- uid smallint ID of user or group to which this permission
- applies
-
- 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
-
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- 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
- 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
- System Datatype ID Number
- ────────────────────────────────────────────────────────────────────────────
- binary 45
- bit 50
- char 4
- datetime 61
- 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
- System Datatype ID Number
- ────────────────────────────────────────────────────────────────────────────
- 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
-
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- type tinyint Physical storage datatype
-
- length tinyint Physical length of datatype
-
- tdefault int ID of stored procedure that generates default
- for this datatype
-
- 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
- ────────────────────────────────────────────────────────────────────────────
- 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.
- Column Datatype Description
- ────────────────────────────────────────────────────────────────────────────
- is 0.
-
- name sysname Username or groupname, unique in this database.
-
- environ varchar(255) reserved
-
- ────────────────────────────────────────────────────────────────────────────
-
-
-
-
- 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 A.1: System Tables Relationship Chart -
-
- (This figure may be found in the printed book.)
-
-
-
-
-
-
- Appendix B 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
- 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
- au_id title_id au_ord royaltyper
- ────────────────────────────────────────────────────────────────────────────
- 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
- 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
- stor_id ord_num date qty payterms title_id
- ────────────────────────────────────────────────────────────────────────────
- 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
-
- 8042 Bookbeat 679 Carson St. Portland OR 89076
-
- 6380 Eric the Read Books 788 Catamaugus Ave. Seattle WA 98056
-
- stor_id stor_name stor_address city state zip
- ────────────────────────────────────────────────────────────────────────────
- 7896 Fricative Bookshop 89 Madison St. Fremont CA 90019
-
- ────────────────────────────────────────────────────────────────────────────
-
-
-
-
- B.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
- BU2075 5001 7000 16
- BU2075 7001 10000 18
- BU2075 10001 12000 20
- BU2075 12001 14000 22
- BU2075 14001 50000 24
- title_id lorange hirange royalty
- ────────────────────────────────────────────────────────────────────────────
- 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
- MC3021 8001 10000 20
- MC3021 10001 12000 22
- MC3021 12001 50000 24
- TC3218 0 2000 10
- TC3218 2001 4000 12
- title_id lorange hirange royalty
- ────────────────────────────────────────────────────────────────────────────
- 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
- TC3218 14001 50000 24
- PC8888 0 5000 10
- PC8888 5001 10000 12
- PC8888 10001 15000 14
- PC8888 15001 50000 16
- title_id lorange hirange royalty
- ────────────────────────────────────────────────────────────────────────────
- 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
- BU1111 28001 50000 24
- MC2222 0 2000 10
- MC2222 2001 4000 12
- MC2222 4001 8000 14
- MC2222 8001 12000 16
- title_id lorange hirange royalty
- ────────────────────────────────────────────────────────────────────────────
- 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
- BU7832 0 5000 10
- BU7832 5001 10000 12
- BU7832 10001 15000 14
- BU7832 15001 20000 16
- BU7832 20001 25000 18
- title_id lorange hirange royalty
- ────────────────────────────────────────────────────────────────────────────
- 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
- 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
-
- 722-51-5454 DeFrance Michel 219 3 Balding Pl. Gary
- 547-9982
-
- au_id au_lname au_fname phone address city
-
- 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.
-
- 724-80-9391 MacFeather Stearns 415 44 Upland Oakland
- 354-7128 Hts.
-
- au_id au_lname au_fname phone address city
-
- 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.
-
- 172-32-1176 White Johnson 408 10932 Bigge Menlo
- 496-7223 Rd. Park
-
- au_id au_lname au_fname phone address city
-
- 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
- Dr.
-
- ─────────────────────────────────────────────────────────────────────────────
-
- au_id au_lname au_fname phone address city
-
-
-
- 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 ─ ─ ─ ─ ─
-
- Rule ─ ─ ─ ─ ─ ─ ─ ─
-
- Trigger deltitle3 ─ ─ ─ ─ ─ ─ ─
- title_id title type pub_id price advan roya yt
- ce lty sa
- s
- 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?
-
-
-
-
- BU2075 You Can Combat business 0736 $2.99 $10125.00 24 18722
- Computer
- Stress!
-
- title_ title type pub_i price advance royal ytd_s
- id d ty ales
- ─────────────────────────────────────────────────────────────────────────────
-
-
-
-
- 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
- Mediterranean
-
-
- MC3026 The Psychology UNDECIDED 0877 NULL NULL NULL NULL
- title_ title type pub_i price advance royal ytd_s
- id d ty ales
- ─────────────────────────────────────────────────────────────────────────────
- 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
- Algorithm
-
-
-
- title_ title type pub_i price advance royal ytd_s
- id d ty ales
- ─────────────────────────────────────────────────────────────────────────────
-
-
- 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
- Balance Sheets
-
- MC2222 Silicon Valley mod_cook 0877 $19.99 $0.00 12 2032
- Gastronomic
- title_ title type pub_i price advance royal ytd_s
- id d ty ales
- ─────────────────────────────────────────────────────────────────────────────
- 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
-
-
-
- PS1372 Computer psychology 0877 $21.59 $7000.00 10 375
- Phobic and
- Non-Phobic
- Individuals:
- title_ title type pub_i price advance royal ytd_s
- id d ty ales
- ─────────────────────────────────────────────────────────────────────────────
- 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 B.1 shows the structure of the pubs sample database.
-
- (This figure may be found in the printed book.)
-
-
-
-
-
-
- Appendix C TRANSACT-SQL Keywords
- ────────────────────────────────────────────────────────────────────────────
-
- TRANSACT-SQL statements contain keywords listed in this appendix. Keywords
- cannot be used for the names of database objects, such as databases, tables,
- rules, defaults, and so on, but they can be used for the names of local
- variables and stored procedure parameter names.
-
- ADD DESC ROLLBACK
- ALL DISK KILL ROWCOUNT
- ALTER DISTINCT RULE
- AND DROP LIKE
- ANY DUMMY LINENO SAVE
- AS DUMP LOAD SELECT
- ASC SET
- AVG ELSE MAX SETUSER
- END MIN STATISTICS
- BEGIN ERRLVL SUM
- BETWEEN ERROREXIT, EXEC NONCLUSTERED
- BREAK EXECUTE NOT TABLE
- BROWSE EXISTS NULL TAPE
- BULK EXIT TEXTSIZE
- BY OFF TO
- FILLFACTOR OFFSETS TRAN
- CHECKPOINT FOR ON TRANSACTION
- CLUSTERED FROM ONCE TRIGGER
- COMMIT OR TRUNCATE
- COMPUTE GETDEFAULT ORDER
- CONFIRM GOTO OVER, PREPARE UNIQUE
- CONTINUE GRANT PRINT UPDATE
- CONTROLROW GROUP PROC USE
- CONVERT PROCEDURE
- COUNT HAVING PROCESSEXIT VALUES
- CREATE HOLDLOCK PUBLIC VIEW
-
- DATABASE IF RAISERROR WAITFOR
- DBCC IN READTEXT WHERE
- DEBUG INDEX RECONFIGURE WHILE
- DECLARE INSERT RETURN WITH
- DEFAULT INTO REVOKE WRITETEXT
- DELETE IS
-
-
-
-
- INDEX
- ──────────────────────────────────────────────────────────────────────────
-
-
-
- + string function
- /*
- */
- **
-
- A
- ABS mathematical function
- ACOS mathematical function
- Aggregate functions
- AVG
- COUNT
- COUNT(*)
- MAX
- MIN
- SUM
- Alias
- add
- remove
- ALTER DATABASE
- ALTER TABLE
- ASCII string function
- ASIN mathematical function
- ATAN mathematical function
- ATN2 mathematical function
- AVG aggregate function
-
- B
- Batch queries
- bcp utility program
- BEGIN TRANSACTION
- BEGIN...END
- binary datatype
- bit datatype
- bldmastr utility program
- Boolean expression
- BREAK
- Browse mode
-
- C
- Case sensitivity
- CEILING mathematical function
- char datatype
- CHAR string function
- Characters
- wildcard
- CHARINDEX string function
- CHECKPOINT
- Clauses
- COMPUTE
- FOR BROWSE
- GROUP BY
- HAVING
- ORDER BY
- WHERE
- Clustered index
- Column
- add
- bind default value to
- bind rule to
- unbind default value from
- unbind rule from
- COL_LENGTH system function
- COL_NAME system function
- Comments
- COMMIT TRANSACTION
- Common key
- COMPUTE clause
- Configuration variable
- display or change
- console utility program
- CONTINUE
- Control-of-flow language
- Conversion function
- COS mathematical function
- COT mathematical function
- COUNT aggregate function
- COUNT(*) aggregate function
- CREATE DATABASE
- CREATE DEFAULT
- CREATE INDEX
- CREATE PROCEDURE
- CREATE RULE
- CREATE TABLE
- CREATE TRIGGER
- CREATE VIEW
-
- D
- Data
- change
- Database device
- help
- remove
- set defaults
- storage space for
- Database object
- help
- rename
- space used by
- Database options
- dbo use only
- no chkpt on recovery
- read only
- select into/bulkcopy
- single user
- trunc. log on chkpt.
- Database Owner
- change
- Database
- add group
- add new user
- back up
- change current
- change default
- change owner
- copy definitions to and from file
- create
- default size
- display object dependency
- display or change options
- dump
- help
- load
- master
- model
- pubs
- remove group from
- remove user
- remove
- rename
- restore damaged
- sample
- select row
- size
- space on disk
- DATALENGTH string function
- Datatype
- bit
- char
- Datatypes
- binary
- bind default
- bind rule
- create user-defined
- datetime
- float
- help
- image
- int
- money
- remove user-defined
- smallint
- sysname
- text
- text/image
- timestamp
- tinyint
- unbind default value from
- unbind rule from
- user-defined
- user_type_name
- varbinary
- varchar
- Date functions
- DATEDIFF
- DATENAME
- DATEPART
- GETDATE
- DATEDIFF date function
- DATENAME date function
- DATEPART date function
- datetime datatype
- DB-LIBRARY
- DBCC (Database Consistency Checker)
- DBCC (database consistency checker)
- dbo use only database option
- DB_ID system function
- DB_NAME system function
- DECLARE
- Default database
- change
- Default value
- bind to column or datatype
- create
- help
- remove
- unbind from column or datatype
- defncopy utility program
- DEGREES mathematical function
- DELETE
- DIFFERENCE string function
- DISK INIT
- DISK REFIT
- DISK REINIT
- DROP DATABASE
- DROP DEFAULT
- DROP INDEX
- DROP PROCEDURE
- DROP RULE
- DROP TABLE
- DROP TRIGGER
- DROP VIEW
- DUMP DATABASE
- Dump database
- Dump device
- add
- help
- remove
- DUMP TRANSACTION
-
- E
- ELSE
- END
- Error message
- EXECUTE
- Exit
- from query or procedure
- EXP mathematical function
- Expressions
- Boolean
-
- F
- float datatype
- FLOOR mathematical function
- FOR BROWSE clause
- Foreign key
- Functions
- aggregate
- conversion
- date
- mathematical
- row aggregate
- scalar aggregate
- string
- system
- text/image
- vector aggregate
-
- G
- GETDATE date function
- Global variables
-
- @CPU_BUSY
- @ERROR
- @IDLE
- @IO_BUSY
- @MAX_CONNECTIONS
- @NESTLEVEL
- @PACKET_ERRORS
- @PACK_RECEIVED
- @PACK_SENT
- @PROCID
- @ROWCOUNT
- @TEXTSIZE
- @TIMETICKS
- @TOTAL_ERRORS
- @TOTAL_READ
- @TOTAL_WRITE
- @TRANCOUNT
- @VERSION
- go command
- GOTO label
- GRANT
- GROUP BY and HAVING clauses
- Group
- add to database
- change user
- help
- remove from database
-
- H
- Help
- database device
- database objects
- databases
- datatypes
- default text
- dump device
- group
- index
- joins
- key
- permissions
- rule text
- statements
- stored procedure text
- syntax
- trigger text
- user
- view text
- HOST_ID system function
- HOST_NAME system function
-
- I
- Identifiers
- IF...ELSE
- image datatype
- Image functions
- PATINDEX
- SET TEXTSIZE
- TEXTPTR
- TEXTVALID
- Index
- clustered
- create
- help
- nonclustered
- remove
- INDEX_COL system function
- INSERT
- int datatype
- ISNULL system function
- isql utility program
- Isql utility program
-
- J
- Joins
- help
-
- K
- Key
- common
- foreign
- help
- primary
- remove
- Keywords
- KILL
-
- L
- Label
- user-defined
- LOAD DATABASE
- Load database
- LOAD TRANSACTION
- Local variables
- Locks
- report on
- LOG mathematical function
- LOG10 mathematical function
- Login authorization
- add
- remove
- LOWER string function
- LTRIM string function
-
- M
- master database
- Mathematical functions
- ABS
- ACOS
- ASIN
- ATAN
- ATN2
- CEILING
- COS
- COT
- DEGREES
- EXP
- FLOOR
- LOG
- LOG10
- PI
- POWER
- RADIANS
- RAND
- ROUND
- SIGN
- SIN
- SQRT
- TAN
- MAX aggregate function
- Message
- print on screen
- MIN aggregate function
- model database
- money datatype
-
- N
- Nest statements
- no chkpt on recovery database option
- Nonclustered index
- Notational conventions
- Null values
-
- O
- OBJECT_ID system function
- OBJECT_NAME system function
- Operating system file
- copy definitions to and from database
- Option
- display or change database
- set
- ORDER BY clause
-
- P
- Parameters
- Password
- add or change
- PATINDEX text/image function
- Permissions
- assign
- help
- revoke
- PI mathematical function
- POWER mathematical function
- Primary key
- PRINT
- Procedure
- create
- exit
- remove
- stored
- system
- system, enter with isql
- Process
- current
- pubs sample database
-
- Q
- Query
- batch
-
- R
- RADIANS mathematical function
- RAISERROR
- RAND mathematical function
- read only database option
- READTEXT
- RECONFIGURE
- Rename
- database object
- database
- table
- REPLICATE string function
- Reserved words
- RETURN
- REVOKE
- RIGHT string function
- ROLLBACK TRANSACTION
- ROUND mathematical function
- Row aggregate functions
- Row
- delete from table
- insert to table or view
- remove
- retrieve from database
- RTRIM string function
- Rule
- bind to column or datatype
- create
- help
- remove
- unbind from column or datatype
-
- S
- SAF
- Sample database, pubs
- SAVE TRANSACTION
- Savepoint
- Scalar aggregate function
- Search conditions
- select into/bulkcopy database option
- SELECT
- Set options
- SET TEXTSIZE text/image function
- SET
- Setup program
- SETUSER
- Shutdown system
- SHUTDOWN
- SIGN mathematical function
- SIN mathematical function
- single user database option
- smallint datatype
- SOUNDEX string function
- SPACE string function
- Space used by database object
- sp_addalias
- sp_addgroup
- sp_addlogin
- sp_addtype
- sp_addumpdevice
- sp_adduser
- sp_bindefault
- sp_bindrule
- sp_changedbowner
- sp_changegroup
- sp_commonkey
- sp_configure
- sp_dboption
- sp_defaultdb
- sp_depends
- sp_diskdefault
- sp_dropalias
- sp_dropdevice
- sp_dropgroup
- sp_dropkey
- sp_droplogin
- sp_droptype
- sp_dropuser
- sp_foreignkey
- sp_help
- sp_helpdb
- sp_helpdevice
- sp_helpgroup
- sp_helpindex
- sp_helpjoins
- sp_helpkey
- sp_helprotect
- sp_helpsql
- sp_helptext
- sp_helpuser
- sp_lock
- sp_logdevice
- sp_monitor
- sp_password
- sp_primarykey
- sp_rename
- sp_renamedb
- sp_spaceused
- sp_unbindefault
- sp_unbindrule
- sp_who
- SQL Server Administration Facility (SAF)
- SQL Server
- shutdown system
- start
- sqlservr utility program
- Sqlservr utility program
- SQRT mathematical function
- Statements
- ALTER DATABASE
- ALTER TABLE
- BEGIN TRANSACTION
- BEGIN
- BREAK
- CHECKPOINT
- COMMIT TRANSACTION
- CONTINUE
- CREATE DATABASE
- CREATE DEFAULT
- CREATE INDEX
- CREATE PROCEDURE
- CREATE RULE
- CREATE TABLE
- CREATE TRIGGER
- CREATE VIEW
- DBCC
- DECLARE
- DELETE
- DISK INIT
- DISK REFIT
- DISK REINIT
- DROP DATABASE
- DROP DEFAULT
- DROP INDEX
- DROP PROCEDURE
- DROP RULE
- DROP TABLE
- DROP TRIGGER
- DROP VIEW
- DUMP DATABASE
- DUMP TRANSACTION
- ELSE
- END
- enter with isql
- EXECUTE
- GOTO
- GRANT
- help
- IF
- IF...ELSE
- INSERT
- KILL
- LOAD DATABASE
- LOAD TRANSACTION
- nest
- PRINT
- RAISERROR
- READTEXT
- RECONFIGURE
- RETURN
- REVOKE
- ROLLBACK TRANSACTION
- SAVE TRANSACTION
- SELECT
- SET
- SETUSER
- SHUTDOWN
- TRUNCATE TABLE
- UPDATE STATISTICS
- UPDATE
- USE
- WAITFOR
- WHILE
- WRITETEXT
- Statistics
- display
- update
- Stored procedure
- execute
- help
- remove
- STR string function
- String functions
- +
- CHAR
- CHARINDEX
- DATALENGTH
- DIFFERENCE
- LOWER
- LTRIM
- REPLICATE
- RIGHT
- RTRIM
- SOUNDEX
- SPACE
- STR
- STUFF
- SUBSTRING
- UPPER
- STUFF string function
- Subqueries
- SUBSTRING string function
- SUM aggregate function
- Summary value
- SUSER_ID system function
- SUSER_NAME system function
- Syntax
- help
- sysalternates
- syscolumns
- syscomments
- sysconfigures
- syscurconfigs
- sysdatabases
- sysdepends
- sysdevices
- sysindexes
- syskeys
- syslocks
- syslogins
- syslogs
- sysmessages
- sysname datatype
- sysobjects
- sysprocedures
- sysprocesses system
- sysprotects
- syssegments
- System functions
- COL_LENGTH
- COL_NAME
- DB_ID
- DB_NAME
- HOST_ID
- HOST_NAME
- INDEX_COL
- ISNULL
- OBJECT_ID
- OBJECT_NAME
- SUSER_ID
- SUSER_NAME
- USER_ID
- USER_NAME
- System procedures
- enter with isql
- execute
- list
- sp_
- sp_addalias
- sp_addgroup
- sp_addlogin
- sp_addtype
- sp_addumpdevice
- sp_adduser
- sp_bindefault
- sp_bindrule
- sp_changedbowner
- sp_changegroup
- sp_commonkey
- sp_configure
- sp_dboption
- sp_defaultdb
- sp_depends
- sp_diskdefault
- sp_dropalias
- sp_dropdevice
- sp_dropgroup
- sp_dropkey
- sp_droplogin
- sp_droptype
- sp_dropuser
- sp_foreignkey
- sp_help
- sp_helpdb
- sp_helpdevice
- sp_helpgroup
- sp_helpindex
- sp_helpjoins
- sp_helpkey
- sp_helprotect
- sp_helpsql
- sp_helptext
- sp_helpuser
- sp_lock
- sp_logdevice
- sp_monitor
- sp_password
- sp_primarykey
- sp_rename
- sp_renamedb
- sp_spaceused
- sp_unbindefault
- sp_unbindrule
- sp_who
- System tables
- list
- relationship chart
- syscolumns
- syscomments
- sysconfigures
- syscurconfigs
- sysdatabases
- sysdepends
- sysdevices
- sysindexes
- syskeys
- syslaternates
- syslocks
- syslogins
- syslogs
- sysmessages
- sysobjects
- sysprocedures
- sysprocesses
- sysprotects
- syssegments
- systypes
- sysusages
- sysusers
- System, shutdown
- systypes
- sysusages
- sysusers
-
- T
- Table
- add columns
- browsing
- copy to and from operating system file
- create
- define common key
- define foreign key
- define primary key
- delete row from
- divide into groups
- remove rows
- remove
- rename
- truncate
- view
- TAN mathematical function
- text datatype
- Text functions
- PATINDEX
- SET TEXTSIZE
- TEXTPTR
- TEXTVALID
- Text
- read from database
- write into database
- TEXTPTR text/image function
- TEXTVALID text/image function
- timestamp datatype
- tinyint datatype
- TRANSACT-SQL
- Transaction log
- back up
- dump
- load
- place in separate database device
- size of database device required
- storage space
- Transaction
- begin
- end
- rollback
- save
- Trigger
- create
- help
- remove
- trunc. log on chkpt. database option
- TRUNCATE TABLE
-
- U
- UPDATE STATISTICS
- UPDATE
- UPPER string function
- USE
- User
- add login authorization
- add new
- change group
- current
- help
- impersonate another
- remove from database
- remove login authorization
- USER_ID system function
- USER_NAME system function
- user_type_name datatype
- Utility programs
- bcp
- bldmastr
- console
- defncopy
- isql
- sqlservr
-
- V
- Value
- null
- summary
- varbinary datatype
- varchar datatype
- Variables
- global. See Global variables
- local
- Vector aggregate function
- Views
- create
- define common key
- define foreign key
- define primary key
- remove
-
- W
- WAITFOR
- WHERE clause
- WHILE
- Wildcard characters
- WRITETEXT
-
-