home *** CD-ROM | disk | FTP | other *** search
/ Microsoft Programmer's Library 1.3 / Microsoft_Programmers_Library.7z / MPL / net / sqlltsql.txt < prev    next >
Encoding:
Text File  |  2013-11-08  |  656.1 KB  |  19,647 lines

  1.  Microsoft  SQL Server - Learning TRANSACT-SQL
  2.  
  3.  
  4.  
  5.  
  6.  
  7.  
  8.  
  9.  ────────────────────────────────────────────────────────────────────────────
  10.              Microsoft (R) SQL Server - Learning TRANSACT-SQL(tm)
  11.  
  12.               The SYBASE (R) SQL Server database for PC networks
  13.                                  VERSION 1.1
  14.  ────────────────────────────────────────────────────────────────────────────
  15.  
  16.  
  17.                      for the MS (R) OS/2 Operating System
  18.  
  19.  
  20.  
  21.  
  22.  
  23.  
  24.  
  25.  
  26.  Microsoft Corporation
  27.  
  28.  Information in this document is subject to change without notice and does
  29.  not represent a commitment on the part of Microsoft Corporation. The
  30.  software described in this document is furnished under a license agreement
  31.  or nondisclosure agreement. The software may be used or copied only in
  32.  accordance with the terms of the agreement. It is against the law to copy
  33.  the software on any medium except as specifically allowed in the license or
  34.  nondisclosure agreement. No part of this manual may be reproduced or
  35.  transmitted in any form or by any means, electronic or mechanical, including
  36.  photocopying and recording, for any purpose without the express written
  37.  permission of Microsoft Corporation.
  38.  (C) 1990 Microsoft Corporation and SYBASE, Inc. All rights reserved.
  39.  
  40.  
  41.  Printed in the USA.
  42.  
  43.  
  44.  Microsoft, MS-DOS, MS, and the Microsoft logo are registered
  45.  trademarks of Microsoft Corporation.
  46.  
  47.  IBM is a registered trademark of International Business
  48.  Machines Corporation.
  49.  
  50.  SYBASE is a registered trademark of SYBASE, Inc.
  51.  TRANSACT-SQL and DB-LIBRARY are trademarks of SYBASE, Inc.
  52.  
  53.  Document Number: SY10233-0290
  54.   OEM-D/0788-1Z
  55.  
  56.  
  57.  
  58.  
  59.  
  60.  
  61.  Table of Contents
  62.  ────────────────────────────────────────────────────────────────────────────
  63.  
  64.  
  65.  
  66.  Before You Begin
  67.       Notational Conventions
  68.       How to Use This Guide
  69.       Finding Further Information
  70.  
  71.  Chapter 1  Overview
  72.  
  73.       Introduction
  74.       SQL and Relational Database Management
  75.              Queries, Data Modification, and Other Statements
  76.              Tables, Columns, and Rows
  77.              Relational Operations
  78.       TRANSACT-SQL Enhancements
  79.              Control-of-Flow Language
  80.              Stored Procedures
  81.              Triggers
  82.              The COMPUTE Clause
  83.              Data Integrity Mechanisms
  84.              Other Extensions to SQL
  85.       About the Examples
  86.              Using the SQL Server Administration Facility
  87.              Format of Examples
  88.              Default Databases
  89.              Using the Sample Database
  90.              What's in the Sample Database
  91.       Identifiers
  92.  
  93.  Chapter 2  Querying Databases
  94.  
  95.       Introduction
  96.       Choosing a Database: USE
  97.       SELECT Syntax
  98.       Choosing Columns: the Select List
  99.              Choosing All Columns: SELECT *
  100.              Choosing Specified Columns
  101.              Rearranging the Order of Columns
  102.              Renaming Columns in Query Results
  103.              Character Strings in Query Results
  104.              Computed Values in the Select List
  105.              Selecting text and image Values
  106.              Select List Summary
  107.       Eliminating Duplicates: DISTINCT
  108.       Specifying Tables: the FROM Clause
  109.       Selecting Rows: the WHERE Clause
  110.              Comparison Operators
  111.              Ranges (BETWEEN and NOT BETWEEN)
  112.              Lists (IN and NOT IN)
  113.              Wildcards and the LIKE Clause
  114.              Character Strings and Quotes
  115.              Unknown Values: IS NULL and IS NOT NULL
  116.              Connecting Conditions with Logical Operators
  117.       Creating a New Table for Results: SELECT INTO
  118.       Grouping Data: GROUP BY and HAVING Clauses
  119.       Sorting Query Results: ORDER BY
  120.       Generating Summary Rows: COMPUTE BY
  121.  
  122.  Chapter 3  Joining Two or More Tables
  123.  
  124.       Introduction
  125.       The Join Operation
  126.              The Select List
  127.              The FROM Clause
  128.              The WHERE Clause
  129.              Joins and the Relational Model
  130.              How Joins Are Processed
  131.              Equijoins and Natural Joins
  132.              Joins with Additional Conditions
  133.              Joins Not Based on Equality
  134.              Self-Joins and Aliases
  135.              The Not-Equal Join
  136.              Joining More Than Two Tables
  137.              Outer Joins
  138.              Joins and Null Values
  139.       Help on Joins
  140.  
  141.  Chapter 4  Displaying Totals: GROUP BY and COMPUTE
  142.  
  143.       Introduction
  144.       Aggregate Functions and the GROUP BY Clause
  145.              Aggregate Functions and Datatypes
  146.              COUNT(*)
  147.              The DISTINCT Keyword
  148.              Null Values and Aggregate Functions
  149.              The GROUP BY Clause
  150.              GROUP BY Syntax
  151.              GROUP BY without Aggregate Functions
  152.              GROUP BY and Null Values
  153.              GROUP BY and the WHERE Clause
  154.              GROUP BY and ALL
  155.              GROUP BY and ORDER BY
  156.              The HAVING Clause
  157.       The COMPUTE Clause
  158.              COMPUTE Syntax
  159.              Row Aggregate Functions
  160.              More Than One Column after COMPUTE BY
  161.              Using More Than One COMPUTE Clause
  162.              Applying an Aggregate to More Than One Column
  163.              Using Different Aggregate Functions in the Same COMPUTE BY
  164.                Clause
  165.              Grand Values: COMPUTE without BY
  166.  
  167.  Chapter 5  Using Built-In Functions
  168.  
  169.       Introduction
  170.       System Functions
  171.              System Function Examples
  172.       String Functions
  173.              SUBSTRING
  174.              CHARINDEX
  175.              STR
  176.              STUFF
  177.              Testing Similarity of Patterns: SOUNDEX and DIFFERENCE
  178.              Concatenation
  179.              Nested String Functions
  180.       Text and Image Functions
  181.              TEXTPTR
  182.       Mathematical Functions
  183.              Examples of Mathematical Functions
  184.       Date Functions
  185.              GETDATE
  186.              DATEPART and DATENAME
  187.              DATEDIFF
  188.              DATEADD
  189.       Conversion Function
  190.              The Style Parameter
  191.  
  192.  Chapter 6  Building Subqueries
  193.  
  194.       Introduction
  195.       Subquery Syntax
  196.       Subquery Rules
  197.       An Example
  198.       Subqueries Introduced with IN
  199.       Subqueries Introduced with NOT IN
  200.              Qualifying Column Names
  201.       Multiple Levels of Nesting
  202.       Subqueries in UPDATE, DELETE, and INSERT
  203.       Subqueries with Aliases
  204.       Comparison Operator Subqueries
  205.              Comparison Operators Modified with ANY or ALL
  206.       Correlated Subqueries
  207.              Correlated Subqueries with Aliases
  208.              Correlated Subqueries with Comparison Operators
  209.              Correlated Subqueries in a HAVING Clause
  210.       Subqueries Introduced with EXISTS
  211.       Subqueries Introduced with NOT EXISTS
  212.              Using EXISTS and NOT EXISTS to Find Intersection and Difference
  213.       Subqueries Used in Place of an Expression
  214.  
  215.  Chapter 7  Creating Databases, Tables, and Indexes
  216.  
  217.       Introduction
  218.       Help on Database Objects
  219.       Permissions
  220.       Databases
  221.              Choosing a Database: USE
  222.              Creating a User Database: CREATE DATABASE
  223.              Removing a Database: DROP DATABASE
  224.              Changing the Size of a Database: ALTER DATABASE
  225.              Help on Databases
  226.       Tables
  227.              CREATE TABLE Basics
  228.              Table Names
  229.              CREATE TABLE Syntax
  230.              System-Supplied Datatypes
  231.              User-Defined Datatypes
  232.              Null Values
  233.              Temporary Tables
  234.              Creating a Table in a Different Database
  235.              Removing a Table
  236.              Space Used
  237.              Table Creation Process
  238.       Changing an Existing Table
  239.              Adding Columns: ALTER TABLE
  240.              Renaming Tables and Other Objects
  241.       Indexes
  242.              How, What, and Why to Index
  243.              Indexing More Than One Column: Composite Indexes
  244.              The UNIQUE Keyword
  245.              Clustered and Nonclustered Indexes
  246.              The FILLFACTOR Option
  247.              The IGNORE_DUP_KEY Option
  248.              The IGNORE_DUP_ROW and ALLOW_DUP_ROW Options
  249.              Help on Indexes
  250.              Removing an Index: DROP INDEX
  251.  
  252.  Chapter 8  Creating Defaults and Rules
  253.  
  254.       Introduction
  255.       Defaults
  256.              Creating Defaults
  257.              Binding Defaults
  258.              Unbinding Defaults
  259.              Dropping Defaults
  260.              Defaults and Null Values
  261.       Rules
  262.              Creating Rules
  263.              Binding Rules
  264.              Unbinding Rules
  265.              Dropping Rules
  266.  
  267.  Chapter 9  Adding, Changing, and Removing Data
  268.  
  269.       Introduction
  270.       Permissions
  271.       Referential Integrity
  272.       Transactions
  273.       Using the Sample Database
  274.       Datatype Entry Rules
  275.              Char, Varchar, and Text
  276.              Datetime
  277.              Binary, Varbinary, and Image
  278.              Money
  279.              Float
  280.              Int, Smallint, and Tinyint
  281.       Adding New Rows: INSERT
  282.              Adding New Rows with VALUES
  283.              Adding New Rows with SELECT
  284.       Changing Existing Data: UPDATE
  285.              The UPDATE Clause
  286.              The SET Clause
  287.              The WHERE Clause
  288.              The FROM Clause
  289.       Adding or Changing Data with WRITETEXT
  290.       Removing Data: DELETE
  291.              The DELETE Clause
  292.              The WHERE Clause
  293.              The FROM Clause
  294.       Deleting All Rows: TRUNCATE TABLE
  295.  
  296.  Chapter 10  Creating Views
  297.  
  298.       Introduction
  299.       Advantages of Views
  300.              Focus
  301.              Simpler Data Manipulation
  302.              Customizing
  303.              Security
  304.              Logical Data Independence
  305.              View Examples
  306.       Help on Views
  307.       Creating and Dropping Views
  308.              The CREATE VIEW Clause
  309.              The SELECT Statement
  310.              Dropping Views
  311.       Retrieving Data through Views
  312.              View Resolution
  313.              Redefining Views
  314.              Renaming Views
  315.              Altering or Dropping Underlying Objects
  316.       Restrictions for Modifying Data through Views
  317.              Computed Columns in View Definition
  318.              GROUP BY or COMPUTE BY in View Definition
  319.              Null Values in Underlying Objects
  320.              Changing More Than One Underlying Object
  321.  
  322.  Chapter 11  Using Control-of-Flow Language
  323.  
  324.       Introduction
  325.       Batches
  326.       Batches and Batch Rules
  327.              Batch Examples
  328.              Batches Submitted as Files
  329.       Control-of-Flow Language
  330.              IF...ELSE
  331.              BEGIN...END
  332.              WHILE and BREAK...CONTINUE
  333.              DECLARE and Local Variables
  334.              DECLARE and Global Variables
  335.              GOTO
  336.              RETURN
  337.              WAITFOR
  338.              PRINT and RAISERROR
  339.              Comments
  340.  
  341.  Chapter 12  Using Stored and System Procedures
  342.  
  343.       Introduction
  344.       Creating and Executing Stored Procedures
  345.              Parameters
  346.              Default Parameters
  347.              Using More Than One Parameter
  348.              Procedure Groups
  349.              WITH RECOMPILE in CREATE PROCEDURE
  350.              WITH RECOMPILE in EXECUTE
  351.              Stored Procedure Rules
  352.              Qualifying Names Inside Stored Procedures
  353.              Dropping Procedures
  354.              Renaming Procedures
  355.              Help on Procedures
  356.              Stored Procedures and Permissions
  357.       System Procedures
  358.              User Identification and Permissions
  359.              Data Definition and Database Objects
  360.              Other System Procedures
  361.  
  362.  Chapter 13  Creating Triggers
  363.  
  364.       Introduction
  365.       Defining a Trigger: CREATE TRIGGER
  366.       Removing a Trigger: DROP TRIGGER
  367.       Trigger Rules and Considerations
  368.              Triggers and Permissions
  369.       Trigger Storage
  370.       Renaming Triggers
  371.       Help on Triggers
  372.              sp_help
  373.              sp_helptext
  374.              sp_depends
  375.       Trigger Examples
  376.              Deleting a Primary Key
  377.              Inserting a Primary Key
  378.              Updating a Primary Key
  379.              Deleting a Foreign Key
  380.              Inserting a Foreign Key
  381.              Inserting a NULL Foreign Key
  382.              Updating a Foreign Key
  383.              Summary Value Triggers
  384.              Other Triggers
  385.              Correlated Subqueries in Triggers
  386.  
  387.  Chapter 14  Advanced Topics for Database Owners
  388.  
  389.       Introduction
  390.       Assigning Permissions: GRANT and REVOKE
  391.              Object Permissions and Statement Permissions
  392.              The Permission Hierarchy
  393.              Permission Summary
  394.              GRANT and REVOKE Syntax
  395.              Views as Security Mechanisms
  396.              Stored Procedures as Security Mechanisms
  397.       Tuning Queries and Stored Procedures: SET
  398.       UPDATE STATISTICS
  399.       Locking and the HOLDLOCK Keyword
  400.              The HOLDLOCK Keyword
  401.              Deadlocks and Livelocks
  402.       Data Integrity and Transaction Processing
  403.              Transactions and Consistency
  404.              Transactions and Recovery
  405.              User-Defined Transactions
  406.              Backup and Recovery
  407.       Database Consistency Checker
  408.  
  409.  Appendix A  The pubs Sample Database
  410.  
  411.              Rules
  412.              Trigger
  413.              Stored Procedure
  414.              View
  415.              Defaults
  416.  
  417.  Glossary
  418.  
  419.  
  420.  Index
  421.  
  422.  
  423.  
  424.  
  425.  Before You Begin
  426.  ────────────────────────────────────────────────────────────────────────────
  427.  
  428.  This manual teaches you to use TRANSACT-SQL(tm), an enhanced version of the
  429.  SQL relational database language. It describes TRANSACT-SQL statements as
  430.  well as other features of TRANSACT-SQL.
  431.  
  432.  Before using this manual, you should have read SQL Server System
  433.  Administrator's Guide for information on using the SQL Server Administration
  434.  Facility (SAF). You should also be familiar with TRANSACT-SQL or another
  435.  version of SQL.
  436.  
  437.  
  438.  Notational Conventions
  439.  
  440.  Throughout this manual, the following conventions are used to distinguish
  441.  elements of text:
  442.  
  443. ╓┌─────────────────────────────────┌─────────────────────────────────────────
  444.  Convention                        Purpose
  445.  ────────────────────────────────────────────────────────────────────────────
  446.  UPPERCASE                         Represents statement and clause names,
  447.                                    functions, macros, and any other portions
  448.                                    of syntax that must appear exactly as
  449.                                    shown.
  450.  
  451.  MIXEDcase                         Shows abbreviations for keywords in
  452.                                    syntax. The uppercase letters show the
  453.                                    required portion of the keyword; the
  454.                                    lowercase letters show the optional
  455.                                    portion.
  456.  
  457.  SMALL CAPS                        Represent key names such as CTRL.
  458.  
  459.  bold                              Represents stored procedures, system
  460.                                    procedures, triggers, defaults, rules,
  461.                                    utility programs, and commands.
  462.  
  463.  italic                            Represents database names, table names,
  464.  Convention                        Purpose
  465.  ────────────────────────────────────────────────────────────────────────────
  466. italic                            Represents database names, table names,
  467.                                    view names, column names, datatypes, index
  468.                                    names, pathnames, filenames, variables
  469.                                    that appear in text, and the first
  470.                                    occurrence of a glossary term.
  471.  
  472.  monospace                         Represents examples, screen output,
  473.                                    program code, and error messages.
  474.  
  475.  [brackets]                        Enclose optional items. Type only the
  476.                                    information within the brackets, not the
  477.                                    brackets themselves.
  478.  
  479.  {braces}                          Enclose required items. Type only the
  480.                                    information within the braces, not the
  481.                                    braces themselves.
  482.  
  483.  | (vertical bar)                  Separates items inside a set of braces or
  484.                                    brackets. The vertical bar means you must
  485.  Convention                        Purpose
  486.  ────────────────────────────────────────────────────────────────────────────
  487.                                   brackets. The vertical bar means you must
  488.                                    choose one and only one item.
  489.  
  490.  ... (ellipsis)                    Means that you can repeat the previous
  491.                                    item as many times as you like.
  492.  
  493.  <execute>                         Executes one or more SQL statements. (In
  494.                                    the SQL Server Administration facility,
  495.                                    SQL statements are executed by pressing
  496.                                    the CONTROL+E keys. In the isql program,
  497.                                    SQL statements are executed with the go
  498.                                    command.)
  499.  
  500.  ────────────────────────────────────────────────────────────────────────────
  501.  
  502.  
  503.  
  504.  
  505.  How to Use This Guide
  506.  
  507.  The following topics are covered in this guide:
  508.  
  509.  ────────────────────────────────────────────────────────────────────────────
  510.  Chapter 1
  511.    TRANSACT-SQL, relational databases, and the sample database, pubs
  512.  
  513.  Chapter 2
  514.    Retrieving columns and rows from a single table
  515.  
  516.  Chapter 3
  517.    Retrieving data from two or more tables (the join operation)
  518.  
  519.  Chapter 4
  520.    Displaying totals
  521.  
  522.  Chapter 5
  523.    Using built-in functions
  524.  
  525.  Chapter 6
  526.    Using subqueries
  527.  
  528.  Chapter 7
  529.    Creating databases, tables, and indexes
  530.  
  531.  Chapter 8
  532.    Setting up defaults and rules
  533.  
  534.  Chapter 9
  535.    Adding, changing, and removing data
  536.  
  537.  Chapter 10
  538.    Creating and using views
  539.  
  540.  Chapter 11
  541.    Creating batch files and using control-of-flow language
  542.  
  543.  Chapter 12
  544.    Creating stored procedures and using system procedures
  545.  
  546.  Chapter 13
  547.    Creating triggers
  548.  
  549.  Chapter 14
  550.    Managing a database (an introduction)
  551.  
  552.  Appendix
  553.    The pubs sample database
  554.  
  555.  ────────────────────────────────────────────────────────────────────────────
  556.  Finding Further Information
  557.  
  558.  The following manuals describe SQL Server and are included as part of the
  559.  standard documentation set:
  560.  
  561.  ────────────────────────────────────────────────────────────────────────────
  562.  SQL Server Installation Guide
  563.    A guide to installing and setting up SQL Server
  564.  
  565.  SQL Server System Administrator's Guide
  566.    A guide for SQL Server System Administrators, including instructions
  567.    explaining how to use the SQL Server Administration Facility (SAF) for
  568.    database queries
  569.  
  570.  SQL Server Language Reference
  571.    A reference to the syntax of all TRANSACT-SQL statements, commands,
  572.    procedures, and utilities
  573.  
  574.  SQL Server Programmer's Reference
  575.    A reference to DB-LIBRARY(tm), which is a set of C routines and macros
  576.    that allow your application to interact with SQL Server
  577.  
  578.  SQL Server Quick Reference
  579.    A quick reference guide for TRANSACT-SQL
  580.  
  581.  ────────────────────────────────────────────────────────────────────────────
  582.  
  583.  
  584.  
  585.  
  586.  Chapter 1  Overview
  587.  ────────────────────────────────────────────────────────────────────────────
  588.  
  589.  
  590.  Introduction
  591.  
  592.  This guide documents TRANSACT-SQL, an enhanced version of the Structured
  593.  Query Language (SQL) relational database language. It will benefit both SQL
  594.  beginners and those who have experience with other implementations of SQL.
  595.  
  596.  Users of the SQL Server database management system who are unfamiliar with
  597.  SQL can treat this guide as a textbook and start at the beginning. On first
  598.  reading, novice SQL users may want to skip Chapter 6, "Building Subqueries."
  599.  Chapter 11, "Using Control-of-Flow Language," and Chapter 14, "Advanced
  600.  Topics for Database Owners," also cover topics that are more advanced than
  601.  beginning SQL.
  602.  
  603.  Readers acquainted with other versions of SQL will find this guide useful
  604.  for information on TRANSACT-SQL enhancements. Even SQL experts should study
  605.  the capabilities and features that SQL Server has added to standard SQL,
  606.  especially the material on stored procedures (which allow you to include
  607.  control-of-flow language and SQL statements in named, precompiled procedures
  608.  that can be executed at any time). These and other extensions are summarized
  609.  later in this chapter, with references to the sections of the guide that
  610.  discuss them in more detail.
  611.  
  612.  A concise and complete reference to TRANSACT-SQL can be found in the SQL
  613.  Server Language Reference, which lists SQL statements, system procedures,
  614.  and utility programs alphabetically. The SQL Server Language Reference also
  615.  discusses some details and advanced concepts not included in this guide. The
  616.  numerous examples in this guide are based on the pubs sample database. For
  617.  best use of this guide, new users should work through the examples. Ask your
  618.  System Administrator how to get a clean copy of the sample database.
  619.  
  620.  You can use TRANSACT-SQL with the SQL Server Administration Facility (SAF).
  621.  The SAF provides an editor that makes it easy to type SQL queries and see
  622.  the results. The SAF is described in the SQL Server System Administrator's
  623.  Guide.
  624.  
  625.  
  626.  SQL and Relational Database Management
  627.  
  628.  SQL is a high-level language for relational database systems. Originally
  629.  developed by IBM(R) in the late 1970s, SQL has been adopted and adapted for
  630.  many relational database management systems. It has been approved as the
  631.  official relational query language standard by the American National
  632.  Standards Institute (ANSI). TRANSACT-SQL is compatible with IBM SQL and most
  633.  other commercial implementations of SQL, but provides important additional
  634.  capabilities and functions.
  635.  
  636.  Although the "Q" in SQL stands for "Query," SQL includes commands not only
  637.  for querying (retrieving data from) a database, but also for creating new
  638.  databases and database objects, adding new data, modifying existing data,
  639.  and a few other functions.
  640.  
  641.  
  642.  Queries, Data Modification, and Other Statements
  643.  
  644.  In this guide, query means a request to retrieve data, using the SELECT
  645.  statement. Data modification refers to an addition, deletion, or change to
  646.  data, using the INSERT, DELETE, or UPDATE statement, respectively. Other SQL
  647.  commands are instructions to perform administrative operations.
  648.  
  649.  Each SQL statement begins with a keyword, such as INSERT, that names the
  650.  basic operation performed. Many SQL statements also have one or more clauses
  651.  that tailor the statement to meet a particular need.
  652.  
  653.  When a query is run, TRANSACT-SQL displays the results for the user. If no
  654.  data meets the criteria specified in the query, the user gets a message to
  655.  that effect. Data modification statements and administrative statements do
  656.  not display results, since they do not retrieve data. TRANSACT-SQL provides
  657.  a message to let the user know whether the statement has been performed.
  658.  
  659.  
  660.  Tables, Columns, and Rows
  661.  
  662.  SQL is a database language specifically designed for the relational model of
  663.  database management. In a relational database management system, users see
  664.  data as tables or relations.
  665.  
  666.  Each row, or record, of a table describes one occurrence of an entity─a
  667.  person, a company, a sale, or some other thing. Each column, or field,
  668.  describes one characteristic of the entity─a person's name or address, a
  669.  company's name or president, items sold, a quantity, or a date.
  670.  
  671. ╓┌───────┌──────────────────────────────────────────────────┌───────────┌────
  672.  Pub_id  Pub_name                                           City        State
  673.  ────────────────────────────────────────────────────────────────────────────
  674.  Pub_id  Pub_name                                           City        State
  675.  ────────────────────────────────────────────────────────────────────────────
  676.  1389    Algodata Infosystems                               Berkeley    CA
  677.  
  678.  0736    New Age Books                                      Boston      MA
  679.  
  680.  0877    Binnet & Hardley                                   Washington  DC
  681.  
  682.  ────────────────────────────────────────────────────────────────────────────
  683.  
  684.  
  685.  
  686.  Figure 1.1 A Table in a Relational Database - A database is made up of a set
  687.  of related tables.
  688.  
  689.  
  690.  Relational Operations
  691.  
  692.  The basic query operations in a relational system are selection (or
  693.  restriction), projection, and join. All of them can be combined in the SQL
  694.  SELECT statement.
  695.  
  696.  A selection is a subset of the rows in a table, based on some conditions
  697.  specified by the user. For example, you might want to look at the rows for
  698.  all the authors who live in Paris.
  699.  
  700.  A projection is a subset of the columns in a table. For example, a query can
  701.  display only the name and city of all the authors, omitting the street
  702.  address, the phone number, and other information.
  703.  
  704.  A join links the rows in two or more tables by comparing the values in
  705.  specified fields. For example, say you have one table containing information
  706.  about authors, including the columns au_id (author identification number)
  707.  and au_lname (author's last name), and another table containing title
  708.  information about books, including a column (au_id) that gives the ID number
  709.  of the book's author. You might join the authors table and the titles table,
  710.  testing for equality of the values in the au_id columns of each table.
  711.  Whenever there is a match, a new row─containing columns from both tables─is
  712.  created and displayed as part of the result of the join. Joins are often
  713.  combined with projections and selections so that only selected columns of
  714.  selected matching rows are displayed.
  715.  
  716.  
  717.  TRANSACT-SQL Enhancements
  718.  
  719.  TRANSACT-SQL is designed to enhance the power of SQL and to minimize─if not
  720.  eliminate─the occasions on which users must resort to a programming language
  721.  to accomplish a desired task. TRANSACT-SQL goes beyond the ANSI standard and
  722.  the many commercial versions of SQL.
  723.  
  724.  SQL Server enhancements are summarized in the following sections. They are
  725.  also noted throughout this guide as they are discussed.
  726.  
  727.  
  728.  Control-of-Flow Language
  729.  
  730.  TRANSACT-SQL provides control-of-flow language that can be used as part of
  731.  any SQL statement. The following constructs are available:
  732.  
  733.  
  734.    ■   BEGIN...END
  735.  
  736.    ■   BREAK
  737.  
  738.    ■   CONTINUE
  739.  
  740.    ■   DECLARE
  741.  
  742.    ■   GOTO label
  743.  
  744.    ■   IF...ELSE
  745.  
  746.    ■   PRINT
  747.  
  748.    ■   RAISERROR
  749.  
  750.    ■   RETURN
  751.  
  752.    ■   WAITFOR
  753.  
  754.    ■   WHILE
  755.  
  756.  
  757.  Local variables can be defined with DECLARE and assigned values. Several
  758.  predefined global variables are included with SQL Server.
  759.  
  760.  
  761.  Stored Procedures
  762.  
  763.  One of the most important SQL Server extensions to standard SQL is the
  764.  ability to create stored procedures. Stored procedures can combine almost
  765.  any SQL statements with control-of-flow language and can take one or more
  766.  parameters.
  767.  
  768.  The ability to write your own stored procedures greatly enhances the power,
  769.  efficiency, and flexibility of the SQL database language. Since stored
  770.  procedures are compiled the first time they are executed, they subsequently
  771.  run much faster than the stand-alone statements. The creator of a stored
  772.  procedure can use local variables and define parameters to be supplied when
  773.  the stored procedure is executed.
  774.  
  775.  SQL-Server-supplied stored procedures, called system procedures, are
  776.  provided for your use in SQL Server system administration. Chapter 12,
  777.  "Using Stored and System Procedures," discusses system procedures and
  778.  explains how to create stored procedures. System procedures are discussed in
  779.  detail in the SQL Server Language Reference.
  780.  
  781.  
  782.  Triggers
  783.  
  784.  A trigger is a special kind of stored procedure used to protect referential
  785.  integrity, which enforces rules about the relationships among data in
  786.  different tables. Triggers go into effect when a user attempts to modify
  787.  data with an INSERT, DELETE, or UPDATE statement.
  788.  
  789.  A trigger can instruct the system to take any number of actions when a
  790.  specified change is attempted. By preventing incorrect, unauthorized, or
  791.  inconsistent changes to data, triggers help maintain the integrity of a
  792.  database. Triggers can also call stored procedures.
  793.  
  794.  
  795.  The COMPUTE Clause
  796.  
  797.  Another important SQL Server extension is the COMPUTE clause, which is used
  798.  with the row aggregate functions (SUM, MAX, MIN, AVG, and COUNT) to
  799.  calculate summary values. The results of a query that includes a COMPUTE
  800.  clause are displayed with both detail and summary rows, and look like a
  801.  report that most database management systems can produce only with a report
  802.  generator. COMPUTE displays summary values as additional rows in the results
  803.  instead of as new columns. The COMPUTE clause is described in Chapter 4,
  804.  "Displaying Totals: GROUP BY and COMPUTE."
  805.  
  806.  
  807.  Data Integrity Mechanisms
  808.  
  809.  TRANSACT-SQL provides a command language for several special data integrity
  810.  mechanisms. In addition to triggers, briefly explained earlier, defaults and
  811.  rules define integrity constraints that come up during the entry and
  812.  modification of data.
  813.  
  814.  A default is a value linked to a particular column or datatype, and inserted
  815.  by the system if no value is provided during data entry. Rules are
  816.  user-defined integrity constraints linked to a particular column or
  817.  datatype, and enforced at data entry time. (Chapter 8, "Creating Defaults
  818.  and Rules," discusses defaults and rules.)
  819.  
  820.  
  821.  Other Extensions to SQL
  822.  
  823.  Other unique or unusual features of TRANSACT-SQL include
  824.  
  825.  
  826.    ■   Updates and selections through views. Unlike most other versions of
  827.        SQL, TRANSACT-SQL places no restrictions on retrieving data through
  828.        views and very few restrictions on updating data through views. (See
  829.        Chapter 10, "Creating Views.")
  830.  
  831.    ■   Fewer restrictions on the ORDER BY clause and the GROUP BY clause.
  832.        (See Chapter 2, "Querying Databases," and Chapter 4, "Displaying
  833.        Totals: GROUP BY and COMPUTE.")
  834.  
  835.    ■   User-defined datatypes built on SQL-Server-supplied datatypes. (See
  836.        Chapter 7, "Creating Databases, Tables, and Indexes," and Chapter 8,
  837.        "Creating Defaults and Rules.")
  838.  
  839.    ■   Subqueries wherever an expression is allowed. (See Chapter 6,
  840.        "Building Subqueries.")
  841.  
  842.    ■   Temporary tables, which exist only for the duration of the current
  843.        work session and disappear thereafter. (See Chapter 7, "Creating
  844.        Databases, Tables, and Indexes.")
  845.  
  846.    ■   Options to the CREATE INDEX statement for fine-tuning aspects of
  847.        performance determined by indexes and controlling the treatment of
  848.        duplicate keys and rows. (See Chapter 2, "Querying Databases.")
  849.  
  850.    ■   Query processing options for checking SQL Server's query execution
  851.        plan, estimating the complexity of a query, and others. (See Chapter
  852.        14, "Advanced Topics for Database Owners.")
  853.  
  854.    ■   User control over what happens when you attempt to enter duplicate
  855.        keys in a unique index or duplicate rows in a table. (See Chapter 7,
  856.        "Creating Databases, Tables, and Indexes.")
  857.  
  858.    ■   The ability to insert data from a table into that same table. (See
  859.        Chapter 9, "Adding, Changing, and Removing Data.")
  860.  
  861.    ■   The ability to extract data from one table and put it into another
  862.        with the UPDATE statement. (See Chapter 9, "Adding, Changing, and
  863.        Removing Data.")
  864.  
  865.    ■   The ability to remove data based on data in other tables, using a join
  866.        in a DELETE statement. (See Chapter 9, "Adding, Changing, and Removing
  867.        Data.")
  868.  
  869.    ■   A fast way to delete all rows in a specified table and reclaim the
  870.        space they took up with the TRUNCATE TABLE statement. (See Chapter 9,
  871.        "Adding, Changing, and Removing Data.")
  872.  
  873.    ■   Bitwise operators for use with integer and bit type columns. (See the
  874.        SQL Server Language Reference.)
  875.  
  876.    ■   Support for text and image datatypes. (See the SQL Server Language
  877.        Reference.)
  878.  
  879.    ■   Dozens of built-in functions for operations on character and numeric
  880.        data. (See Chapter 5, "Using Built-In Functions.")
  881.  
  882.    ■   Support for browse mode in a DB-LIBRARY application and for updates
  883.        while browsing. (See the SQL Server Programmer's Reference.)
  884.  
  885.  
  886.  
  887.  About the Examples
  888.  
  889.  This section discusses the examples in this guide and the pubs sample
  890.  database.
  891.  
  892.  
  893.  Using the SQL Server Administration Facility
  894.  
  895.  The SQL Server Administration Facility (SAF) contains menus that make it
  896.  easy to interactively develop queries and view the results. You'll be using
  897.  the SAF to do the examples throughout this guide. For directions on using
  898.  the SAF, see the SQL Server System Administrator's Guide.
  899.  
  900.  Before you can start the SAF, you'll need the following (if necessary, see
  901.  your System Administrator):
  902.  
  903.  
  904.    ■   The name of the server to which you will log in
  905.  
  906.    ■   Your login ID
  907.  
  908.    ■   Your password
  909.  
  910.    ■   A clean copy of the pubs sample database
  911.  
  912.  
  913.  After typing SQL statements on the SAF screen, execute the statements from
  914.  the menu or press CONTROL+E. The examples throughout this guide include SQL
  915.  statements only; they do not include directions for executing statements.
  916.  
  917.  
  918.  Format of Examples
  919.  
  920.  An SQL statement must follow precise syntactical and structural rules.
  921.  However, SQL is a free-form language; there are no rules about how many
  922.  words you can put on a line or where you need to break a line. For
  923.  readability and consistency, the examples in this guide are formatted so
  924.  that each clause of a statement begins on a new line.
  925.  
  926.  
  927.  Default Databases
  928.  
  929.  Your System Administrator may have assigned you a default database, a
  930.  database that you are connected to when you log in. For example, your
  931.  default database could be the sample database, pubs. If the System
  932.  Administrator has not assigned you a default database, you are connected to
  933.  the master database.
  934.  
  935.  You can change your default database to any database that you have
  936.  permission to use or to any database that has a guest account. Any user with
  937.  an SQL Server login ID (that is, listed in master..syslogins) can be a
  938.  guest. To change your default database, use the sp_defaultdb system
  939.  procedure. For information on this system procedure, see the SQL Server
  940.  Language Reference.
  941.  
  942.  In any case, you can make sure you're in pubs by using this statement:
  943.  
  944.    use pubs
  945.  
  946.  
  947.  Using the Sample Database
  948.  
  949.  The sample database, pubs, is used for just about every example in this
  950.  guide. You can try any of the examples on your own screen.
  951.  
  952.  You will notice that the query results you see on your screen will sometimes
  953.  differ from the way they look in this guide. That's because some of the
  954.  examples here have been reformatted (for example, the columns realigned) for
  955.  visual clarity or to take up less space on the page.
  956.  
  957.  You may need to get additional permissions from your System Administrator to
  958.  change the sample database using CREATE or data modification statements,
  959.  which are discussed in Chapter 7, "Creating Databases, Tables, and Indexes,"
  960.  Chapter 8, "Creating Defaults and Rules," and Chapter 9, "Adding, Changing,
  961.  and Removing Data." If you do change the sample database, it should be
  962.  returned to its original state for future users and uses. Ask your System
  963.  Administrator how to do this.
  964.  
  965.  
  966.  What's in the Sample Database
  967.  
  968.  The sample database, pubs, consists of eight tables: publishers, authors,
  969.  titles, titleauthor, roysched, sales, stores, and discounts. The following
  970.  list describes these tables:
  971.  
  972. ╓┌─────────────────────────────────┌─────────────────────────────────────────
  973.  Table                             Description
  974.  ────────────────────────────────────────────────────────────────────────────
  975.  publishers                        Contains the identification numbers,
  976.                                    names, cities, and states of three
  977.                                    publishing companies.
  978.  
  979.  authors                           Contains an identification number, first
  980.                                    and last name, address, and contract
  981.                                    status for each author.
  982.  
  983.  titles                            Contains the identification number, name,
  984.                                    type, identification number of the
  985.                                    publisher, price, advance, royalty,
  986.                                    year-to-date sales, comments, and
  987.                                    publication date for each book that has
  988.                                    been or is about to be published.
  989.  Table                             Description
  990.  ────────────────────────────────────────────────────────────────────────────
  991.                                   been or is about to be published.
  992.  
  993.  titleauthor                       Links the titles and authors tables
  994.                                    together. For each book, it contains the
  995.                                    title ID, the author ID, the author order,
  996.                                    and the royalty split among the authors of
  997.                                    a book.
  998.  
  999.  roysched                          Lists the unit sales ranges and the
  1000.                                    royalty connected with each range. The
  1001.                                    royalty is some percentage of the net
  1002.                                    receipts from sales.
  1003.  
  1004.  sales                             Records bookstore sales of titles in the
  1005.                                    titles table.
  1006.  
  1007.  stores                            Lists bookstores by store ID.
  1008.  
  1009.  discounts                         Lists three types of discounts for
  1010.  Table                             Description
  1011.  ────────────────────────────────────────────────────────────────────────────
  1012. discounts                         Lists three types of discounts for
  1013.                                    bookstores.
  1014.  
  1015.  ────────────────────────────────────────────────────────────────────────────
  1016.  
  1017.  
  1018.  
  1019.  The pubs sample database is illustrated in the Appendix of this guide.
  1020.  
  1021.  
  1022.  Identifiers
  1023.  
  1024.  An identifier is the name of a database object. Identifiers may be between 1
  1025.  and 30 characters. The first character of an identifier can be an alphabetic
  1026.  letter (a-z or A-Z) or the symbols # (pound sign) or _ (underscore). A table
  1027.  name beginning with # denotes a temporary table.
  1028.  
  1029.  After the first character, identifiers can include letters, digits, or the
  1030.  $, #, or _ symbol.
  1031.  
  1032.  ────────────────────────────────────────────────────────────────────────────
  1033.  NOTE
  1034.  When an identifier is preceded by the @ symbol, the identifier contains from
  1035.  1 to 29 characters. (For example, variable names and stored procedure
  1036.  parameter names are preceded by @.)
  1037.  ────────────────────────────────────────────────────────────────────────────
  1038.  
  1039.  By default, SQL Server is not sensitive to the case (upper or lower) of
  1040.  identifiers and data. If required, a System Administrator can build a
  1041.  case-sensitive SQL Server with the bldmastr program. The case of options for
  1042.  utility programs is significant.
  1043.  
  1044.  No embedded spaces are allowed in identifiers, and none of the SQL reserved
  1045.  words can be used.
  1046.  
  1047.  The names of database objects need not be unique in a database. However,
  1048.  column names and index names must be unique within a table, and other object
  1049.  names must be unique for each owner within a database. Database names must
  1050.  be unique on SQL Server.
  1051.  
  1052.  If you try to create a column using a name that is not unique in the table
  1053.  or if you try to create another database object (a table, a view, a stored
  1054.  procedure, and so on) with a name that you've already used in the same
  1055.  database, SQL Server responds with an error message.
  1056.  
  1057.  You can uniquely identify a table or column by adding other names that
  1058.  qualify it─the database name, the owner's name, and the table name or view
  1059.  name for a column. Each of these qualifiers is separated from the next by a
  1060.  period:
  1061.  
  1062.    database.owner.table_name.column_name
  1063.     database.owner.view_name.column_name
  1064.  
  1065.  For example, if the user sharon owns the authors table in the pubs database,
  1066.  the unique identifier of the city column in that table is
  1067.  
  1068.    pubs.sharon.authors.city
  1069.  
  1070.  The same naming syntax applies to other database objects. You can refer to
  1071.  any object in a similar fashion:
  1072.  
  1073.    pubs.dbo.titleview
  1074.     dbo.ziprule
  1075.  
  1076.  However, the full naming syntax is not always allowed in CREATE statements
  1077.  because you cannot create a view, procedure, rule, default, or trigger in a
  1078.  database other than the one you are currently in.
  1079.  
  1080.  The naming conventions are indicated in the syntax as
  1081.  
  1082.    [[database.]owner.]object_name
  1083.  
  1084.  or
  1085.  
  1086.    [owner.]object_name
  1087.  
  1088.  The default value for owner is the current user, and the default value for
  1089.  database is the current database. When you reference an object in SQL
  1090.  statements (other than CREATE statements) without qualifying it with the
  1091.  database name and owner name, SQL Server tries to find the object in the
  1092.  current database among the objects you own, so you need not qualify objects
  1093.  that you own.
  1094.  
  1095.  In addition, you need not qualify the names of objects owned by the Database
  1096.  Owner. When you give the name of an object, SQL Server first looks at all
  1097.  the objects you own and then at the objects owned by the Database Owner,
  1098.  whose name in the database is dbo.
  1099.  
  1100.  As long as SQL Server is given enough information to identify an object, you
  1101.  need not type every element of its name. Intermediate elements can be
  1102.  omitted and their positions indicated by dots:
  1103.  
  1104.    database..table_name
  1105.  
  1106.  When qualifying a column name and a table name in the same statement, be
  1107.  sure to use the same naming abbreviations for each; they are evaluated as
  1108.  strings and must match or an error message is returned.
  1109.  
  1110.  The following examples have different entries for the column name. The
  1111.  second example is not executed because the syntax for the column name does
  1112.  not match the syntax for the table name.
  1113.  
  1114.    select demo.mary.publishers.city
  1115.     from demo.mary.publishers
  1116.     city
  1117.     -----------------------
  1118.     Boston
  1119.     Washington
  1120.     Berkeley
  1121.  
  1122.     select demo.mary.publishers.city
  1123.     from demo..publishers
  1124.     The column prefix "demo.mary.publishers" does not match
  1125.     a table name or alias name used in the query.
  1126.  
  1127.  
  1128.  
  1129.  
  1130.  
  1131.  
  1132.  Chapter 2  Querying Databases
  1133.  ────────────────────────────────────────────────────────────────────────────
  1134.  
  1135.  
  1136.  Introduction
  1137.  
  1138.  The SELECT statement is used for choosing rows and columns from tables. You
  1139.  can use it for selections (retrieving a subset of the rows in one or more
  1140.  tables), projections (retrieving a subset of the columns in one or more
  1141.  tables), and joins (linking rows in two or more tables to retrieve
  1142.  cross-table data).
  1143.  
  1144.  In this chapter, you'll find information about
  1145.  
  1146.  
  1147.    ■   Selecting all or specified columns in a table
  1148.  
  1149.    ■   Changing the format for results
  1150.  
  1151.    ■   Including simple computed values in a SELECT statement
  1152.  
  1153.    ■   Eliminating duplicate rows with DISTINCT
  1154.  
  1155.    ■   Specifying tables and views with the FROM clause
  1156.  
  1157.    ■   Using the WHERE clause with comparison operators, logical operators,
  1158.        BETWEEN, IN, ANY, and LIKE
  1159.  
  1160.    ■   Using NULL and NOT NULL
  1161.  
  1162.    ■   Creating new tables for results with SELECT INTO
  1163.  
  1164.    ■   Using GROUP BY and HAVING
  1165.  
  1166.    ■   Sorting query results with ORDER BY
  1167.  
  1168.    ■   Producing simple summary reports with COMPUTE
  1169.  
  1170.  
  1171.  This chapter focuses on single-table SELECT statements. Information on
  1172.  advanced uses of SELECT is described in later chapters of this book:
  1173.  
  1174.  
  1175.    ■   Chapter 3, "Joining Two or More Tables," explains the join operation.
  1176.  
  1177.    ■   Chapter 4, "Displaying Totals: GROUP BY and  COMPUTE," gives details
  1178.        on the GROUP BY, HAVING, and COMPUTE BY clauses.
  1179.  
  1180.    ■   Chapter 5, "Using Built-In Functions," covers SQL Server's built-in
  1181.        functions.
  1182.  
  1183.    ■   Chapter 6, "Building Subqueries," focuses on subqueries, also known as
  1184.        nested queries or nested select statements.
  1185.  
  1186.  
  1187.  
  1188.  Choosing a Database: USE
  1189.  
  1190.  In most cases, when you log in to SQL Server, you are connected to the
  1191.  master database. To connect to pubs, you need to execute the USE statement.
  1192.  
  1193.  
  1194.  The USE statement accesses a database that already exists. It must be
  1195.  executed before you can do any other work in that database. The USE
  1196.  statement has the following syntax:
  1197.  
  1198.    USE database_name
  1199.  
  1200.  For example, to open pubs, type
  1201.  
  1202.    use pubs
  1203.  
  1204.  Usually, all users can access the master and pubs databases even if they
  1205.  haven't explicitly been given access to them. This is because users not
  1206.  recognized by name in the master or pubs databases are allowed access under
  1207.  the guest account.
  1208.  
  1209.  
  1210.  SELECT Syntax
  1211.  
  1212.  The SELECT statement specifies the columns you want to retrieve. The FROM
  1213.  clause specifies the tables where the columns are located. The WHERE clause
  1214.  specifies the rows in the tables you want to see.
  1215.  
  1216.  A simplified syntax for the SELECT statement is
  1217.  
  1218.    SELECT select_list
  1219.     FROM table_list
  1220.     WHERE search_conditions
  1221.  
  1222.  The following SELECT statement finds the first and last names of writers in
  1223.  the authors table who have a contract. (Authors with contracts have "1" in
  1224.  the contract column.)
  1225.  
  1226.    select au_fname, au_lname
  1227.     from authors
  1228.     where contract = 1
  1229.  
  1230.  SELECT statement results appear in a columnar format, like this:
  1231.  
  1232.    au_fname  au_lname
  1233.     ---------  --------------
  1234.     Johnson   White
  1235.     Marjorie  Green
  1236.     Cheryl   Carson
  1237.     Michael   O'Leary
  1238.     Dick   Straight
  1239.     Abraham   Bennet
  1240.     Ann    Dull
  1241.     Burt   Gringlesby
  1242.     Chastity  Locksley
  1243.     Reginald  Blotchet-Halls
  1244.     Akiko   Yokomoto
  1245.     Innes   del Castillo
  1246.     Michel   DeFrance
  1247.     Stearns   MacFeather
  1248.     Livia   Karsen
  1249.     Sylvia   Panteley
  1250.     Sheryl   Hunter
  1251.     Anne   Ringer
  1252.     Albert   Ringer
  1253.  
  1254.     (19 rows affected)
  1255.  
  1256.  The complete syntax of the SELECT statement includes the following phrases
  1257.  and keywords:
  1258.  
  1259.    SELECT [ALL | DISTINCT] select_list
  1260.     [INTO [[database.]owner.]table_name]
  1261.     [FROM [[database.]owner.]{table_name | view_name} [HOLDLOCK]
  1262.     [,[[database.]owner.]{table_name | view_name} [HOLDLOCK]...]
  1263.     [WHERE search_conditions]
  1264.     [GROUP BY [ALL] aggregate_free_expression
  1265.     [, aggregate_free_expression]...]
  1266.     [HAVING search_conditions]
  1267.     [ORDER BY {[[[database.]owner.]{table_name |
  1268.      view_name}.]column_name | select_list_number | expression}
  1269.     [ASC | DESC] [,{[[[database.]owner.]{table_name |
  1270.      view_name}.]column_name | select_list_number | expression}
  1271.     [ASC | DESC]]...]
  1272.     [COMPUTE row_aggregate(column_name)
  1273.     [, row_aggregate(column_name)...]
  1274.     [BY column_name [, column_name...]]]
  1275.     [FOR BROWSE]
  1276.  
  1277.  The clauses in a SELECT statement must be used in the order shown here.
  1278.  (That is, if the statement includes a GROUP BY clause and an ORDER BY
  1279.  clause, the GROUP BY clause must be typed before the ORDER BY clause.)
  1280.  
  1281.  As the "Identifiers" section in Chapter 1 explains, the names of database
  1282.  objects must be qualified if there is ambiguity about which object is being
  1283.  referred to. For example, if there are several columns called name, you may
  1284.  have to qualify name with the database name, owner name, or table name.
  1285.  
  1286.  Since the examples in this chapter involve single-table queries, column
  1287.  names in syntax models and examples are usually not qualified with the names
  1288.  of the tables, owners, or databases to which they belong. These elements are
  1289.  left out to promote readability; it is never wrong to include qualifiers.
  1290.  
  1291.  The following sections describe the syntax of the SELECT statement in
  1292.  detail.
  1293.  
  1294.  
  1295.  Choosing Columns: the Select List
  1296.  
  1297.  The select list frequently consists of a series of column names separated by
  1298.  commas (in the order in which the table was created) or an asterisk to
  1299.  represent all columns.
  1300.  
  1301.  However, the select list can include one or more expressions (separated by
  1302.  commas) where an expression is a constant, column name, function, subquery,
  1303.  or any combination of these connected by arithmetic or bitwise operators and
  1304.  parentheses. The select list has the following syntax:
  1305.  
  1306.    SELECT expression [, expression...]
  1307.     FROM table_list
  1308.  
  1309.  
  1310.  Choosing All Columns: SELECT *
  1311.  
  1312.  The asterisk (*) has a special meaning in SELECT statements. It stands for
  1313.  all the column names in all the tables in the FROM clause. Use it to save
  1314.  typing time (and cut down on typing errors) when you want to see all the
  1315.  columns in a table.
  1316.  
  1317.  The syntax for selecting all the columns in a table is as follows:
  1318.  
  1319.    SELECT *
  1320.     FROM table_list
  1321.  
  1322.  Because SELECT * finds all the columns currently in a table, changes in the
  1323.  structure of a table (adding, removing, or renaming columns) automatically
  1324.  modify the results of a SELECT *. Listing the columns individually allows
  1325.  more precise control over the results.
  1326.  
  1327.  The following statement retrieves all columns in the publishers table and
  1328.  displays them in the order in which they were defined when the publishers
  1329.  table was created. No WHERE clause is included, so this statement also
  1330.  retrieves every row.
  1331.  
  1332.    select *
  1333.     from publishers
  1334.  
  1335.  The results look like this:
  1336.  
  1337.    pub_id  pub_name    city   state
  1338.     ------  -------------------  ----------  -----
  1339.     0736  New Age Books   Boston   MA
  1340.     0877  Binnet & Hardley  Washington  DC
  1341.     1389  Algodata Infosystems Berkeley  CA
  1342.  
  1343.     (3 rows affected)
  1344.  
  1345.  You get exactly the same results by listing all the column names in the
  1346.  table in order after the SELECT keyword:
  1347.  
  1348.    select pub_id, pub_name, city, state
  1349.     from publishers
  1350.  
  1351.  You can use * more than once in a query:
  1352.  
  1353.    select *, *
  1354.     from publishers
  1355.  
  1356.  This format displays each column name and each piece of column data twice.
  1357.  
  1358.  Like a column name, * can be qualified with a table name, as in the
  1359.  following query:
  1360.  
  1361.    select publishers.*
  1362.     from publishers
  1363.  
  1364.  
  1365.  Choosing Specified Columns
  1366.  
  1367.  To select some (but not necessarily all) of the columns in a table, use the
  1368.  following syntax:
  1369.  
  1370.    SELECT column_name[, column_name...]
  1371.     FROM table_name
  1372.  
  1373.  Each column name must be separated from the following column name by a
  1374.  comma.
  1375.  
  1376.  
  1377.  Rearranging the Order of Columns
  1378.  
  1379.  The order in which you list the column names determines the order in which
  1380.  the columns are displayed. The following two examples show how you specify
  1381.  column order in a display and the results. Both of them find and display the
  1382.  publisher names and identification numbers from all three rows in the
  1383.  publishers table. The first one prints pub_id first, followed by pub_name.
  1384.  The second reverses that order. The information is exactly the same; only
  1385.  its organization changes.
  1386.  
  1387.    select pub_id, pub_name
  1388.     from publishers
  1389.  
  1390.     pub_id  pub_name
  1391.     ------  --------------------
  1392.     0736  New Age Books
  1393.     0877  Binnet & Hardley
  1394.     1389  Algodata Infosystems
  1395.  
  1396.     (3 rows affected)
  1397.  
  1398.     select pub_name, pub_id
  1399.     from publishers
  1400.  
  1401.     pub_name    pub_id
  1402.     -------------------- ------
  1403.     New Age Books   0736
  1404.     Binnet & Hardley  0877
  1405.     Algodata Infosystems 1389
  1406.  
  1407.     (3 rows affected)
  1408.  
  1409.  
  1410.  Renaming Columns in Query Results
  1411.  
  1412.  When query results are displayed, the name given to a column when it was
  1413.  created is the default heading. You can specify a column heading by using
  1414.  either "column heading = column_name" or "column_name column heading"
  1415.  instead of just the column name in a select list. This provides a substitute
  1416.  name for the column name. When this name is displayed in the results, it
  1417.  functions as a column heading, which can produce more readable results.
  1418.  
  1419.  For example, to change pub_name to Publisher in the query shown earlier,
  1420.  type either of the following statements:
  1421.  
  1422.    select Publisher = pub_name, pub_id
  1423.     from publishers
  1424.  
  1425.  or
  1426.  
  1427.    select pub_name Publisher, pub_id
  1428.     from publishers
  1429.  
  1430.  The results of either statement look like this:
  1431.  
  1432.    Publisher   pub_id
  1433.     ---------------- --------
  1434.     New Age Books   0736
  1435.     Binnet & Hardley  0877
  1436.     Algodata Infosystems 1389
  1437.  
  1438.     (3 rows affected)
  1439.  
  1440.  
  1441.  Character Strings in Query Results
  1442.  
  1443.  The SELECT statements you've seen so far produce results that consist of
  1444.  data from the tables in the FROM clause. Strings (of characters) can also be
  1445.  displayed in query results.
  1446.  
  1447.  Enclose the entire string in single or double quotation marks and separate
  1448.  it from other elements in the select list with commas. Use double quotation
  1449.  marks if there is an apostrophe in the string; otherwise, the apostrophe is
  1450.  interpreted as a single quotation mark.
  1451.  
  1452.  An example statement with a character string is shown here, followed by its
  1453.  results.
  1454.  
  1455.    select "The publisher's name is", Publisher = pub_name
  1456.     from publishers
  1457.  
  1458.            Publisher
  1459.     ------------------------ --------------------
  1460.     The publisher's name is  New Age Books
  1461.     The publisher's name is  Binnet & Hardley
  1462.     The publisher's name is  Algodata Infosystems
  1463.  
  1464.     (3 rows affected)
  1465.  
  1466.  
  1467.  Computed Values in the Select List
  1468.  
  1469.  You can perform computations with data from numeric columns or on numeric
  1470.  constants in a select list.
  1471.  
  1472.  
  1473.  Arithmetic Operators
  1474.  
  1475.  The following arithmetic operators are available. (See the SQL Server
  1476.  Language Reference for information on bitwise operators.)
  1477.  
  1478. ╓┌─────────────────────────────────┌─────────────────────────────────────────╖
  1479.  Symbol                            Operation
  1480.  ────────────────────────────────────────────────────────────────────────────
  1481.  ++                                addition
  1482.  
  1483.  -                                 subtraction
  1484.  
  1485.  /                                 division
  1486.  
  1487.  *                                 multiplication
  1488.  
  1489.  %                                 modulo
  1490.  
  1491.  ────────────────────────────────────────────────────────────────────────────
  1492.  
  1493.  Symbol                            Operation
  1494.  ────────────────────────────────────────────────────────────────────────────
  1495. 
  1496.  
  1497.  
  1498.  The arithmetic operators─addition, subtraction, division, and
  1499.  multiplication─can be used on any numeric column─int, smallint, tinyint,
  1500.  float, or money. The modulo operator cannot be used on money columns. A
  1501.  modulo is the integer remainder after a division operation on two integers.
  1502.  For example, 21 % 9 = 3, because 21 divided by 9 equals 2, with a remainder
  1503.  of 3.
  1504.  
  1505.  Certain arithmetic operations can also be performed on datetime columns,
  1506.  using the date functions. See Chapter 5, "Using Built-In Functions," for
  1507.  information on the date functions.
  1508.  
  1509.  All of these operators can be used in the select list with column names and
  1510.  numeric constants in any combination. The following example shows a
  1511.  projected sales increase of 100% for all the books in the titles table:
  1512.  
  1513. ╓┌───────┌────────────────────────────────────────────────────────┌──────────
  1514.  ────────────────────────────────────────────────────────────────────────────
  1515.          select title_id, ytd_sales, ytd_sales * 2
  1516.  
  1517.          from titles
  1518.  
  1519.          title_id                                                 ytd_sales
  1520.  
  1521.          --------                                                 ---------  -
  1522.  
  1523.          BU1032                                                   4095       8
  1524.  
  1525.          BU1111                                                   3876       7
  1526.  
  1527.          BU2075                                                   18722      3
  1528.  
  1529.          BU7832                                                   4095       8
  1530.  
  1531.          MC2222                                                   2032       4
  1532.  
  1533.          MC3021                                                   22246      4
  1534.  
  1535.  ────────────────────────────────────────────────────────────────────────────
  1536. 
  1537.          MC3026                                                   NULL       N
  1538.  
  1539.          PC1035                                                   8780       1
  1540.  
  1541.          PC8888                                                   4095       8
  1542.  
  1543.          PC9999                                                   NULL       N
  1544.  
  1545.          PS1372                                                   375        7
  1546.  
  1547.          PS2091                                                   2045       4
  1548.  
  1549.          PS2106                                                   111        2
  1550.  
  1551.          PS3333                                                   4072       8
  1552.  
  1553.          PS7777                                                   3336       6
  1554.  
  1555.          TC3218                                                   375        7
  1556.  ────────────────────────────────────────────────────────────────────────────
  1557.         TC3218                                                   375        7
  1558.  
  1559.          TC4203                                                   15096      3
  1560.  
  1561.          TC7777                                                   4095       8
  1562.  
  1563.          (18 rows affected)
  1564.  
  1565.  
  1566.  
  1567.  Notice the null values in the ytd_sales column and the computed column. Null
  1568.  values have no explicitly assigned values. When you perform any arithmetic
  1569.  operation on a null value, the result is NULL.
  1570.  
  1571.  To give the computed column a heading (say proj_sales), type
  1572.  
  1573.    select title_id, ytd_sales, proj_sales = ytd_sales * 2
  1574.     from titles
  1575.  
  1576.  You can also add character strings such as "Current sales =" and "Projected
  1577.  sales are" to the SELECT statement.
  1578.  
  1579.  The column from which the computed column is generated does not have to
  1580.  appear in the select list. The ytd_sales column, for example, is shown in
  1581.  these sample queries only for comparison of its values with the values from
  1582.  the ytd_sales * 2 column. To see just the computed values, type
  1583.  
  1584.    select title_id, ytd_sales * 2
  1585.     from titles
  1586.  
  1587.  Arithmetic operators also work directly with the data values in specified
  1588.  columns when no constants are involved. Here's an example:
  1589.  
  1590. ╓┌───────┌───────────────────────────────────────────────────────────────┌───
  1591.  ────────────────────────────────────────────────────────────────────────────
  1592.          select title_id, ytd_sales * price
  1593.  
  1594.          from titles
  1595.  
  1596.          title_id
  1597.  
  1598.  ────────────────────────────────────────────────────────────────────────────
  1599. 
  1600.          ------                                                          -----
  1601.  
  1602.          BU1032                                                          81,85
  1603.  
  1604.          BU1111                                                          46,31
  1605.  
  1606.          BU2075                                                          55,97
  1607.  
  1608.          BU7832                                                          81,85
  1609.  
  1610.          MC2222                                                          40,61
  1611.  
  1612.          MC3021                                                          66,51
  1613.  
  1614.          MC3026                                                          NULL
  1615.  
  1616.          PC1035                                                          201,5
  1617.  
  1618.          PC8888                                                          81,90
  1619.  ────────────────────────────────────────────────────────────────────────────
  1620.         PC8888                                                          81,90
  1621.  
  1622.          PC9999                                                          NULL
  1623.  
  1624.          PS1372                                                          8,096
  1625.  
  1626.          PS2091                                                          22,39
  1627.  
  1628.          PS2106                                                          777.0
  1629.  
  1630.          PS3333                                                          81,39
  1631.  
  1632.          PS7777                                                          26,65
  1633.  
  1634.          TC3218                                                          7,856
  1635.  
  1636.          TC4203                                                          180,3
  1637.  
  1638.          TC7777                                                          61,38
  1639.  
  1640.  ────────────────────────────────────────────────────────────────────────────
  1641. 
  1642.          (18 rows affected)
  1643.  
  1644.  
  1645.  
  1646.  Finally, computed columns can come from more than one table. (Chapter 3,
  1647.  "Joining Two or More Tables," and Chapter 6, "Building Subqueries," tell how
  1648.  to work with multiple-table queries, so check them for syntax details.)
  1649.  
  1650.  This query calculates the product of the quantity of books sold by an outlet
  1651.  (the qty column from the sales table) and the price of the book (the price
  1652.  column from the titles table).
  1653.  
  1654. ╓┌───────┌────────────────────────────────────────────────────────┌────────┌─
  1655.  ────────────────────────────────────────────────────────────────────────────
  1656.          select titles.title_id, stor_id, qty * price
  1657.  
  1658.          from titles, sales
  1659.  
  1660.          where titles.title_id = sales.title_id
  1661.  ────────────────────────────────────────────────────────────────────────────
  1662.         where titles.title_id = sales.title_id
  1663.  
  1664.          title_id                                                 stor_id
  1665.  
  1666.          -------                                                  -------  ---
  1667.  
  1668.          BU1032                                                   8042     199
  1669.  
  1670.          BU1032                                                   6380     99.
  1671.  
  1672.          BU1111                                                   8042     298
  1673.  
  1674.          BU2075                                                   7896     104
  1675.  
  1676.          BU7832                                                   7896     299
  1677.  
  1678.          MC2222                                                   7896     199
  1679.  
  1680.          MC3021                                                   7131     74.
  1681.  
  1682.  ────────────────────────────────────────────────────────────────────────────
  1683. 
  1684.          MC3021                                                   8042     44.
  1685.  
  1686.          PC1035                                                   8042     688
  1687.  
  1688.          PC8888                                                   7066     1,0
  1689.  
  1690.          PS1372                                                   7131     431
  1691.  
  1692.          PS2091                                                   7066     821
  1693.  
  1694.          PS2091                                                   7067     109
  1695.  
  1696.          PS2091                                                   7131     219
  1697.  
  1698.          PS2091                                                   6380     32.
  1699.  
  1700.          PS2106                                                   7131     175
  1701.  
  1702.          PS3333                                                   7131     299
  1703.  ────────────────────────────────────────────────────────────────────────────
  1704.         PS3333                                                   7131     299
  1705.  
  1706.          PS7777                                                   7131     199
  1707.  
  1708.          TC3218                                                   7067     838
  1709.  
  1710.          TC4203                                                   7067     239
  1711.  
  1712.          TC7777                                                   7067     299
  1713.  
  1714.          (21 rows affected)
  1715.  
  1716.  
  1717.  
  1718.  
  1719.  Datatype Precedence in Mixed-Mode Arithmetic
  1720.  
  1721.  Mixed-mode arithmetic means performing arithmetic operations on values of
  1722.  different datatypes; for example int + smallint. The hierarchy of datatypes,
  1723.  which is created from the rank ordering of the hexadecimal values of the
  1724.  datatype0 codes, determines the datatype of the result. In a mixed mode
  1725.  expression, the lower datatype is converted internally to the higher type.
  1726.  
  1727.  In the following example, qty from the sales table is multiplied by royalty
  1728.  from the roysched table. qty has a smallint datatype; royalty has an int
  1729.  datatype. The smallint datatype has a hexadecimal value of 34; the int
  1730.  datatype has a hexadecimal value of 38. Therefore, the resultant datatype is
  1731.  int.
  1732.  
  1733.    smallint(qty) * int(royalty) = int
  1734.  
  1735.  The hierarchy of datatypes is shown in the system table systypes. (See also
  1736.  the SQL Server System Administrator's Guide and the SQL Server Language
  1737.  Reference.)
  1738.  
  1739.  You can use the following query to obtain a list of datatypes with their
  1740.  decimal and hexadecimal values. Select the name of the datatype and its
  1741.  decimal type code; then use the CONVERT function to compute the hexadecimal
  1742.  value of each datatype.
  1743.  
  1744. ╓┌───────┌───────────────────────────────────────────────────────────────┌───
  1745.  ────────────────────────────────────────────────────────────────────────────
  1746.          select name, type, hex=convert(varbinary(2),type) from
  1747.          systypes
  1748.  
  1749.          order by type
  1750.  
  1751.          go
  1752.  
  1753.          name                                                            type
  1754.  
  1755.          ---------                                                       ----
  1756.  
  1757.          image                                                           34
  1758.  
  1759.          text                                                            35
  1760.  
  1761.          timestamp                                                       37
  1762.  
  1763.          varbinary                                                       37
  1764.  
  1765.          intn                                                            38
  1766.  ────────────────────────────────────────────────────────────────────────────
  1767.         intn                                                            38
  1768.  
  1769.          id                                                              39
  1770.  
  1771.          tid                                                             39
  1772.  
  1773.          sysname                                                         39
  1774.  
  1775.          varchar                                                         39
  1776.  
  1777.          binary                                                          45
  1778.  
  1779.          char                                                            47
  1780.  
  1781.          tinyint                                                         48
  1782.  
  1783.          bit                                                             50
  1784.  
  1785.          smallint                                                        52
  1786.  
  1787.  ────────────────────────────────────────────────────────────────────────────
  1788. 
  1789.          int                                                             56
  1790.  
  1791.          money                                                           60
  1792.  
  1793.          datetime                                                        61
  1794.  
  1795.          float                                                           62
  1796.  
  1797.          floatn                                                          109
  1798.  
  1799.          moneyn                                                          110
  1800.  
  1801.          datetimn                                                        111
  1802.  
  1803.          (21 rows affected)
  1804.  
  1805.  
  1806.  
  1807.  The results of this query on one of your databases will be slightly
  1808.  different if you have any user-defined datatypes. User-defined datatypes
  1809.  take on the hexadecimal value of their base datatypes.
  1810.  
  1811.  
  1812.  Arithmetic Operator Precedence
  1813.  
  1814.  When there is more than one arithmetic operator in an expression,
  1815.  multiplication, division, and modulo are calculated first, followed by
  1816.  subtraction and addition. When all arithmetic operators in an expression
  1817.  have the same level of precedence, the order of execution is left to right.
  1818.  Expressions within parentheses take precedence over all other operations.
  1819.  
  1820.  For example, the following SELECT statement subtracts the part of the
  1821.  year-to-date sales that the author receives (sales times author's royalty
  1822.  percent, divided by 100) from the total sales. The final result is the
  1823.  amount of money the publisher receives.
  1824.  
  1825.  The product of ytd_sales and royalty is calculated first because the
  1826.  operator is multiplication. Next, the total is divided by 100. Then, this
  1827.  result is subtracted from ytd_sales.
  1828.  
  1829.    select title_id, ytd_sales - ytd_sales * royalty / 100
  1830.     from titles
  1831.  
  1832.  To avoid misunderstandings, use parentheses. The following query has the
  1833.  same meaning and gives the same results as the previous one, but some may
  1834.  find it easier to understand:
  1835.  
  1836. ╓┌───────┌───────────────────────────────────────────────────────────────────
  1837.  ────────────────────────────────────────────────────────────────────────────
  1838.          select title_id, ytd_sales - (ytd_sales * royalty / 100)
  1839.  
  1840.          from titles
  1841.  
  1842.          title_id
  1843.  
  1844.          --------
  1845.  
  1846.          BU1032
  1847.  
  1848.          BU1111
  1849.  
  1850.  ────────────────────────────────────────────────────────────────────────────
  1851. 
  1852.          BU2075
  1853.  
  1854.          BU7832
  1855.  
  1856.          MC2222
  1857.  
  1858.          MC3021
  1859.  
  1860.          MC3026
  1861.  
  1862.          PC1035
  1863.  
  1864.          PC8888
  1865.  
  1866.          PC9999
  1867.  
  1868.          PS1372
  1869.  
  1870.          PS2091
  1871.  ────────────────────────────────────────────────────────────────────────────
  1872.         PS2091
  1873.  
  1874.          PS2106
  1875.  
  1876.          PS3333
  1877.  
  1878.          PS7777
  1879.  
  1880.          TC3218
  1881.  
  1882.          TC4203
  1883.  
  1884.          TC7777
  1885.  
  1886.          (18 rows affected)
  1887.  
  1888.  
  1889.  
  1890.  Use parentheses to change the order of execution; calculations inside
  1891.  parentheses are handled first. If parentheses are nested, the most deeply
  1892.  nested calculation has precedence. For example, the result and meaning of
  1893.  the preceding can be changed if you use parentheses to force evaluation of
  1894.  the subtraction before the multiplication:
  1895.  
  1896. ╓┌───────┌───────────────────────────────────────────────────────────────────
  1897.  ────────────────────────────────────────────────────────────────────────────
  1898.          select title_id, (ytd_sales - ytd_sales) * royalty / 100
  1899.  
  1900.          from titles
  1901.  
  1902.          title_id
  1903.  
  1904.          --------
  1905.  
  1906.          BU1032
  1907.  
  1908.          BU1111
  1909.  
  1910.          BU2075
  1911.  
  1912.          BU7832
  1913.  ────────────────────────────────────────────────────────────────────────────
  1914.         BU7832
  1915.  
  1916.          MC2222
  1917.  
  1918.          MC3021
  1919.  
  1920.          MC3026
  1921.  
  1922.          PC1035
  1923.  
  1924.          PC8888
  1925.  
  1926.          PC9999
  1927.  
  1928.          PS1372
  1929.  
  1930.          PS2091
  1931.  
  1932.          PS2106
  1933.  
  1934.  ────────────────────────────────────────────────────────────────────────────
  1935. 
  1936.          PS3333
  1937.  
  1938.          PS7777
  1939.  
  1940.          TC3218
  1941.  
  1942.          TC4203
  1943.  
  1944.          TC7777
  1945.  
  1946.          (18 rows affected)
  1947.  
  1948.  
  1949.  
  1950.  
  1951.  Selecting text and image Values
  1952.  
  1953.  You may select text and image values with the SELECT or READTEXT statements.
  1954.  
  1955.  
  1956.  
  1957.  Using the SELECT Statement
  1958.  
  1959.  When the select list includes text and image values, the limit on the length
  1960.  of the data returned depends on the setting of the @TEXTSIZE global
  1961.  variable. The default setting for TEXTSIZE is 32 kilobytes (K). The value is
  1962.  changed with the SET statement, as shown in the following example:
  1963.  
  1964.    set textsize 25
  1965.  
  1966.  With this setting of TEXTSIZE, a SELECT statement that included a text
  1967.  column would display only the first 25 characters of the data, as shown in
  1968.  the following example:
  1969.  
  1970.    select (pub_id, blurb) from blurbs
  1971.  
  1972.  Since pubs does not actually contain a blurbs table with a blurb text
  1973.  column, this example cannot be run.
  1974.  
  1975.  ────────────────────────────────────────────────────────────────────────────
  1976.  NOTE
  1977.  
  1978.  When you are selecting image data, the returned value includes the
  1979.  characters "Ox" that indicate the data is hexadecimal. These two characters
  1980.  are counted as part of TEXTSIZE.
  1981.  ────────────────────────────────────────────────────────────────────────────
  1982.  
  1983.  To reset TEXTSIZE to its default value, use the following statement:
  1984.  
  1985.    set textsize 0
  1986.  
  1987.  The default display is the actual length of the data when its size is less
  1988.  than TEXTSIZE.
  1989.  
  1990.  
  1991.  Using the READTEXT Statement
  1992.  
  1993.  The READTEXT statement provides another way to retrieve text and image
  1994.  values. The READTEXT statement parameters include the name of the table and
  1995.  column, the text pointer, a starting offset within the column, and the
  1996.  number of bytes to retrieve. The following example finds five characters in
  1997.  the blurb column in the blurbs table:
  1998.  
  1999.    declare @val varbinary (30)
  2000.     select @val = textptr(blurb) from blurbs
  2001.     where title_id = "PS3333"
  2002.     readtext blurbs.blurb @val 1 5
  2003.  
  2004.  In this example, READTEXT displays characters 2 through 6 of the blurb
  2005.  column, since the offset was 1.
  2006.  
  2007.  ────────────────────────────────────────────────────────────────────────────
  2008.  NOTE
  2009.  
  2010.  Since pubs does not actually contain a blurbs table, this example cannot be
  2011.  run.
  2012.  ────────────────────────────────────────────────────────────────────────────
  2013.  
  2014.  The READTEXT statement has the following syntax:
  2015.  
  2016.    READTEXT [[database.]owner.]table_name.column_name text_ptr
  2017.     offset size [HOLDLOCK]
  2018.  
  2019.  Without using a local variable a statement such as the following returns a
  2020.  long binary string:
  2021.  
  2022.    textptr(text_col) from my_table
  2023.  
  2024.  It is a good idea to put this string into a local variable, as in the
  2025.  preceding example, and use it by reference.
  2026.  
  2027.  
  2028.  Select List Summary
  2029.  
  2030.  The select list can include * (all columns in the order in which the table
  2031.  was created), a list of column names in any order, character strings, column
  2032.  headings, and expressions including arithmetic operators. You can also
  2033.  include aggregate functions, which are discussed in "Grouping Data: GROUP BY
  2034.  and HAVING Clauses," later in this chapter, and in Chapter 4, "Displaying
  2035.  Totals: GROUP BY and COMPUTE." Here are some select lists to try with the
  2036.  tables in the pubs database:
  2037.  
  2038.    A. select titles.*
  2039.     from titles
  2040.  
  2041.    B. select Name = au_fname, Surname = au_lname
  2042.     from authors
  2043.  
  2044.    C. select Sales = ytd_sales, ToAuthor = ytd_sales * royalty,
  2045.     ToPublisher = ytd_sales - (ytd_sales * royalty)
  2046.     from titles
  2047.  
  2048.    D. select 'Social security #', au_id
  2049.     from authors
  2050.  
  2051.    E. select this_year = advance,
  2052.     next_year = advance + advance/10,
  2053.     third_year = advance /2, 'for book title #', title_id
  2054.     from titles
  2055.  
  2056.    F. select 'Total income is', Revenue = price * ytd_sales,
  2057.     'for', Book# = title_id
  2058.     from titles
  2059.  
  2060.  
  2061.  Eliminating Duplicates: DISTINCT
  2062.  
  2063.  The DISTINCT keyword, which is optional before the select list, eliminates
  2064.  duplicate rows from the results of a SELECT statement.
  2065.  
  2066.  If you don't specify DISTINCT, you get all rows, including duplicates.
  2067.  
  2068.  For example, if you select all the author identification codes in the
  2069.  titleauthor table without DISTINCT, you'll get these rows:
  2070.  
  2071.    select au_id
  2072.     from titleauthor
  2073.  
  2074.     au_id
  2075.     -----------
  2076.     172-32-1176
  2077.     213-46-8915
  2078.     213-46-8915
  2079.     238-95-7766
  2080.     267-41-2394
  2081.     267-41-2394
  2082.     274-80-9391
  2083.     409-56-7008
  2084.     427-17-2319
  2085.     472-27-2349
  2086.     486-29-1786
  2087.     486-29-1786
  2088.     648-92-1872
  2089.     672-71-3249
  2090.     712-45-1867
  2091.     722-51-5454
  2092.     724-80-9391
  2093.     724-80-9391
  2094.     756-30-7391
  2095.     807-91-6654
  2096.     846-92-7186
  2097.     899-46-2035
  2098.     899-46-2035
  2099.     998-72-3567
  2100.     998-72-3567
  2101.  
  2102.     (25 rows affected)
  2103.  
  2104.  Looking at the results, you'll see that there are some duplicate listings.
  2105.  You can eliminate them and see only the unique au_ids with DISTINCT:
  2106.  
  2107.    select distinct au_id
  2108.     from titleauthor
  2109.  
  2110.     au_id
  2111.     -----------
  2112.     172-32-1176
  2113.     213-46-8915
  2114.     238-95-7766
  2115.     267-41-2394
  2116.     274-80-9391
  2117.     409-56-7008
  2118.     427-17-2319
  2119.     472-27-2349
  2120.     486-29-1786
  2121.     648-92-1872
  2122.     672-71-3249
  2123.     712-45-1867
  2124.     722-51-5454
  2125.     724-80-9391
  2126.     756-30-7391
  2127.     807-91-6654
  2128.     846-92-7186
  2129.     899-46-2035
  2130.     998-72-3567
  2131.  
  2132.     (19 rows affected)
  2133.  
  2134.  ────────────────────────────────────────────────────────────────────────────
  2135.  NOTE
  2136.  
  2137.  For compatibility with other implementations of SQL, SQL Server syntax
  2138.  allows the use of the ALL keyword to explicitly ask for all rows. However,
  2139.  there is no reason to use ALL because "all rows" is the default.
  2140.  ────────────────────────────────────────────────────────────────────────────
  2141.  
  2142.  For the DISTINCT keyword, null values are considered to be duplicates of
  2143.  each other. In other words, when DISTINCT is included in a SELECT statement,
  2144.  only one NULL is returned in the results, no matter how many null values are
  2145.  encountered.
  2146.  
  2147.  
  2148.  Specifying Tables: the FROM Clause
  2149.  
  2150.  The FROM clause is required in every SELECT statement involving data from
  2151.  tables or views. Use it to list all the tables and views containing columns
  2152.  included in the select list and in the WHERE clause. If the FROM clause
  2153.  includes more than one table or view, separate them with commas. The FROM
  2154.  clause has the following syntax:
  2155.  
  2156.    SELECT select_list
  2157.     FROM [[database.]owner.]{table_name | view_name} [HOLDLOCK]
  2158.     [,[[database.]owner.]{table_name | view_name} [HOLDLOCK]...]
  2159.  
  2160.  Table names can be from 1 to 30 characters long. You can use a letter, #, or
  2161.  _ as the first character. The following characters can be digits, letters,
  2162.  #, $, or _. A table name that begins with # denotes a temporary table. (See
  2163.  Chapter 7, "Creating Databases, Tables, and Indexes.")
  2164.  
  2165.  The full naming syntax for tables and views is always permitted in the FROM
  2166.  clause:
  2167.  
  2168.    database.owner.table_name
  2169.  
  2170.     database.owner.view_name
  2171.  
  2172.  This is necessary, however, only when there might be some confusion about
  2173.  the name.
  2174.  
  2175.  Table names can be given aliases to save typing. Aliases are assigned in the
  2176.  FROM clause by giving the alias after the table name:
  2177.  
  2178.    select p.pub_id, p.pub_name
  2179.     from publishers p
  2180.  
  2181.  The optional HOLDLOCK keyword in a SELECT statement makes a system-generated
  2182.  lock more restrictive. It keeps a shared lock in force until the completion
  2183.  of a transaction, instead of releasing the lock as soon as the data is no
  2184.  longer needed. (See Chapter 14, "Advanced Topics for Database Owners," for
  2185.  details.)
  2186.  
  2187.  
  2188.  Selecting Rows: the WHERE Clause
  2189.  
  2190.  The WHERE clause in a SELECT statement specifies the criteria for exactly
  2191.  which rows are retrieved. The WHERE clause has the following syntax:
  2192.  
  2193.    SELECT select_list
  2194.     FROM table_list
  2195.     WHERE search_conditions
  2196.  
  2197.  Search conditions, or qualifications, in the WHERE clause include
  2198.  
  2199.  
  2200.    ■   Comparison operators (=, <, >, and so on)
  2201.  
  2202.        where advance * 2 > ytd_sales * price
  2203.  
  2204.  
  2205.    ■   Ranges (BETWEEN and NOT BETWEEN)
  2206.  
  2207.        where ytd_sales between 4095 and 12000
  2208.  
  2209.  
  2210.    ■   Lists (IN, NOT IN)
  2211.  
  2212.        where state in ("CA", "IN", "MD")
  2213.  
  2214.  
  2215.    ■   Character matches (LIKE and NOT LIKE)
  2216.  
  2217.        where phone not like "415%"
  2218.  
  2219.  
  2220.    ■   Unknown values (IS NULL and IS NOT NULL)
  2221.  
  2222.        where advance is null
  2223.  
  2224.  
  2225.    ■   Combinations of these (AND, OR)
  2226.  
  2227.        where advance < 5000 or ytd_sales between 2000 and 2500
  2228.  
  2229.  
  2230.  
  2231.  In addition, the WHERE keyword can introduce join conditions and subqueries.
  2232.  (See Chapter 3, "Joining Two or More Tables," and Chapter 6, "Building
  2233.  Subqueries.")
  2234.  
  2235.  ────────────────────────────────────────────────────────────────────────────
  2236.  NOTE
  2237.  
  2238.  The only WHERE condition that you can use on text columns is LIKE (and NOT
  2239.  LIKE).
  2240.  ────────────────────────────────────────────────────────────────────────────
  2241.  
  2242.  For a complete list of the possible search conditions, including a few not
  2243.  mentioned here, see the "Search Conditions" or "WHERE Clause" section of the
  2244.  SQL Server Language Reference.
  2245.  
  2246.  
  2247.  Comparison Operators
  2248.  
  2249.  TRANSACT-SQL uses the following comparison operators:
  2250.  
  2251. ╓┌─────────────────────────────────┌─────────────────────────────────────────╖
  2252.  Operator                          Meaning
  2253.  ────────────────────────────────────────────────────────────────────────────
  2254.  =                                 equal to
  2255.  
  2256.  >                                 greater than
  2257.  
  2258.  <                                 less than
  2259.  
  2260.  >=                                greater than or equal to
  2261.  
  2262.  <=                                less than or equal to
  2263.  
  2264.  !=                                not equal to
  2265.  
  2266.  !>                                not greater than
  2267.  
  2268.  !<                                not less than
  2269.  
  2270.  Operator                          Meaning
  2271.  ────────────────────────────────────────────────────────────────────────────
  2272. 
  2273.  ────────────────────────────────────────────────────────────────────────────
  2274.  
  2275.  
  2276.  
  2277.  The operators have the following syntax:
  2278.  
  2279.    WHERE expression comparison_operator expression
  2280.  
  2281.  An expression is a constant, column name, function, subquery, or any
  2282.  combination of them connected by arithmetic or bitwise operators.
  2283.  
  2284.  In comparing char and varchar data, < means earlier in the alphabet, and >
  2285.  means later in the alphabet.
  2286.  
  2287.  Trailing blanks are ignored for the purposes of comparison. So, for example,
  2288.  "Dirk" is the same as "Dirk ".
  2289.  
  2290.  In comparing dates, < means earlier and > means later.
  2291.  
  2292.  Be sure to put apostrophes or quotation marks around all char, varchar,
  2293.  text, and datetime data. (For more on entering datetime data, see Chapter 9,
  2294.  "Adding, Changing, and Removing Data.")
  2295.  
  2296.  The following examples use SELECT statements with comparison operators:
  2297.  
  2298.    A. select *
  2299.     from titleauthor
  2300.     where royaltyper < 50
  2301.    B. select authors.au_lname, authors.au_fname
  2302.     from authors
  2303.     where au_lname >'McBadden'
  2304.    C. select au_id, phone
  2305.     from authors
  2306.     where phone !='415 658-9932'
  2307.    D. select title_id, newprice = price * $1.15
  2308.     from pubs..titles
  2309.     where advance > 5000
  2310.  
  2311.  NOT negates an expression. Either of the two following queries will find all
  2312.  business and psychology books that do not have an advance over $5,500.
  2313.  However, note the difference in position between the negative logical
  2314.  operator (NOT) and the negative comparison operator (!).
  2315.  
  2316.    select title_id, type, advance
  2317.     from titles
  2318.     where (type = "business" or type = "psychology")
  2319.     and not advance >5500
  2320.  
  2321.     select title_id, type, advance
  2322.     from titles
  2323.     where (type = "business" or type = "psychology")
  2324.     and advance !>5500
  2325.  
  2326.     title_id  type    advance
  2327.     --------  ----------   --------
  2328.     BU1032   business   5,000.00
  2329.     BU1111   business   5,000.00
  2330.     BU7832   business   5,000.00
  2331.     PS2091   psychology   2,275.00
  2332.     PS3333   psychology   2,000.00
  2333.     PS7777   psychology   4,000.00
  2334.  
  2335.     (6 rows affected)
  2336.  
  2337.  
  2338.  Ranges (BETWEEN and NOT BETWEEN)
  2339.  
  2340.  The BETWEEN keyword specifies an inclusive range in which the lower value
  2341.  and the upper value are searched for as well as the values they bracket.
  2342.  
  2343.  For example, to find all the books with sales between (and including) 4,095
  2344.  and 12,000, use this query:
  2345.  
  2346. ╓┌───────┌────────────────────────────────────────────────────────────────┌──
  2347.  ────────────────────────────────────────────────────────────────────────────
  2348.          select title_id, ytd_sales
  2349.  
  2350.          from titles
  2351.  
  2352.          where ytd_sales between 4095 and 12000
  2353.  
  2354.  ────────────────────────────────────────────────────────────────────────────
  2355. 
  2356.          title_id                                                         ytd_
  2357.  
  2358.          --------                                                         ----
  2359.  
  2360.          BU1032                                                           4095
  2361.  
  2362.          BU7832                                                           4095
  2363.  
  2364.          PC1035                                                           8780
  2365.  
  2366.          PC8888                                                           4095
  2367.  
  2368.          TC7777                                                           4095
  2369.  
  2370.          (5 rows affected)
  2371.  
  2372.  
  2373.  
  2374.  Notice that books with sales of 4,095 are included in the results. If there
  2375.  were any with sales of 12,000, they would be included too. You can specify
  2376.  an exclusive range with the greater-than and less-than operators. The same
  2377.  query using the greater-than and less-than operators returns the following
  2378.  results because these operators are not inclusive:
  2379.  
  2380. ╓┌───────┌────────────────────────────────────────────────────────────────┌──
  2381.  ────────────────────────────────────────────────────────────────────────────
  2382.          select title_id, ytd_sales
  2383.  
  2384.          from titles
  2385.  
  2386.          where ytd_sales > 4095 and ytd_sales < 12000
  2387.  
  2388.          title_id                                                         ytd_
  2389.  
  2390.          --------                                                         ----
  2391.  
  2392.          PC1035                                                           8780
  2393.  
  2394.          (1 row affected)
  2395.  
  2396.  ────────────────────────────────────────────────────────────────────────────
  2397. 
  2398.  
  2399.  
  2400.  NOT BETWEEN finds all the rows that are not inside the range. To find all
  2401.  the books with sales outside the 4,095 to 12,000 range, type
  2402.  
  2403. ╓┌───────┌────────────────────────────────────────────────────────────────┌──
  2404.  ────────────────────────────────────────────────────────────────────────────
  2405.          select title_id, ytd_sales
  2406.  
  2407.          from titles
  2408.  
  2409.          where ytd_sales not between 4095 and 12000
  2410.  
  2411.          title_id                                                         ytd_
  2412.  
  2413.          --------                                                         ----
  2414.  
  2415.          BU1111                                                           3876
  2416.  
  2417.  ────────────────────────────────────────────────────────────────────────────
  2418. 
  2419.          BU2075                                                           1872
  2420.  
  2421.          MC2222                                                           2032
  2422.  
  2423.          MC3021                                                           2224
  2424.  
  2425.          PS1372                                                           375
  2426.  
  2427.          PS2091                                                           2045
  2428.  
  2429.          PS2106                                                           111
  2430.  
  2431.          PS3333                                                           4072
  2432.  
  2433.          PS7777                                                           3336
  2434.  
  2435.          TC3218                                                           375
  2436.  
  2437.          TC4203                                                           1509
  2438.  ────────────────────────────────────────────────────────────────────────────
  2439.         TC4203                                                           1509
  2440.  
  2441.          (11 rows affected)
  2442.  
  2443.  
  2444.  
  2445.  
  2446.  Lists (IN and NOT IN)
  2447.  
  2448.  The IN keyword allows you to select values that match any one of a list of
  2449.  values. For example, without IN, if you want a list of the names and states
  2450.  of all the authors who live in California, Indiana, or Maryland, you can
  2451.  type this query:
  2452.  
  2453.    select au_lname, state
  2454.     from authors
  2455.     where state = 'CA' or state = 'IN' or state = 'MD'
  2456.  
  2457.  However, you get the same results with less typing if you use IN. The items
  2458.  following the IN keyword must be separated by commas and enclosed in
  2459.  parentheses.
  2460.  
  2461.    select au_lname, state
  2462.     from authors
  2463.     where state in('CA', 'IN', 'MD')
  2464.  
  2465.  This is what results from either query:
  2466.  
  2467.    au_lname  state
  2468.     --------  -----
  2469.     White   CA
  2470.     Green   CA
  2471.     Carson   CA
  2472.     O'Leary   CA
  2473.     Straight  CA
  2474.     Bennet   CA
  2475.     Dull   CA
  2476.     Gringlesby  CA
  2477.     Locksley  CA
  2478.     Yokomoto  CA
  2479.     DeFrance  IN
  2480.     Stringer  CA
  2481.     MacFeather  CA
  2482.     Karsen   CA
  2483.     Panteley  MD
  2484.     Hunter   CA
  2485.     McBadden  CA
  2486.  
  2487.     (17 rows affected)
  2488.  
  2489.  Perhaps the most important use for the IN keyword is in nested queries, also
  2490.  referred to as subqueries. (For a full discussion of subqueries, see Chapter
  2491.  6, "Building Subqueries.") The following example gives some idea of what you
  2492.  can do with nested queries and the IN keyword.
  2493.  
  2494.  Suppose you want to know the names of the authors who receive less than 50
  2495.  percent of the total royalties on the books they coauthor. The authors table
  2496.  gives author names and the titleauthor table gives royalty information. By
  2497.  putting the two together using IN (but without listing the two tables in the
  2498.  same FROM clause) you can extract the information you need.
  2499.  
  2500.  The following query finds all the au_ids in the titleauthor table for
  2501.  authors who make less than 50 percent of the royalty on any one book, then
  2502.  selects from the authors table all the author names with au_ids that match
  2503.  the results from the titleauthor query. The results show that several
  2504.  authors fall into the less than 50 percent category.
  2505.  
  2506.    select au_lname, au_fname
  2507.     from authors
  2508.     where au_id in
  2509.     (select au_id
  2510.     from titleauthor
  2511.     where royaltyper <50)
  2512.  
  2513.     au_lname   au_fname
  2514.     -----------   --------
  2515.     Green    Marjorie
  2516.     O'Leary    Michael
  2517.     O'Leary    Michael
  2518.     Gringlesby   Burt
  2519.     Yokomoto   Akiko
  2520.     MacFeather   Stearns
  2521.     Ringer    Anne
  2522.  
  2523.     (7 rows affected)
  2524.  
  2525.  NOT IN finds the authors that do not match the items in the list. The
  2526.  following query finds the names of authors who do not make less than 50
  2527.  percent of the royalties on at least one book.
  2528.  
  2529.    select au_lname, au_fname
  2530.     from authors
  2531.     where au_id not in
  2532.     (select au_id
  2533.     from titleauthor
  2534.     where royaltyper <50)
  2535.  
  2536.     au_lname   au_fname
  2537.     -------------  --------
  2538.     White    Johnson
  2539.     Carson    Cheryl
  2540.     Straight   Dick
  2541.     Smith    Meander
  2542.     Bennet    Abraham
  2543.     Dull    Ann
  2544.     Locksley   Chastity
  2545.     Greene    Morningstar
  2546.     Blotchet-Halls  Reginald
  2547.     del Castillo  Innes
  2548.     DeFrance   Michel
  2549.     Stringer   Dirk
  2550.     Karsen    Livia
  2551.     Panteley   Sylvia
  2552.     Hunter    Sheryl
  2553.     McBadden   Heather
  2554.     Ringer    Albert
  2555.  
  2556.     (17 rows affected)
  2557.  
  2558.  
  2559.  Wildcards and the LIKE Clause
  2560.  
  2561.  The LIKE keyword selects rows containing fields that match specified
  2562.  portions of character strings. LIKE is used with char, varchar, text, and
  2563.  datetime data. It takes four wildcard characters:
  2564.  
  2565. ╓┌─────────────────────────────────┌─────────────────────────────────────────
  2566.  Wildcard                          Meaning
  2567.  ────────────────────────────────────────────────────────────────────────────
  2568.  %                                 Any string of zero or more characters
  2569.  
  2570.  _                                 Any single character
  2571.  
  2572.  [ ]                               Any single character within the specified
  2573.                                    range (for example, [a-f]) or set (for
  2574.                                    example, [abcdef])
  2575.  
  2576.  [^]                               Any single character not within the
  2577.                                    specified range (for example, [^a-f]) or
  2578.                                    set (for example, [^abcdef])
  2579.  
  2580.  ────────────────────────────────────────────────────────────────────────────
  2581.  
  2582.  
  2583.  
  2584.  Enclose the wildcard(s) and character string in quotation marks. For
  2585.  example, using LIKE with the data in the authors table:
  2586.  
  2587.  
  2588.    ■   LIKE 'Mc%' searches for every name that begins with the letters "Mc"
  2589.        (McBadden).
  2590.  
  2591.    ■   LIKE '%inger' searches for every name that ends with "inger" (Ringer,
  2592.        Stringer).
  2593.  
  2594.    ■   LIKE '%en%' searches for every name that has the letters "en" in it
  2595.        (Bennet, Green, McBadden).
  2596.  
  2597.    ■   LIKE '_heryl' searchs for every 6-letter name ending with "heryl"
  2598.        (Cheryl).
  2599.  
  2600.    ■   LIKE '[CK]ars[eo]n' searches for "Carsen," "Karsen," "Carson," and
  2601.        "Karson" (Carson).
  2602.  
  2603.    ■   LIKE '[M-Z]inger' searches for all the names ending with "inger" that
  2604.        begin with any single letter from M to Z (Ringer).
  2605.  
  2606.    ■   LIKE 'M[^c]%' searches for all names beginning with "M" not having "c"
  2607.        as the second letter.
  2608.  
  2609.  
  2610.  This query finds all the phone numbers in the authors table that have 415 as
  2611.  the area code:
  2612.  
  2613.    select phone
  2614.     from authors
  2615.     where phone like '415%'
  2616.  
  2617.  You can use NOT LIKE with the same wildcards. To find all the phone numbers
  2618.  in the authors table that do not have 415 as the area code, you could use
  2619.  either of these queries (they are equivalent):
  2620.  
  2621.    select phone
  2622.     from authors
  2623.     where phone not like '415%'
  2624.  
  2625.     select phone
  2626.     from authors
  2627.     where not phone like '415%'
  2628.  
  2629.  Wildcards used without LIKE are interpreted as literals rather than as a
  2630.  pattern; they represent exactly their own values. The following query
  2631.  attempts to find any phone numbers that consist of the four characters
  2632.  "415%" only. It will not find phone numbers that start with 415.
  2633.  
  2634.    select phone
  2635.     from authors
  2636.     where phone = '415%'
  2637.  
  2638.  You can search for the wildcards themselves, too. To use the wildcards as
  2639.  characters in a LIKE match string rather than as wildcards, use square
  2640.  brackets to enclose the percent sign, the underscore, and the open bracket;
  2641.  use the close bracket by itself. To search for a dash, rather than using it
  2642.  to specify a range for which to search, use the dash as the first character
  2643.  inside a set of brackets.
  2644.  
  2645. ╓┌─────────────────────────────────┌─────────────────────────────────────────
  2646.  Symbol                            Meaning
  2647.  ────────────────────────────────────────────────────────────────────────────
  2648.  Symbol                            Meaning
  2649.  ────────────────────────────────────────────────────────────────────────────
  2650.  LIKE '5%'                         5 followed by any string of 0 or more
  2651.                                    characters
  2652.  
  2653.  LIKE '5[%]'                       5%
  2654.  
  2655.  LIKE '_n'                         an, in, on, and so on
  2656.  
  2657.  LIKE '[_]n'                       _n
  2658.  
  2659.  LIKE '[a-cdf]'                    a, b, c, d, or f
  2660.  
  2661.  LIKE '[-acdf]'                    -, a, c, d, or f
  2662.  
  2663.  LIKE '[[]'                         [
  2664.  
  2665.  LIKE ']'                          ]
  2666.  
  2667.  ────────────────────────────────────────────────────────────────────────────
  2668.  
  2669.  Symbol                            Meaning
  2670.  ────────────────────────────────────────────────────────────────────────────
  2671. 
  2672.  
  2673.  
  2674.  For a few more variations on LIKE and the wildcard characters, see the SQL
  2675.  Server Language Reference.
  2676.  
  2677.  
  2678.  Character Strings and Quotes
  2679.  
  2680.  Character and date data (char, varchar, and datetime datatypes) must be
  2681.  enclosed in single or double quotation marks when you enter or search for
  2682.  them.
  2683.  
  2684.  There are two ways to specify literal quotation marks within a character
  2685.  entry. The first method is to use two consecutive quotation marks. For
  2686.  example, if you have begun a character entry with a single quotation mark
  2687.  and wish to include a single quotation mark as part of the entry, use two
  2688.  single quotation marks:
  2689.  
  2690.    'I don"t understand.'
  2691.  
  2692.  With double quotation marks:
  2693.  
  2694.    "He said, ""It's not really confusing."""
  2695.  
  2696.  The second method is to enclose a quote in the other kind of quotation mark.
  2697.  In other words, surround an entry containing double quotation marks with
  2698.  single quotation marks (or vice versa). Here are some examples:
  2699.  
  2700.    'George said, "There must be a better way."'
  2701.     "Isn't there a better way?"
  2702.     'George asked, "Isn"t there a better way?"'
  2703.  
  2704.  To continue a character string that would go off the end of one line on your
  2705.  screen, enter a backslash (\) before going to the following line.
  2706.  
  2707.  
  2708.  Unknown Values: IS NULL and IS NOT NULL
  2709.  
  2710.  When you see NULL in a column, it means that the user or application has
  2711.  made no entry in that column. A data value for the column is "unknown" or
  2712.  "not available."
  2713.  
  2714.  NULL is not synonymous with zero (numerical values) or blank (character
  2715.  values). Rather, null values allow you to distinguish between a deliberate
  2716.  entry of zero (for numeric columns) or blank (for character columns) and a
  2717.  non-entry (NULL for both numeric and character columns).
  2718.  
  2719.  NULL can be entered in a column for which null values are permitted (as
  2720.  specified in the CREATE TABLE statement) in two ways. If no data is entered,
  2721.  SQL Server automatically enters the value NULL. The user can explicitly
  2722.  enter the value NULL by typing the word NULL or null without single or
  2723.  double quotation marks.
  2724.  
  2725.  If the word NULL is typed into a character column with single or double
  2726.  quotation marks, it is treated as data, not as a null value.
  2727.  
  2728.  When null values are retrieved, displays of query results show the word NULL
  2729.  in the appropriate position. For example, the advance column of the titles
  2730.  table allows null values. By inspecting the data in that column, you can
  2731.  tell whether a book had no advance payment by agreement (zero in the advance
  2732.  column, probably due to poor negotiating skills on the author's part, as in
  2733.  the row for MC2222) or whether the advance amount was not known when the
  2734.  data was entered (NULL in the advance column, as in the row for MC3026).
  2735.  
  2736. ╓┌───────┌──────────────────────────────────────────────────┌───────────┌────
  2737.  ────────────────────────────────────────────────────────────────────────────
  2738.          select title_id, type, advance
  2739.  
  2740.          from titles
  2741.  
  2742.          where pub_id = "0877"
  2743.  
  2744.          title_id                                           type        advanc
  2745.  
  2746.          --------                                           ----------  ------
  2747.  
  2748.          MC2222                                             mod_cook    0.00
  2749.  
  2750.          MC3021                                             mod_cook    15,000
  2751.  
  2752.          MC3026                                             UNDECIDED   NULL
  2753.  ────────────────────────────────────────────────────────────────────────────
  2754.         MC3026                                             UNDECIDED   NULL
  2755.  
  2756.          PS1372                                             psychology  7,000.
  2757.  
  2758.          TC3218                                             trad_cook   7,000.
  2759.  
  2760.          TC4203                                             trad_cook   4,000.
  2761.  
  2762.          TC7777                                             trad_cook   8,000.
  2763.  
  2764.          (7 rows affected)
  2765.  
  2766.  
  2767.  
  2768.  When you compare a null value with another value, the result is never true;
  2769.  a null value does not match anything, not even another null value. So, for
  2770.  example, "ytd_sales > null" is false and will never return any results.
  2771.  
  2772.  Null values do not match each other because there is no reason to assume
  2773.  that two unknown values would be the same. So null values never join, not
  2774.  even to other null values. (See Chapter 3, "Joining Two or More Tables.")
  2775.  
  2776.  However, null values are not considered different for the purposes of the
  2777.  DISTINCT keyword.
  2778.  
  2779.  Computations involving NULL evaluate to NULL because the result must be
  2780.  unknown if any of the factors is unknown. For example, 1 + column1 evaluates
  2781.  to NULL if column1 is NULL.
  2782.  
  2783.  You can find null values (or non-null values when the columns being searched
  2784.  are defined as allowing null values) in the database with this pattern:
  2785.  
  2786.    WHERE column_name IS [NOT] NULL
  2787.  
  2788.  If you try to find null values in columns defined as NOT NULL, SQL Server
  2789.  displays an error message.
  2790.  
  2791.  Some of the rows in the titles table contain incomplete data. For example, a
  2792.  book called The Psychology of Computer Cooking has been proposed and its
  2793.  title, title identification number, and probable publisher entered. However,
  2794.  since the author has no contract as yet and details are still up in the air,
  2795.  null values appear in the price, advance, royalty, ytd_sales, and notes
  2796.  columns.
  2797.  
  2798.  Because null values don't match anything in a comparison, a query for all
  2799.  the title identification numbers and advances for books with moderate
  2800.  advances (under $5,000) will not find the row for The Psychology of Computer
  2801.  Cooking, title identification number MC3026.
  2802.  
  2803. ╓┌───────┌──────────────────────────────────────────────────────────────┌────
  2804.  ────────────────────────────────────────────────────────────────────────────
  2805.          select title_id, advance
  2806.  
  2807.          from titles
  2808.  
  2809.          where advance < $5000
  2810.  
  2811.          title_id                                                       advanc
  2812.  
  2813.          --------                                                       ------
  2814.  
  2815.          MC2222                                                         0.00
  2816.  ────────────────────────────────────────────────────────────────────────────
  2817.         MC2222                                                         0.00
  2818.  
  2819.          PS2091                                                         2,275.
  2820.  
  2821.          PS3333                                                         2,000.
  2822.  
  2823.          PS7777                                                         4,000.
  2824.  
  2825.          TC4203                                                         4,000.
  2826.  
  2827.          (5 rows affected)
  2828.  
  2829.  
  2830.  
  2831.  Here's how a query for books with an advance under $5000 or a null value in
  2832.  the advance column would look:
  2833.  
  2834. ╓┌───────┌──────────────────────────────────────────────────────────────┌────
  2835.  ────────────────────────────────────────────────────────────────────────────
  2836.          select title_id, advance
  2837.  ────────────────────────────────────────────────────────────────────────────
  2838.          select title_id, advance
  2839.  
  2840.          from titles
  2841.  
  2842.          where advance < $5000
  2843.  
  2844.          or advance is null
  2845.  
  2846.          title_id                                                       advanc
  2847.  
  2848.          --------                                                       ------
  2849.  
  2850.          MC2222                                                         0.00
  2851.  
  2852.          MC3026                                                         NULL
  2853.  
  2854.          PC9999                                                         NULL
  2855.  
  2856.          PS2091                                                         2,275.
  2857.  
  2858.  ────────────────────────────────────────────────────────────────────────────
  2859. 
  2860.          PS3333                                                         2,000.
  2861.  
  2862.          PS7777                                                         4,000.
  2863.  
  2864.          TC4203                                                         4,000.
  2865.  
  2866.          (7 rows affected)
  2867.  
  2868.  
  2869.  
  2870.  (See Chapter 7, "Creating Databases, Tables, and Indexes," for information
  2871.  on NULL in the CREATE TABLE statement and for information on the
  2872.  relationship between NULL and defaults. See Chapter 9, "Adding, Changing,
  2873.  and Removing Data," for information on inserting null values into a table.
  2874.  See the SQL Server Language Reference for more information.)
  2875.  
  2876.  
  2877.  Connecting Conditions with Logical Operators
  2878.  
  2879.  The logical operators AND, OR, and NOT are used to connect search conditions
  2880.  in WHERE clauses.
  2881.  
  2882.  AND joins two or more conditions and returns results only when all of the
  2883.  conditions are true. For example, the following query finds only the rows in
  2884.  which the author's last name is Ringer and the author's first name is Anne.
  2885.  It will not find the row for Albert Ringer.
  2886.  
  2887.    select *
  2888.     from authors
  2889.     where au_lname = 'Ringer' and au_fname = 'Anne'
  2890.  
  2891.  OR also connects two or more conditions, but it returns results when any of
  2892.  the conditions is true. The following query searches for rows containing
  2893.  Anne or Ann in the au_fname column.
  2894.  
  2895.    select *
  2896.     from authors
  2897.     where au_fname = 'Anne' or au_fname = 'Ann'
  2898.  
  2899.  NOT negates the expression that follows it. The following query selects all
  2900.  the authors who do not live in California:
  2901.  
  2902.    select * from authors
  2903.     where not state = "CA"
  2904.  
  2905.  
  2906.  Logical Operator Precedence
  2907.  
  2908.  Arithmetic (and bitwise) operators are handled before logical operators.
  2909.  When more than one logical operator is used in a statement, NOT is evaluated
  2910.  first, then AND, and finally OR. See the SQL Server Language Reference for
  2911.  information on bitwise operators.
  2912.  
  2913.  For example, the following query finds all the business books in the titles
  2914.  table, no matter what their advances are, as well as all psychology books
  2915.  that have an advance greater than $5,500. The advance condition pertains to
  2916.  psychology books and not to business books because the AND is handled before
  2917.  the OR.
  2918.  
  2919. ╓┌───────┌──────────────────────────────────────────────────┌───────────┌────
  2920.  ────────────────────────────────────────────────────────────────────────────
  2921.  ────────────────────────────────────────────────────────────────────────────
  2922.          select title_id, type, advance
  2923.  
  2924.          from titles
  2925.  
  2926.          where type = "business" or type = "psychology"
  2927.  
  2928.          and advance >5500
  2929.  
  2930.          title_id                                           type        advanc
  2931.  
  2932.          --------                                           ----------  ------
  2933.  
  2934.          BU1032                                             business    5,000.
  2935.  
  2936.          BU1111                                             business    5,000.
  2937.  
  2938.          BU2075                                             business    10,125
  2939.  
  2940.          BU7832                                             business    5,000.
  2941.  
  2942.  ────────────────────────────────────────────────────────────────────────────
  2943. 
  2944.          PS1372                                             psychology  7,000.
  2945.  
  2946.          PS2106                                             psychology  6,000.
  2947.  
  2948.          (6 rows affected)
  2949.  
  2950.  
  2951.  
  2952.  You can change the meaning of the query by adding parentheses to force
  2953.  evaluation of the OR first. This query finds all business and psychology
  2954.  books that have advances over $5,500:
  2955.  
  2956. ╓┌───────┌──────────────────────────────────────────────────┌───────────┌────
  2957.  ────────────────────────────────────────────────────────────────────────────
  2958.          select title_id, type, advance
  2959.  
  2960.          from titles
  2961.  
  2962.          where (type = "business" or type = "psychology")
  2963.  ────────────────────────────────────────────────────────────────────────────
  2964.         where (type = "business" or type = "psychology")
  2965.  
  2966.          and advance >5500
  2967.  
  2968.          title_id                                           type        advanc
  2969.  
  2970.          --------                                           ----------  ------
  2971.  
  2972.          BU2075                                             business    10,125
  2973.  
  2974.          PS1372                                             psychology  7,000.
  2975.  
  2976.          PS2106                                             psychology  6,000.
  2977.  
  2978.          (3 rows affected)
  2979.  
  2980.  
  2981.  
  2982.  
  2983.  Creating a New Table for Results: SELECT INTO
  2984.  
  2985.  The SELECT INTO clause selects into a permanent table only if the select
  2986.  into/bulkcopy database option is set. To see whether this option is set,
  2987.  execute the sp_helpdb system procedure. Here's what the command and its
  2988.  results look like if the option is set:
  2989.  
  2990.    sp_helpdb pubs
  2991.  
  2992.     name  db_size  owner  dbid created    status
  2993.     ----  -------  -----  ---- ----------   --------------
  2994.     pubs  2 MB  sa   5   Jun 3 1988   no options set
  2995.  
  2996.      (1 row affected)
  2997.  
  2998.  
  2999.     device    size    usage
  3000.     ---------   -------    ------------
  3001.     master    2 MB    data and log
  3002.  
  3003.     (1 row affected)
  3004.  
  3005.  If the option is not set, the report from sp_helpdb will indicate this. Only
  3006.  the System Administrator or the Database Owner can set the database options.
  3007.  
  3008.  
  3009.  If the select into/bulkcopy database option is set, you can use the SELECT
  3010.  INTO clause to build a new permanent table without using a CREATE TABLE
  3011.  statement. (You can select into a temporary table even if the option is not
  3012.  set.) Unlike a view that displays a portion of a table, a table created with
  3013.  SELECT INTO is a separate, independent entity. (See Chapter 10, "Creating
  3014.  Views," for details on views.)
  3015.  
  3016.  The new table is based on the columns you specify in the select list, the
  3017.  table(s) you name in the FROM clause, and the rows you choose in the WHERE
  3018.  clause. The name of the new table must be unique in the database and must
  3019.  conform to the rules for identifiers.
  3020.  
  3021.  A SELECT statement with an INTO clause allows you to define a table and put
  3022.  data into it (based on existing definitions and data) without going through
  3023.  the usual data definition process.
  3024.  
  3025.  The following example shows a SELECT INTO statement and its results. A table
  3026.  called newtable is created, using two of the columns in the 4-column table
  3027.  publishers. Because this particular statement includes no WHERE clause, data
  3028.  from all of the rows (but only two of the columns) of publishers is copied
  3029.  into newtable.
  3030.  
  3031.    select pub_id, pub_name
  3032.     into newtable
  3033.     from publishers
  3034.  
  3035.     (4 rows affected)
  3036.  
  3037.  SQL Server's message "(4 rows affected)" refers to the row created in the
  3038.  system table sysobjects for the new table, newtable, plus the three rows
  3039.  inserted into newtable. Here's what newtable looks like:
  3040.  
  3041.    select *
  3042.     from newtable
  3043.  
  3044.     pub_id  pub_name
  3045.     ------  --------------------
  3046.     0736  New Age Books
  3047.     0877  Binnet & Hardley
  3048.     1389  Algodata Infosystems
  3049.  
  3050.     (3 rows affected)
  3051.  
  3052.  The new table contains the results of the SELECT statement. It becomes part
  3053.  of the database, just like its parent table.
  3054.  
  3055.  The INTO clause is useful for creating test tables, new tables as copies of
  3056.  existing tables, and for making several smaller tables out of one large
  3057.  table.
  3058.  
  3059.  You can also use SELECT INTO to create a skeleton table with no data by
  3060.  putting a false condition in the WHERE clause. For example:
  3061.  
  3062.    select *
  3063.     into newtable2
  3064.     from publishers
  3065.     where 1=2
  3066.  
  3067.     (0 rows affected)
  3068.  
  3069.  
  3070.     select *
  3071.     from newtable2
  3072.  
  3073.     pub_id  pub_name  city  state
  3074.     ------  --------  ----  -----
  3075.  
  3076.     (0 rows affected)
  3077.  
  3078.  No rows are inserted into the new table because 1 never equals 2.
  3079.  
  3080.  
  3081.  Grouping Data: GROUP BY and HAVING Clauses
  3082.  
  3083.  This section provides an overview of GROUP BY, HAVING, and the aggregate
  3084.  functions. (See Chapter 4, "Displaying Totals: GROUP BY and COMPUTE," for a
  3085.  detailed description of these topics.)
  3086.  
  3087.  Generally, GROUP BY organizes data into groups; HAVING sets conditions on
  3088.  which groups to include in the results. (HAVING is almost never used by
  3089.  itself.)
  3090.  
  3091.  Aggregate functions return summary values, either for the whole table or for
  3092.  groups within the table. For this reason they work well with GROUP BY.
  3093.  Aggregate functions can appear in a select list or a HAVING clause, but not
  3094.  in a WHERE clause.
  3095.  
  3096.  
  3097.  You can use these aggregate functions with GROUP BY (expression is almost
  3098.  always a column name):
  3099.  
  3100. ╓┌─────────────────────────────────┌─────────────────────────────────────────
  3101.  Aggregate Function                Result
  3102.  ────────────────────────────────────────────────────────────────────────────
  3103.  SUM([DISTINCT] expression)        Total of the [distinct] values in the
  3104.                                    numeric column
  3105.  
  3106.  AVG([DISTINCT] expression)        Average of the [distinct] values in the
  3107.                                    numeric column
  3108.  
  3109.  COUNT([DISTINCT] expression)      Number of [distinct] non-null values in
  3110.  Aggregate Function                Result
  3111.  ────────────────────────────────────────────────────────────────────────────
  3112. COUNT([DISTINCT] expression)      Number of [distinct] non-null values in
  3113.                                    the column
  3114.  
  3115.  COUNT(*)                          Number of selected rows
  3116.  
  3117.  MAX(expression)                   Highest value in the expression
  3118.  
  3119.  MIN(expression)                   Lowest value in the expression
  3120.  
  3121.  ────────────────────────────────────────────────────────────────────────────
  3122.  
  3123.  
  3124.  
  3125.  SUM and AVG work only with numeric values. SUM, AVG, COUNT, MAX, and MIN
  3126.  ignore null values, but COUNT(*) does not.
  3127.  
  3128.  The following query finds the total year-to-date sales of each publisher in
  3129.  the database:
  3130.  
  3131. ╓┌─────────────────────────────────┌─────────────────────────────────────────
  3132.  ────────────────────────────────────────────────────────────────────────────
  3133.                                    select pub_id, total = sum(ytd_sales)
  3134.  
  3135.                                    from titles
  3136.  
  3137.                                    group by pub_id
  3138.  
  3139.  
  3140.  
  3141. ╓┌───────┌──────────────────┌────────────────────────────────────────────────╖
  3142.  ────────────────────────────────────────────────────────────────────────────
  3143.          pub_id             total
  3144.  
  3145.          ------             ------
  3146.  
  3147.          0736               28286
  3148.  
  3149.          0877               44219
  3150.  
  3151.          1389               24941
  3152.  ────────────────────────────────────────────────────────────────────────────
  3153.         1389               24941
  3154.  
  3155.          (3 rows affected)
  3156.  
  3157.  
  3158.  
  3159.  Because of the GROUP BY clause, only one row is returned for each publisher,
  3160.  and it contains the sum of all sales for that publisher.
  3161.  
  3162.  The HAVING clause sets conditions on the GROUP BY clause, similar to the way
  3163.  the WHERE clause interacts with the SELECT clause. The HAVING clause syntax
  3164.  is exactly like the WHERE clause syntax except that the HAVING clause can
  3165.  contain aggregate functions and the WHERE clause cannot.
  3166.  
  3167.  If, for example, you want to make sure that there are more than five books
  3168.  involved in the calculations for each publisher, use HAVING COUNT(*)>5 to
  3169.  eliminate any publishers that are returning totals for fewer than six books.
  3170.  The query looks like this:
  3171.  
  3172.    select pub_id, total = sum(ytd_sales)
  3173.     from titles
  3174.     group by pub_id
  3175.     having count(*)>5
  3176.  
  3177.     pub_id  total
  3178.     ------  -----
  3179.     0877  44219
  3180.     1389  24941
  3181.  
  3182.     (2 rows affected)
  3183.  
  3184.  With this statement, two rows are returned. New Age Books (0736) is
  3185.  eliminated.
  3186.  
  3187.  
  3188.  Sorting Query Results: ORDER BY
  3189.  
  3190.  The ORDER BY clause sorts query results by one or more columns. You can sort
  3191.  up to 16 columns. Each sort can be either ascending (ASC) or descending
  3192.  (DESC). If neither is specified, ASC is assumed. The following query returns
  3193.  results ordered by pub_id:
  3194.  
  3195.    select pub_id, type, title_id
  3196.     from titles
  3197.     order by pub_id
  3198.  
  3199.     pub_id  type    title_id
  3200.     ------  ------------  --------
  3201.     0736  business   BU2075
  3202.     0736  psychology   PS2091
  3203.     0736  psychology   PS2106
  3204.     0736  psychology   PS3333
  3205.     0736  psychology   PS7777
  3206.     0877  UNDECIDED   MC3026
  3207.     0877  mod_cook   MC2222
  3208.     0877  mod_cook   MC3021
  3209.     0877  psychology   PS1372
  3210.     0877  trad_cook   TC3218
  3211.     0877  trad_cook   TC4203
  3212.     0877  trad_cook   TC7777
  3213.     1389  business   BU1032
  3214.     1389  business   BU1111
  3215.     1389  business   BU7832
  3216.     1389  popular_comp  PC1035
  3217.     1389  popular_comp  PC8888
  3218.     1389  popular_comp  PC9999
  3219.  
  3220.     (18 rows affected)
  3221.  
  3222.  If more than one column is named in the ORDER BY clause, sorts are nested.
  3223.  The following statement sorts the rows in the titles table first by
  3224.  publisher in descending order, then by type (ascending) within each
  3225.  publisher, and finally by title number (also ascending, since DESC is not
  3226.  specified). Null values are sorted first within any group.
  3227.  
  3228.    select pub_id, type, title_id
  3229.     from titles
  3230.     order by pub_id desc, type, title_id
  3231.  
  3232.     pub_id  type    title_id
  3233.     ------  ------------  --------
  3234.     1389  business   BU1032
  3235.     1389  business   BU1111
  3236.     1389  business   BU7832
  3237.     1389  popular_comp  PC1035
  3238.     1389  popular_comp  PC8888
  3239.     1389  popular_comp  PC9999
  3240.     0877  UNDECIDED   MC3026
  3241.     0877  mod_cook   MC2222
  3242.     0877  mod_cook   MC3021
  3243.     0877  psychology   PS1372
  3244.     0877  trad_cook   TC3218
  3245.     0877  trad_cook   TC4203
  3246.     0877  trad_cook   TC7777
  3247.     0736  business   BU2075
  3248.     0736  psychology   PS2091
  3249.     0736  psychology   PS2106
  3250.     0736  psychology   PS3333
  3251.     0736  psychology   PS7777
  3252.  
  3253.     (18 rows affected)
  3254.  
  3255.  The positional number of a column in a select list can be used instead of
  3256.  the column name. Column names and select list numbers can be mixed. Both of
  3257.  the following statements produce the same results as the preceding one:
  3258.  
  3259.    select pub_id, type, title_id
  3260.     from titles
  3261.     order by 1 desc, 2, 3
  3262.  
  3263.     select pub_id, type, title_id
  3264.     from titles
  3265.     order by 1 desc, type, 3
  3266.  
  3267.  Most versions of SQL require that ORDER BY items appear in the select list,
  3268.  but TRANSACT-SQL has no such restriction. You can order the results of the
  3269.  preceding query by title, although that column does not appear in the select
  3270.  list.
  3271.  
  3272.  
  3273.  Generating Summary Rows: COMPUTE BY
  3274.  
  3275.  Use COMPUTE BY with row aggregate functions to produce reports that
  3276.  summarize values whenever the value in a specified column changes. Such
  3277.  reports (usually produced by a report generator) are called control-break
  3278.  reports since summary values appear in the report under the control of the
  3279.  groupings ("breaks") you specify in the COMPUTE BY clause.
  3280.  
  3281.  These summary values appear as additional rows in the query results, unlike
  3282.  the aggregate function results of a GROUP BY clause, which appear as new
  3283.  columns.
  3284.  
  3285.  A COMPUTE BY clause allows you to see detail and summary rows with one
  3286.  SELECT statement. You can calculate summary values for subgroups and you can
  3287.  calculate more than one row aggregate function for the same group.
  3288.  
  3289.  The COMPUTE BY clause has the following syntax:
  3290.  
  3291.    COMPUTE row_aggregate(column_name)
  3292.     [, row_aggregate(column_name)...]
  3293.     [BY column_name [, column_name...]]
  3294.  
  3295.  The row aggregate functions you can use with COMPUTE BY are SUM, AVG, MIN,
  3296.  MAX, and COUNT. SUM and AVG are used with numeric columns only.
  3297.  
  3298.  Following are two queries and their results. The first one uses GROUP BY and
  3299.  aggregate functions. The second uses COMPUTE BY and row aggregate functions.
  3300.  Notice the difference in the displays.
  3301.  
  3302. ╓┌───────┌────────────────────────────────────────────────┌────────────┌─────
  3303.  ────────────────────────────────────────────────────────────────────────────
  3304.          select type, sum(price), sum(advance)
  3305.  
  3306.          from titles
  3307.  
  3308.          group by type
  3309.  
  3310.          type
  3311.  
  3312.          ------------                                     -----        -------
  3313.  
  3314.          UNDECIDED                                        NULL         NULL
  3315.  
  3316.          business                                         54.92        25,125.
  3317.  
  3318.          mod_cook                                         22.98        15,000.
  3319.  
  3320.  ────────────────────────────────────────────────────────────────────────────
  3321. 
  3322.          popular_comp                                     42.95        15,000.
  3323.  
  3324.          psychology                                       67.52        21,275.
  3325.  
  3326.          trad_cook                                        47.89        19,000.
  3327.  
  3328.          (6 rows affected)
  3329.  
  3330.          select type, price, advance
  3331.  
  3332.          from titles
  3333.  
  3334.          order by type
  3335.  
  3336.          compute sum(price), sum(advance) by type
  3337.  
  3338.          type                                             price        advance
  3339.  
  3340.          ------------                                     -----------  -------
  3341.  ────────────────────────────────────────────────────────────────────────────
  3342.         ------------                                     -----------  -------
  3343.  
  3344.          UNDECIDED                                        NULL         NULL
  3345.  
  3346.                                                           sum          sum
  3347.  
  3348.                                                           -----------  -------
  3349.  
  3350.                                                           NULL         NULL
  3351.  
  3352.          type                                             price        advance
  3353.  
  3354.          --------                                         -----------  -------
  3355.  
  3356.          business                                         2.99         10,125.
  3357.  
  3358.          business                                         11.95        5,000.0
  3359.  
  3360.          business                                         19.99        5,000.0
  3361.  
  3362.  ────────────────────────────────────────────────────────────────────────────
  3363. 
  3364.          business                                         19.99        5,000.0
  3365.  
  3366.                                                           sum          sum
  3367.  
  3368.                                                           -----------  -------
  3369.  
  3370.                                                           54.92        25,125.
  3371.  
  3372.          type                                             price        advance
  3373.  
  3374.          --------                                         -----------  -------
  3375.  
  3376.          mod_cook                                         2.99         15,000.
  3377.  
  3378.          mod_cook                                         19.99        0.00
  3379.  
  3380.                                                           sum          sum
  3381.  
  3382.                                                           -----------  -------
  3383.  ────────────────────────────────────────────────────────────────────────────
  3384.                                                          -----------  -------
  3385.  
  3386.                                                           22.98        15,000.
  3387.  
  3388.          type                                             price        advance
  3389.  
  3390.          ------------                                     -----------  -------
  3391.  
  3392.          popular_comp                                     NULL         NULL
  3393.  
  3394.          popular_comp                                     20.00        8,000.0
  3395.  
  3396.          popular_comp                                     22.95        7,000.0
  3397.  
  3398.                                                           sum          sum
  3399.  
  3400.                                                           -----------  -------
  3401.  
  3402.                                                           42.95        15,000.
  3403.  
  3404.  ────────────────────────────────────────────────────────────────────────────
  3405. 
  3406.          type                                             price        advance
  3407.  
  3408.          ----------                                       -----------  -------
  3409.  
  3410.          psychology                                       7.00         6,000.0
  3411.  
  3412.          psychology                                       7.99         4,000.0
  3413.  
  3414.          psychology                                       10.95        2,275.0
  3415.  
  3416.          psychology                                       19.99        2,000.0
  3417.  
  3418.          psychology                                       21.59        7,000.0
  3419.  
  3420.                                                           sum          sum
  3421.  
  3422.                                                           -----------  -------
  3423.  
  3424.                                                           67.52        21,275.
  3425.  ────────────────────────────────────────────────────────────────────────────
  3426.                                                          67.52        21,275.
  3427.  
  3428.          type                                             price        advance
  3429.  
  3430.          ---------                                        -----------  -------
  3431.  
  3432.          trad_cook                                        11.95        4,000.0
  3433.  
  3434.          trad_cook                                        14.99        8,000.0
  3435.  
  3436.          trad_cook                                        20.95        7,000.0
  3437.  
  3438.                                                           sum          sum
  3439.  
  3440.                                                           -----------  -------
  3441.  
  3442.                                                           47.89        19,000.
  3443.  
  3444.          (24 rows affected)
  3445.  
  3446.  ────────────────────────────────────────────────────────────────────────────
  3447. 
  3448.  
  3449.  
  3450.  The summary values are treated as new rows, which is why SQL Server's
  3451.  message says "(24 rows affected)." (See Chapter 4, "Displaying Totals: GROUP
  3452.  BY and COMPUTE," for a fuller explanation, rules, and more examples of the
  3453.  COMPUTE clause.)
  3454.  
  3455.  
  3456.  
  3457.  
  3458.  
  3459.  
  3460.  Chapter 3  Joining Two or More Tables
  3461.  ────────────────────────────────────────────────────────────────────────────
  3462.  
  3463.  
  3464.  Introduction
  3465.  
  3466.  This chapter describes retrieval operations that involve data from two or
  3467.  more tables. These tables can be in the same database or in different
  3468.  databases.
  3469.  
  3470.  The multi-table operation discussed in this chapter is the join. Subqueries
  3471.  (queries nested within other queries), which also can involve two or more
  3472.  tables, are covered in Chapter 6, "Building Subqueries." Many joins can be
  3473.  stated as subqueries.
  3474.  
  3475.  
  3476.  The Join Operation
  3477.  
  3478.  Joining two or more tables is a process of comparing the data in specified
  3479.  fields and using the comparison results to form a new table from the rows
  3480.  that qualify. Specifically, a join statement does the following:
  3481.  
  3482.  
  3483.    ■   Specifies a column from each table
  3484.  
  3485.    ■   Compares the values in those columns row by row
  3486.  
  3487.    ■   Combines rows with qualifying values into new rows
  3488.  
  3489.  
  3490.  The comparison is usually for equality─values that match exactly─but other
  3491.  types of joins can be specified. If a join is to have meaningful results,
  3492.  the columns being compared must have similar values─values drawn from the
  3493.  same domain.
  3494.  
  3495.  There are several varieties of joins─equijoins, natural joins, outer joins,
  3496.  and so on.
  3497.  
  3498.  The most common variety is the join based on equality. Here is an example of
  3499.  a join that finds the names of authors and publishers located in the same
  3500.  city:
  3501.  
  3502.    select au_fname, au_lname, pub_name
  3503.     from authors, publishers
  3504.     where authors.city = publishers.city
  3505.  
  3506.     au_fname  au_lname  pub_name
  3507.     --------  -------   --------------------
  3508.     Cheryl   Carson   Algodata Infosystems
  3509.     Abraham   Bennet   Algodata Infosystems
  3510.  
  3511.     (2 rows affected)
  3512.  
  3513.  Since the query draws on information contained in two separate tables,
  3514.  publishers and authors, a join is required to retrieve the requested
  3515.  information.
  3516.  
  3517.  
  3518.  The Select List
  3519.  
  3520.  A join statement, like a selection statement, starts with the keyword
  3521.  SELECT. The columns named after the SELECT keyword are the columns to be
  3522.  included in the query results, in their desired order. The previous example
  3523.  specified the columns that contained the authors' and publishers' names.
  3524.  
  3525.  In the preceding example, the columns au_fname, au_lname, and pub_name did
  3526.  not have to be qualified by a table name since there is no ambiguity about
  3527.  the table to which they belong. But the city column used for the join
  3528.  comparison did have to be qualified since there are columns of that name in
  3529.  both the publishers and authors tables. Though in this example neither of
  3530.  the city columns is printed in the results, SQL Server needs the table name
  3531.  to perform the comparison.
  3532.  
  3533.  As in a SELECT statement, you can use the "*" to specify that all the
  3534.  columns of the tables involved in the query be included in the results. For
  3535.  example, to include all the columns in publishers and authors in the
  3536.  preceding join query, the SQL statement is as follows:
  3537.  
  3538.    select *
  3539.     from authors, publishers
  3540.     where authors.city = publishers.city
  3541.  
  3542.     au_id   au_lname  au_fname
  3543.      phone      address
  3544.      city      state zip  contract pub_id
  3545.      pub_name     city   state
  3546.     -----------  ---------  ---------
  3547.      ------------     ----------------
  3548.      --------     ----- ----- -------- ------
  3549.      --------------------  --------  -----
  3550.     238-95-7766  Carson   Cheryl
  3551.      415 548-7723     589 Darwin Ln.
  3552.      Berkeley     CA  94705 1    1389
  3553.      Algodata Infosystems  Berkeley  CA
  3554.  
  3555.  
  3556.    409-56-7008  Bennet   Abraham
  3557.      415 658-9932    6223 Bateman St.
  3558.      Berkeley     CA  94705 1   1389
  3559.      Algodata Infosystems  Berkeley  CA
  3560.  
  3561.     (2 rows affected)
  3562.  
  3563.  The display shows a total of 2 rows with 13 columns each. Because of the
  3564.  length of the rows, each takes up multiple horizontal lines in this display.
  3565.  
  3566.  
  3567.  Whenever "*" is used, the columns in the results are displayed in their
  3568.  order in the CREATE statement for the table. (See Chapter 7, "Creating
  3569.  Databases, Tables, and Indexes," for details.)
  3570.  
  3571.  The select list (and the results) of a join need not include columns from
  3572.  both of the tables being joined. For example, to find the names of the
  3573.  authors that live in the same city as one of the publishers, your query need
  3574.  not include any columns from publishers:
  3575.  
  3576.    select au_lname, au_fname
  3577.     from authors, publishers
  3578.     where authors.city = publishers.city
  3579.  
  3580.  Remember, just as in any SELECT statement, column names in the select list
  3581.  (and table names in the FROM clause) must be separated by commas.
  3582.  
  3583.  
  3584.  The FROM Clause
  3585.  
  3586.  The FROM clause of a join statement names all the tables (or views) involved
  3587.  in the join. This is actually the clause that indicates to SQL Server that a
  3588.  join is desired. The order in which the tables (or views) are listed is not
  3589.  important.
  3590.  
  3591.  More than two tables or views can be named in the FROM clause. Joins
  3592.  involving more than two tables or views are discussed later in this chapter.
  3593.  
  3594.  
  3595.  As explained in Chapter 2, "Querying Databases," table or view names can be
  3596.  qualified by the names of the owner and database, and can be given alias
  3597.  names for convenience.
  3598.  
  3599.  Views can be joined in exactly the same way as tables and used wherever
  3600.  tables are used. Chapter 10, "Creating Views," discusses views; this chapter
  3601.  uses only tables in its examples.
  3602.  
  3603.  
  3604.  The WHERE Clause
  3605.  
  3606.  The WHERE clause specifies the connection between the tables named in the
  3607.  FROM clause, restricting the rows to be included in the results. It gives
  3608.  the names of the columns to be joined (qualified by table names if
  3609.  necessary) and the join operator─often equality, sometimes "greater than" or
  3610.  "less than." (For details of WHERE clause syntax, see Chapter 2, "Querying
  3611.  Databases," or the SQL Server Language Reference.)
  3612.  
  3613.  Joins that match columns on the basis of equality are called equijoins. A
  3614.  more precise definition of an equijoin is given later in this chapter, along
  3615.  with examples of joins not based on equality.
  3616.  
  3617.  Use the following relational operators to determine the basis on which
  3618.  columns will be matched:
  3619.  
  3620. ╓┌─────────────────────────────────┌─────────────────────────────────────────╖
  3621.  Symbol                            Meaning
  3622.  ────────────────────────────────────────────────────────────────────────────
  3623.  =                                 equal to
  3624.  
  3625.  >                                 greater than
  3626.  
  3627.  >=                                greater than or equal to
  3628.  
  3629.  <                                 less than
  3630.  
  3631.  <=                                less than or equal to
  3632.  
  3633.  !=                                not equal to
  3634.  
  3635.  Symbol                            Meaning
  3636.  ────────────────────────────────────────────────────────────────────────────
  3637. 
  3638.  !>                                not greater than
  3639.  
  3640.  !<                                not less than
  3641.  
  3642.  ────────────────────────────────────────────────────────────────────────────
  3643.  
  3644.  
  3645.  
  3646.  Joins that use the relational operators are collectively called theta joins.
  3647.  Another set of join operators is used for outer joins, also discussed in
  3648.  detail later in this chapter. The outer join operators are *=, which
  3649.  includes in the results all the rows from the first table, not just the ones
  3650.  in which the joined columns match, and =*, which includes in the results all
  3651.  the rows from the second table, not just the ones in which the joined
  3652.  columns match.
  3653.  
  3654.  Columns being joined do not need to have the same name, though they often
  3655.  will, or be the same datatype. (See Chapter 7, "Creating Databases, Tables,
  3656.  and Indexes.")
  3657.  
  3658.  However, if the datatypes are not identical, they must be compatible─types
  3659.  that SQL Server automatically converts. For example, SQL Server
  3660.  automatically converts among any of the numeric type columns─int, smallint,
  3661.  tinyint, decimal, or float, and among any of the character type and date
  3662.  columns─char, varchar, and datetime. (For details on datatype conversion,
  3663.  see Chapter 5, "Using Built-In Functions," or the SQL Server Language
  3664.  Reference.)
  3665.  
  3666.  ────────────────────────────────────────────────────────────────────────────
  3667.  NOTE
  3668.  Tables cannot be joined in text or image columns.
  3669.  ────────────────────────────────────────────────────────────────────────────
  3670.  
  3671.  The WHERE clause of a join statement can include other conditions in
  3672.  addition to the one that links columns from different tables. In other
  3673.  words, you can include a join operation and a select operation in the same
  3674.  SQL statement. An example is given later in this chapter.
  3675.  
  3676.  ────────────────────────────────────────────────────────────────────────────
  3677.  WARNING
  3678.  
  3679.  You will get unexpected results if you leave off the WHERE clause of a join.
  3680.  Without a WHERE clause, any of the join queries discussed so far will
  3681.  produce 69 rows instead of 2! This situation is explained later in the
  3682.  section "How Joins Are Processed."
  3683.  ────────────────────────────────────────────────────────────────────────────
  3684.  
  3685.  
  3686.  Joins and the Relational Model
  3687.  
  3688.  The join operation is the hallmark of the relational model of database
  3689.  management. More than any other feature, the join distinguishes relational
  3690.  database management systems from other types of database management systems.
  3691.  
  3692.  
  3693.  In structured database management systems (often known as network and
  3694.  hierarchical systems), relationships between data values are predefined.
  3695.  Once a database has been set up, it's difficult to make queries about
  3696.  unanticipated relationships among the data.
  3697.  
  3698.  On the other hand, in a relational database management system, relationships
  3699.  among data values are left unstated in the definition of a database. They
  3700.  become explicit when the data is manipulated─when you query the database,
  3701.  not when you create it. You can ask any question that comes to mind about
  3702.  the data stored in the database, regardless of what was intended when the
  3703.  database was set up.
  3704.  
  3705.  According to the rules of good database design (called normalization rules),
  3706.  each table should describe one kind of entity─a person, place, event, or
  3707.  thing. When you want to compare information about two or more kinds of
  3708.  entities, you will use the join operation.
  3709.  
  3710.  The join operation gives you unlimited flexibility in adding new kinds of
  3711.  data to your database. You can always create a new table that contains data
  3712.  about a different kind of entity. If the new table has a field with values
  3713.  similar to those in some field of an existing table or tables, it can be
  3714.  linked to those other tables by joining.
  3715.  
  3716.  
  3717.  How Joins Are Processed
  3718.  
  3719.  Knowing how joins are processed helps to understand them and to figure out
  3720.  why, when you incorrectly state a join, you sometimes get unexpected
  3721.  results. This section describes the processing of joins in conceptual terms.
  3722.  SQL Server's actual procedure is more sophisticated.
  3723.  
  3724.  Conceptually speaking, the first step in processing a join is to form the
  3725.  Cartesian product of the tables, all the possible combinations of the rows
  3726.  from each of the tables. The number of rows in a Cartesian product of two
  3727.  tables is equal to the number of rows in the first table times the number of
  3728.  rows in the second table.
  3729.  
  3730.  The Cartesian product of the authors table and the publishers table is 69─23
  3731.  authors multiplied by 3 publishers. You can have a look at a Cartesian
  3732.  product with any query that includes columns from more than one table in the
  3733.  select list, more than one table in the FROM clause, and no WHERE clause.
  3734.  For example, if you leave the WHERE clause off the join used in previous
  3735.  examples, SQL Server combines each of the 23 authors with each of the 3
  3736.  publishers and returns all 69 rows.
  3737.  
  3738.  This Cartesian product does not contain any particularly useful information.
  3739.  In fact, it is misleading, since it seems to imply that every author in the
  3740.  database has a relationship with every publisher in the database─which is
  3741.  not true.
  3742.  
  3743.  That's why a join must include a WHERE clause, which specifies the columns
  3744.  to be matched and the basis on which to match them. (It may also include
  3745.  other restrictions.) Once the Cartesian product has been formed, the rows
  3746.  that do not satisfy the join are eliminated, using the conditions in the
  3747.  WHERE clause.
  3748.  
  3749.  The WHERE clause included in the previous example eliminates from the
  3750.  results all the rows in which the author's city is not the same as the
  3751.  publisher's city.
  3752.  
  3753.  
  3754.  Equijoins and Natural Joins
  3755.  
  3756.  An equijoin is a join in which the values in the columns being joined are
  3757.  compared for equality, and all the columns in the tables being joined are
  3758.  included in the results.
  3759.  
  3760.  The following query is an example of an equijoin:
  3761.  
  3762.    select *
  3763.     from authors, publishers
  3764.     where authors.city = publishers.city
  3765.  
  3766.  In the results of that statement, the city column appears twice. By
  3767.  definition, the results of an equijoin contain two identical columns.
  3768.  
  3769.  Since there's usually no point in repeating the same information, one of
  3770.  these two identical columns can be eliminated by restating the query. The
  3771.  result is called a natural join.
  3772.  
  3773.  The query that results in the natural join of publishers and authors on the
  3774.  city column is
  3775.  
  3776.    select publishers.pub_id, publishers.pub_name,
  3777.     publishers.state, authors.*
  3778.     from publishers, authors
  3779.     where publishers.city = authors.city
  3780.  
  3781.  The column publishers.city does not appear in the results.
  3782.  
  3783.  
  3784.  Joins with Additional Conditions
  3785.  
  3786.  The WHERE clause of a join query can include selection criteria as well as
  3787.  specifying the join condition. For example, to retrieve the names and
  3788.  publishers of all the books for which advances greater than $7500 were paid,
  3789.  the statement is
  3790.  
  3791. ╓┌───────┌─────────────────────────────────────────────────────────────┌─────
  3792.  ────────────────────────────────────────────────────────────────────────────
  3793.          select title, pub_name, advance
  3794.  
  3795.          from titles, publishers
  3796.  
  3797.          where titles.pub_id = publishers.pub_id
  3798.  
  3799.          and advance > $7500
  3800.  
  3801.          title
  3802.  
  3803.  ────────────────────────────────────────────────────────────────────────────
  3804. 
  3805.          pub_name                                                      advance
  3806.  
  3807.          -------------------------------
  3808.  
  3809.          --------------------                                          -------
  3810.  
  3811.          You Can Combat Computer Stress!
  3812.  
  3813.          New Age Books                                                 10,125.
  3814.  
  3815.          The Gourmet Microwave
  3816.  
  3817.          Binnet & Hardley                                              15,000.
  3818.  
  3819.          Secrets of Silicon Valley
  3820.  
  3821.          Algodata Infosystems                                          8,000.0
  3822.  
  3823.          Sushi, Anyone?
  3824.  ────────────────────────────────────────────────────────────────────────────
  3825.         Sushi, Anyone?
  3826.  
  3827.          Binnet & Hardley                                              8,000.0
  3828.  
  3829.          (4 rows affected)
  3830.  
  3831.  
  3832.  
  3833.  Notice that the columns being joined need not appear in the select list (and
  3834.  thus, do not show up in the results).
  3835.  
  3836.  As many selection criteria as desired can be included in a join statement.
  3837.  The order of the selection criteria and the join condition is not important.
  3838.  
  3839.  
  3840.  
  3841.  Joins Not Based on Equality
  3842.  
  3843.  You can join values in two columns that are not equal. The following
  3844.  comparison operators can be used:
  3845.  
  3846. ╓┌─────────────────────────────────┌─────────────────────────────────────────╖
  3847.  Symbol                            Meaning
  3848.  ────────────────────────────────────────────────────────────────────────────
  3849.  >                                 greater than
  3850.  
  3851.  >=                                greater than or equal to
  3852.  
  3853.  <                                 less than
  3854.  
  3855.  <=                                less than or equal to
  3856.  
  3857.  !=                                not equal to
  3858.  
  3859.  ────────────────────────────────────────────────────────────────────────────
  3860.  
  3861.  
  3862.  
  3863.  This example of a greater-than join finds New Age authors who live in states
  3864.  that come after New Age Books' state (Massachusetts) in alphabetical order:
  3865.  
  3866.  
  3867.    select pub_name, publishers.state,
  3868.     au_lname, au_fname, authors.state
  3869.     from publishers, authors
  3870.     where authors.state > publishers.state
  3871.     and pub_name = "New Age Books"
  3872.  
  3873.     pub_name   state au_lname  au_fname  state
  3874.     --------------  ----- -------------- -----------  -----
  3875.     New Age Books  MA  Greene   Morningstar  TN
  3876.     New Age Books  MA  Blotchet-Halls Reginald  OR
  3877.     New Age Books  MA  del Castillo Innes   MI
  3878.     New Age Books  MA  Panteley  Sylvia   MD
  3879.     New Age Books  MA  Ringer   Anne   UT
  3880.     New Age Books  MA  Ringer   Albert   UT
  3881.  
  3882.     (6 rows affected)
  3883.  
  3884.  The following example uses a greater-than-or-equal-to join and a less-than
  3885.  join to print the royalty columns from the titles and roysched tables. If
  3886.  these columns match in this output, it means that the trigger that updates
  3887.  the royalty column in titles has been written correctly.
  3888.  
  3889. ╓┌───────┌──────────────────────────────────────────────┌──────────┌────────┌
  3890.  ────────────────────────────────────────────────────────────────────────────
  3891.          select t.title_id, t.ytd_sales, r.royalty,
  3892.          t.royalty
  3893.  
  3894.          from titles t, roysched r
  3895.  
  3896.          where t.title_id = r.title_id
  3897.  
  3898.          and t.ytd_sales >= r.lorange and t.ytd_sales
  3899.          < r.hirange
  3900.  
  3901.          title_id                                       ytd_sales  royalty  ro
  3902.  
  3903.          --------                                       ---------  -------  --
  3904.  
  3905.          BU1032                                         4095       10       10
  3906.  
  3907.          BU1111                                         3876       10       10
  3908.  ────────────────────────────────────────────────────────────────────────────
  3909.         BU1111                                         3876       10       10
  3910.  
  3911.          BU2075                                         18722      24       24
  3912.  
  3913.          BU7832                                         4095       10       10
  3914.  
  3915.          MC2222                                         2032       12       12
  3916.  
  3917.          MC3021                                         22246      24       24
  3918.  
  3919.          PC1035                                         8780       16       16
  3920.  
  3921.          PC8888                                         4095       10       10
  3922.  
  3923.          PS1372                                         375        10       10
  3924.  
  3925.          PS2091                                         2045       12       12
  3926.  
  3927.          PS2106                                         111        10       10
  3928.  
  3929.  ────────────────────────────────────────────────────────────────────────────
  3930. 
  3931.          PS3333                                         4072       10       10
  3932.  
  3933.          PS7777                                         3336       10       10
  3934.  
  3935.          TC3218                                         375        10       10
  3936.  
  3937.          TC4203                                         15096      14       14
  3938.  
  3939.          TC7777                                         4095       10       10
  3940.  
  3941.          (16 rows affected)
  3942.  
  3943.  
  3944.  
  3945.  
  3946.  Self-Joins and Aliases
  3947.  
  3948.  You can compare values within a column of a table with a self-join. For
  3949.  example, you can use a self-join to find out which authors in Oakland,
  3950.  California, live in the same zip code area.
  3951.  
  3952.  Since this query involves a join of the authors table with itself, the
  3953.  authors table appears in two roles. To distinguish these roles, you can
  3954.  temporarily (and arbitrarily) give the authors table two different
  3955.  aliases─au1 and au2─in the FROM clause. These aliases are used to qualify
  3956.  the column names in the rest of the query. The self-join statement looks
  3957.  like this:
  3958.  
  3959.    select au1.au_fname, au1.au_lname,
  3960.     au2.au_fname, au2.au_lname
  3961.     from authors au1, authors au2
  3962.     where au1.city = "Oakland" and au2.city = "Oakland"
  3963.     and au1.state = "CA" and au2.state = "CA"
  3964.     and au1.zip = au2.zip
  3965.  
  3966.     au_fname  au_lname  au_fname  au_lname
  3967.     --------  --------  --------  --------
  3968.     Marjorie  Green   Marjorie  Green
  3969.     Dick   Straight  Dick   Straight
  3970.     Dick   Straight  Dirk   Stringer
  3971.     Dick   Straight  Livia   Karsen
  3972.     Dirk   Stringer  Dick   Straight
  3973.     Dirk   Stringer  Dirk   Stringer
  3974.     Dirk   Stringer  Livia   Karsen
  3975.     Stearns   MacFeather  Stearns   MacFeather
  3976.     Livia   Karsen   Dick   Straight
  3977.     Livia   Karsen   Dirk   Stringer
  3978.     Livia   Karsen   Livia   Karsen
  3979.  
  3980.     (11 rows affected)
  3981.  
  3982.  To eliminate the rows in the results where the authors match themselves and
  3983.  to eliminate rows that are identical except that the order of the authors is
  3984.  reversed, you can make this addition to the self-join query:
  3985.  
  3986.    select au1.au_fname, au1.au_lname,
  3987.     au2.au_fname, au2.au_lname
  3988.     from authors au1, authors au2
  3989.     where au1.city = "Oakland" and au2.city = "Oakland"
  3990.     and au1.state = "CA" and au2.state = "CA"
  3991.     and au1.zip = au2.zip
  3992.     and au1.au_id < au2.au_id
  3993.  
  3994.  
  3995.     au_fname au_lname  au_fname  au_lname
  3996.     --------- --------  --------  --------
  3997.     Dick  Straight  Dirk   Stringer
  3998.     Dick  Straight  Livia   Karsen
  3999.     Dirk  Stringer  Livia   Karsen
  4000.  
  4001.     (3 rows affected)
  4002.  
  4003.  It is now clear that Dick Straight, Dirk Stringer, and Livia Karsen all have
  4004.  the same zip code.
  4005.  
  4006.  
  4007.  The Not-Equal Join
  4008.  
  4009.  The not-equal join is rarely used, except by mistake. As a general rule,
  4010.  not-equal joins make sense only when used with a self-join. For example, a
  4011.  not-equal join and a self-join are used to find the categories in which
  4012.  there are 2 or more inexpensive (less than $15) books of different prices:
  4013.  
  4014. ╓┌───────┌───────────────────────────────────────────────────────────────┌───
  4015.  ────────────────────────────────────────────────────────────────────────────
  4016.          select distinct t1.type, t1.price
  4017.  
  4018.          from titles t1, titles t2
  4019.  
  4020.          where t1.price <$15 and t2.price <$15
  4021.  
  4022.          and t1.type = t2.type
  4023.  
  4024.          and t1.price != t2.price
  4025.  
  4026.          type                                                            price
  4027.  
  4028.          ----------                                                      -----
  4029.  
  4030.          business                                                        2.99
  4031.  
  4032.          business                                                        11.95
  4033.  
  4034.  ────────────────────────────────────────────────────────────────────────────
  4035. 
  4036.          psychology                                                      7.00
  4037.  
  4038.          psychology                                                      7.99
  4039.  
  4040.          psychology                                                      10.95
  4041.  
  4042.          trad_cook                                                       11.95
  4043.  
  4044.          trad_cook                                                       14.99
  4045.  
  4046.          (7 rows affected)
  4047.  
  4048.  
  4049.  
  4050.  ────────────────────────────────────────────────────────────────────────────
  4051.  NOTE
  4052.  
  4053.  The expression NOT column_name = column_name is equivalent to column_name !=
  4054.  column_name.
  4055.  ────────────────────────────────────────────────────────────────────────────
  4056.  
  4057.  The following example uses a not-equal join combined with a self-join. It
  4058.  finds all the rows in the titleauthor table where there are 2 or more rows
  4059.  with the same title_id but different au_id numbers (that is, books that have
  4060.  more than one author).
  4061.  
  4062.    select distinct t1.au_id,t1.title_id
  4063.     from titleauthor t1, titleauthor t2
  4064.     where t1.title_id = t2.title_id
  4065.     and t1.au_id != t2.au_id
  4066.  
  4067.     au_id    title_id
  4068.     -----------   --------
  4069.     213-46-8915   BU1032
  4070.     267-41-2394   BU1111
  4071.     267-41-2394   TC7777
  4072.     409-56-7008   BU1032
  4073.     427-17-2319   PC8888
  4074.     472-27-2349   TC7777
  4075.     672-71-3249   TC7777
  4076.     722-51-5454   MC3021
  4077.     724-80-9391   BU1111
  4078.     724-80-9391   PS1372
  4079.     756-30-7391   PS1372
  4080.     846-92-7186   PC8888
  4081.     899-46-2035   MC3021
  4082.     899-46-2035   PS2091
  4083.     998-72-3567   PS2091
  4084.  
  4085.     (15 rows affected)
  4086.  
  4087.  
  4088.  Not-Equal Joins and Subqueries
  4089.  
  4090.  Sometimes a not-equal join query is not sufficiently restrictive and needs
  4091.  to be replaced by a subquery. For example, suppose you wanted to list the
  4092.  names of authors who live in a city where no publisher is located. For the
  4093.  sake of clarity, we have further restricted this query to authors whose last
  4094.  names begin with "A," "B," or "C." A not-equal join query might be
  4095.  
  4096.    select distinct au_lname, authors.city
  4097.     from publishers, authors
  4098.     where au_lname like "[ABC]%"
  4099.     and publishers.city != authors.city
  4100.  
  4101.  Here are the results. Notice that they do not answer the question that was
  4102.  asked.
  4103.  
  4104.    au_lname    city
  4105.     --------------   ---------
  4106.     Bennet     Berkeley
  4107.     Carson     Berkeley
  4108.     Blotchet-Halls   Corvallis
  4109.  
  4110.     (3 rows affected)
  4111.  
  4112.  The system interprets this version of the SQL statement to mean "find the
  4113.  names of authors who live in a city where some publisher is not located."
  4114.  All the authors that have last names beginning with "A," "B," or "C"
  4115.  qualify, including the authors who live in Berkeley (home of the publisher
  4116.  Algodata Infosystems).
  4117.  
  4118.  In this case, the way that the system processes joins (first finding every
  4119.  eligible combination before evaluating other conditions) causes this query
  4120.  to fail. The failure is a consequence of relational theory, not the
  4121.  implementation. In cases like this, you must use a subquery to get the
  4122.  results you want. A subquery can eliminate the ineligible rows first and
  4123.  then perform the remaining restrictions.
  4124.  
  4125.  Here's the correct statement:
  4126.  
  4127.    select distinct au_lname, authors.city
  4128.     from publishers, authors
  4129.     where au_lname like "[ABC]%"
  4130.     and authors.city not in
  4131.     (select city from publishers
  4132.     where authors.city = publishers.city)
  4133.  
  4134.  The following results are what we want:
  4135.  
  4136.    au_lname     city
  4137.     --------------    ---------
  4138.     Blotchet-Halls    Corvallis
  4139.  
  4140.     (1 row affected)
  4141.  
  4142.  Subqueries are covered in greater detail in Chapter 6, "Building
  4143.  Subqueries."
  4144.  
  4145.  
  4146.  Joining More Than Two Tables
  4147.  
  4148.  The titleauthor table of the pubs database offers a good example of a
  4149.  situation in which joining more than two tables is helpful. To find the
  4150.  titles of all the books of a particular type and the names of their authors,
  4151.  the query is
  4152.  
  4153.    select au_lname, au_fname, title
  4154.     from authors, titles, titleauthor
  4155.     where authors.au_id = titleauthor.au_id
  4156.     and titles.title_id = titleauthor.title_id
  4157.     and titles.type = "trad_cook"
  4158.  
  4159.  
  4160.  
  4161.  
  4162.  
  4163.    au_lname   au_fname
  4164.      title
  4165.     --------------  ---------
  4166.      ---------------------------------------------------------------
  4167.     Panteley   Sylvia
  4168.      Onions, Leeks, and Garlic: Cooking Secrets of the Mediterranean
  4169.     Blotchet-Halls  Reginald
  4170.      Fifty Years in Buckingham Palace Kitchens
  4171.     O'Leary    Michael
  4172.      Sushi, Anyone?
  4173.     Gringlesby   Burt
  4174.      Sushi, Anyone?
  4175.     Yokomoto   Akiko
  4176.      Sushi, Anyone?
  4177.  
  4178.     (5 rows affected)
  4179.  
  4180.  Notice that one of the tables in the FROM clause, titleauthor, does not
  4181.  contribute any columns to the results. Nor do any of the columns that are
  4182.  joined, au_id and title_id, appear in the results. Nonetheless, this join is
  4183.  possible only by using titleauthor as an intermediate table.
  4184.  
  4185.  You can also join more than two pairs of columns in the same statement. For
  4186.  example, here's how to find the authors who live in the same city and state
  4187.  as a publisher:
  4188.  
  4189.    select au_fname, au_lname, pub_name
  4190.     from authors, publishers
  4191.     where authors.city = publishers.city
  4192.     and authors.state = publishers.state
  4193.  
  4194.     au_fname  au_lname  pub_name
  4195.     --------  --------  --------------------
  4196.     Cheryl   Carson   Algodata Infosystems
  4197.     Abraham   Bennet   Algodata Infosystems
  4198.  
  4199.     (2 rows affected)
  4200.  
  4201.  When there is more than one join operator in the same statement, either to
  4202.  join more than two tables or to join more than two pairs of columns, the
  4203.  join expressions are almost always connected with AND, as in earlier
  4204.  examples. However, it is also legal to connect them with OR.
  4205.  
  4206.  
  4207.  Outer Joins
  4208.  
  4209.  In the joins we've discussed so far, only matching rows (rows with values in
  4210.  the specified columns that satisfy the join condition) are included in the
  4211.  results. In a sense, these join operations eliminate the information
  4212.  contained in the rows that do not match.
  4213.  
  4214.  Sometimes it is desirable to retain that information by including
  4215.  nonmatching rows in the results of a join. On such occasions, the outer join
  4216.  is the operation of choice. TRANSACT-SQL is one of a few versions of SQL
  4217.  that supports the outer join.
  4218.  
  4219.  Consider a join of the authors table and the publishers table on their city
  4220.  columns. The results show only the authors that live in cities in which a
  4221.  publisher is located.
  4222.  
  4223.    select au_fname, au_lname, pub_name
  4224.     from authors, publishers
  4225.     where authors.city = publishers.city
  4226.  
  4227.     au_fname  au_lname  pub_name
  4228.     --------  --------  --------------------
  4229.     Abraham   Bennet   Algodata Infosystems
  4230.     Cheryl   Carson   Algodata Infosystems
  4231.  
  4232.     (2 rows affected)
  4233.  
  4234.  To include all the authors in the results, regardless of whether a publisher
  4235.  is located in the same city, use an outer join. Here's what the query and
  4236.  the results of the outer join look like:
  4237.  
  4238.    select au_fname, au_lname, pub_name
  4239.     from authors, publishers
  4240.     where authors.city *= publishers.city
  4241.  
  4242.     au_fname  au_lname   pub_name
  4243.     -----------  --------------  --------------------
  4244.     Johnson   White    NULL
  4245.     Marjorie  Green    NULL
  4246.     Cheryl   Carson    Algodata Infosystems
  4247.     Michael   O'Leary    NULL
  4248.     Dick   Straight   NULL
  4249.     Meander   Smith    NULL
  4250.     Abraham   Bennet    Algodata Infosystems
  4251.     Ann    Dull    NULL
  4252.     Burt   Gringlesby   NULL
  4253.     Chastity  Locksley   NULL
  4254.     Morningstar  Greene    NULL
  4255.     Reginald  Blotchet-Halls  NULL
  4256.     Akiko   Yokomoto   NULL
  4257.     Innes   del Castillo  NULL
  4258.     Michel   DeFrance   NULL
  4259.     Dirk   Stringer   NULL
  4260.     Stearns   MacFeather   NULL
  4261.     Livia   Karsen    NULL
  4262.     Sylvia   Panteley   NULL
  4263.     Sheryl   Hunter    NULL
  4264.     Heather   McBadden   NULL
  4265.     Anne   Ringer    NULL
  4266.     Albert   Ringer    NULL
  4267.  
  4268.     (23 rows affected)
  4269.  
  4270.  The comparison operator "*=" distinguishes the outer join from an ordinary
  4271.  join. It tells SQL Server to include all the rows in the authors table in
  4272.  the results, whether or not there is a match on the city column in the
  4273.  publishers table. Notice that in the results, there is no matching data for
  4274.  most of the authors listed, so these rows contain null values in the
  4275.  pub_name column.
  4276.  
  4277.  The other variety of outer join is specified with the comparison operator
  4278.  "=*", which indicates that all the rows in the second table are to be
  4279.  included in the results, regardless of whether there is matching data in the
  4280.  first table.
  4281.  
  4282.  Substituting this operator in the outer join query shown earlier gives this
  4283.  result:
  4284.  
  4285.    select au_fname, au_lname, pub_name
  4286.     from authors, publishers
  4287.     where authors.city =* publishers.city
  4288.  
  4289.     au_fname  au_lname  pub_name
  4290.     --------  --------  ------------------
  4291.     NULL   NULL   New Age Books
  4292.     NULL   NULL   Binnet & Hardley
  4293.     Cheryl   Carson   Algodata Infosystems
  4294.     Abraham   Bennet   Algodata Infosystems
  4295.  
  4296.     (4 rows affected)
  4297.  
  4298.  An outer join can be helpful in other situations. Say you are generating a
  4299.  list of authors' names and phone numbers for a salesperson in your
  4300.  publishing company to contact. You have just opened offices in Salt Lake
  4301.  City and Oakland, and you wish to flag the authors who live in those cities
  4302.  so that the salesperson will remember to mention the new office to them.
  4303.  
  4304.  The first step is to create a table like this one:
  4305.  
  4306.    create table reminder
  4307.     (city varchar(20),
  4308.     message varchar(25))
  4309.  
  4310.  After inserting city and message data in reminder, it looks like this:
  4311.  
  4312.    select *
  4313.     from reminder
  4314.  
  4315.     city     message
  4316.     ---------------   ------------------
  4317.     Salt Lake City   MENTION NEW OFFICE
  4318.     Oakland     MENTION NEW OFFICE
  4319.  
  4320.     (2 rows affected)
  4321.  
  4322.  Now, an outer join between authors and reminder produces the list you want:
  4323.  
  4324.  
  4325.    select au_fname, au_lname, phone, message
  4326.     from authors, reminder
  4327.     where authors.city *= reminder.city
  4328.  
  4329.     au_fname  au_lname  phone   message
  4330.     ---------  -------------- ------------ ------------------
  4331.     Johnson   White   408 496-7223 NULL
  4332.     Marjorie  Green   415 986-7020 MENTION NEW OFFICE
  4333.     Cheryl   Carson   415 548-7723 NULL
  4334.     Michael   O'Leary   408 286-2428 NULL
  4335.     Dick   Straight  415 834-2919 MENTION NEW OFFICE
  4336.     Meander   Smith   913 843-0462 NULL
  4337.     Abraham   Bennet   415 658-9932 NULL
  4338.     Ann    Dull   415 836-7128 NULL
  4339.     Burt   Gringlesby  707 938-6445 NULL
  4340.     Chastity  Locksley  415 585-4620 NULL
  4341.     Morningstar  Greene   615 297-2723 NULL
  4342.     Reginald  Blotchet-Halls 503 745-6402 NULL
  4343.     Akiko   Yokomoto  415 935-4228 NULL
  4344.     Innes   del Castillo 615 996-8275 NULL
  4345.     Michel   DeFrance  219 547-9982 NULL
  4346.     Dirk   Stringer  415 843-2991 MENTION NEW OFFICE
  4347.     Stearns   MacFeather  415 354-7128 MENTION NEW OFFICE
  4348.     Livia   Karsen   415 534-9219 MENTION NEW OFFICE
  4349.     Sylvia   Panteley  301 946-8853 NULL
  4350.     Sheryl   Hunter   415 836-7128 NULL
  4351.     Heather   McBadden  707 448-4982 NULL
  4352.     Anne   Ringer   801 826-0752 MENTION NEW OFFICE
  4353.     Albert   Ringer   801 826-0752 MENTION NEW OFFICE
  4354.  
  4355.     (23 rows affected)
  4356.  
  4357.  
  4358.  Joins and Null Values
  4359.  
  4360.  If there are null values in the columns of the tables being joined, the null
  4361.  values will never match each other. This is because null values represent
  4362.  unknown values and there is no reason to believe one unknown value will
  4363.  match another.
  4364.  
  4365.  
  4366.  Help on Joins
  4367.  
  4368.  The sp_helpjoins system procedure lists the columns in two tables or views
  4369.  that are likely join candidates. The sp_helpjoins system procedure has the
  4370.  following syntax:
  4371.  
  4372.    sp_helpjoins leftab, righttab
  4373.  
  4374.  For example, here's how you'd use sp_helpjoins to find the likely join
  4375.  columns between titleauthor and titles:
  4376.  
  4377.    sp_helpjoins titleauthor, titles
  4378.  
  4379.  The column pairs that sp_helpjoins displays come from two sources. First,
  4380.  sp_helpjoins checks the syskeys table in the current database to see if any
  4381.  common keys have been defined on the two tables with sp_commonkey. If it
  4382.  doesn't find any common keys there, the procedure applies less restrictive
  4383.  criteria to come up with any keys that can be reasonably joined; it checks
  4384.  for keys with the same user datatypes and if that fails, for columns with
  4385.  the same name and datatype.
  4386.  
  4387.  For complete information on system procedures, see the SQL Server Language
  4388.  Reference.
  4389.  
  4390.  
  4391.  
  4392.  
  4393.  
  4394.  
  4395.  Chapter 4  Displaying Totals: GROUP BY and COMPUTE
  4396.  ────────────────────────────────────────────────────────────────────────────
  4397.  
  4398.  
  4399.  Introduction
  4400.  
  4401.  This chapter describes aggregate functions and the GROUP BY clause, and row
  4402.  aggregate functions and the COMPUTE clause.
  4403.  
  4404.  Aggregate functions─SUM, AVG, COUNT, COUNT(*), MAX, and MIN─generate summary
  4405.  values that appear as new columns in the query results. The GROUP BY clause,
  4406.  part of the SELECT statement, divides a table into groups. TRANSACT-SQL has
  4407.  eliminated some of the restrictions that apply to the GROUP BY clause in
  4408.  other versions of SQL. GROUP BY and aggregate functions are often used
  4409.  together, in which case a summary value is calculated for each group.
  4410.  
  4411.  Row aggregate functions─SUM, AVG, COUNT, MAX, and MIN─and the COMPUTE clause
  4412.  are always used together as part of a SELECT statement. Row aggregate
  4413.  functions generate summary values that appear as additional rows in the
  4414.  query results. An SQL statement that includes a COMPUTE clause and row
  4415.  aggregate functions produces a report with detail and summary rows.
  4416.  
  4417.  
  4418.  Aggregate Functions and the GROUP BY Clause
  4419.  
  4420.  Aggregate functions calculate summary values from the data in a particular
  4421.  column. Aggregate functions can be applied to all the rows in a table, to a
  4422.  subset of the table specified by a WHERE clause, or to one or more groups of
  4423.  rows in the table. From each set of rows to which an aggregate function is
  4424.  applied, a single value is generated.
  4425.  
  4426.  This example calculates the sum of year-to-date sales for all books in the
  4427.  titles table:
  4428.  
  4429.  select sum(ytd_sales)
  4430.  
  4431.  from titles
  4432.  
  4433.  
  4434.  
  4435.  ------------
  4436.  
  4437.  97446
  4438.  
  4439.  
  4440.  
  4441.  (1 row affected)
  4442.  
  4443.  Notice that to use an aggregate function, you give the function name
  4444.  followed by an expression on whose values the aggregate function will
  4445.  operate. Enclose the expression in parentheses.
  4446.  
  4447.  Aggregate functions have the following syntax:
  4448.  
  4449.    aggregate_function ([DISTINCT] expression)
  4450.  
  4451.  The aggregate operators are SUM, AVG, MAX, MIN, COUNT, and COUNT(*). The
  4452.  optional keyword DISTINCT can be used with SUM, AVG, and COUNT to eliminate
  4453.  duplicate values before aggregate function is applied. DISTINCT is not
  4454.  allowed with MAX, MIN, or COUNT(*).
  4455.  
  4456.  
  4457.  The expression to which the syntax statement refers is usually a column
  4458.  name. It can also be a constant, a function, or any combination of column
  4459.  names, constants, and functions connected by arithmetic or bitwise
  4460.  operators. An expression can also be a subquery.
  4461.  
  4462.  For example, with this query you can find the average price of all books if
  4463.  the prices were doubled:
  4464.  
  4465.  select avg(price * 2)
  4466.  
  4467.  from titles
  4468.  
  4469.  
  4470.  
  4471.  ------------
  4472.  
  4473.   29.53
  4474.  
  4475.  
  4476.  
  4477.  (1 row affected)
  4478.  
  4479.  The syntax of the aggregate functions and their results are as follows:
  4480.  
  4481. ╓┌─────────────────────────────────┌─────────────────────────────────────────
  4482.  Aggregate Function                Result
  4483.  ────────────────────────────────────────────────────────────────────────────
  4484.  SUM([DISTINCT] expression)        Total of the [distinct] values in the
  4485.                                    numeric column
  4486.  
  4487.  AVG([DISTINCT] expression)        Average of the [distinct] values in the
  4488.                                    numeric column
  4489.  
  4490.  COUNT([DISTINCT] expression)      Number of [distinct] non-null values in
  4491.                                    the column
  4492.  
  4493.  COUNT(*)                          Number of selected rows
  4494.  
  4495.  MAX(expression)                   Highest value in the expression
  4496.  Aggregate Function                Result
  4497.  ────────────────────────────────────────────────────────────────────────────
  4498. MAX(expression)                   Highest value in the expression
  4499.  
  4500.  MIN(expression)                   Lowest value in the expression
  4501.  
  4502.  ────────────────────────────────────────────────────────────────────────────
  4503.  
  4504.  
  4505.  
  4506.  Aggregate functions can be used in a select list, as in the previous
  4507.  examples, or in the HAVING clause of a SELECT statement that includes a
  4508.  GROUP BY clause.
  4509.  
  4510.  Aggregate functions cannot be used in a WHERE clause. However, a SELECT
  4511.  statement with aggregate functions in its select list often includes a WHERE
  4512.  clause that restricts the rows to which the aggregate function is applied.
  4513.  In the examples given earlier, each aggregate function produced a single
  4514.  summary value for the whole table. If a SELECT statement includes a WHERE
  4515.  clause (but not a GROUP BY clause), an aggregate function produces a single
  4516.  value for the subset of rows that the WHERE clause specifies.
  4517.  
  4518.  This query returns the average advance and the sum of year-to-date sales for
  4519.  business books only:
  4520.  
  4521.  select avg(advance),, sum(ytd_sales)
  4522.  
  4523.  from titles
  4524.  
  4525.  where type = "business"
  4526.  
  4527.  
  4528.  
  4529.  --------------
  4530.  
  4531.  6281.2530788
  4532.  
  4533.  
  4534.  
  4535.  (1 row affected)
  4536.  
  4537.  Whenever an aggregate function is used in a SELECT statement that does not
  4538.  include a GROUP BY clause, it produces a single value. This is true whether
  4539.  it is operating on all the rows in a table or on a subset of rows defined by
  4540.  a WHERE clause. It is called a scalar aggregate.
  4541.  
  4542.  Note that you can use more than one aggregate function in the same select
  4543.  list and produce more than one scalar aggregate in a single SELECT
  4544.  statement.
  4545.  
  4546.  When you sum or average integer data, TRANSACT-SQL treats the result as an
  4547.  int value, even if the datatype of the column is smallint or tinyint. To
  4548.  avoid overflow errors in DB-LIBRARY programs, declare all variables for
  4549.  results of averages or sums as type int.
  4550.  
  4551.  
  4552.  Aggregate Functions and Datatypes
  4553.  
  4554.  SUM and AVG can be used with numeric columns only─int, smallint, tinyint,
  4555.  float, and money. MIN and MAX cannot be used with bit datatypes. Aggregate
  4556.  functions cannot be used with text and image datatypes.
  4557.  
  4558.  With these exceptions the other aggregate functions can be used with any
  4559.  type of column. For example, you can use MIN (minimum) to find the lowest
  4560.  value, the one closest to the beginning of the alphabet, in a character type
  4561.  column:
  4562.  
  4563.    select min(au_lname)
  4564.     from authors
  4565.  
  4566.     --------------------
  4567.     Bennet
  4568.  
  4569.     (1 row affected)
  4570.  
  4571.  
  4572.  COUNT(*)
  4573.  
  4574.  COUNT(*) does not require an expression as a parameter because, by
  4575.  definition it does not use information about any particular column. It is
  4576.  used to find the total number of rows in a table. This statement finds the
  4577.  total number of books:
  4578.  
  4579.  select count(*)
  4580.  
  4581.  from titles
  4582.  
  4583.  
  4584.  
  4585.  ------------
  4586.  
  4587.  18
  4588.  
  4589.  
  4590.  
  4591.  (1 row affected)
  4592.  
  4593.  COUNT(*) returns the number of rows in the specified table without
  4594.  eliminating duplicates. It counts each row separately, including rows that
  4595.  contain null values.
  4596.  
  4597.  Like other aggregate functions, COUNT(*) can be combined with other
  4598.  aggregate functions in the select list, with WHERE clauses, and so on. This
  4599.  statement shows COUNT(*) combined with a WHERE clause:
  4600.  
  4601.  select count(*), avg(price)
  4602.  
  4603.  from titles
  4604.  
  4605.  where advance > 1000
  4606.  
  4607.  
  4608.  
  4609.  -------------------
  4610.  
  4611.  1514.42
  4612.  
  4613.  
  4614.  
  4615.  (1 row affected)
  4616.  
  4617.  
  4618.  The DISTINCT Keyword
  4619.  
  4620.  The DISTINCT keyword is optional with SUM, AVG, and COUNT. It is not allowed
  4621.  with MIN, MAX, or COUNT(*). When DISTINCT is used, duplicate values are
  4622.  eliminated before the sum, average, or count is calculated.
  4623.  
  4624.  If you use DISTINCT, the parameter cannot include an arithmetic expression.
  4625.  It must consist of a column name only.
  4626.  
  4627.  When DISTINCT is used, it appears inside the parentheses and before the
  4628.  column name. The following statement returns the average of the distinct
  4629.  prices of business books:
  4630.  
  4631.  select avg(distinct price)
  4632.  
  4633.  from titles
  4634.  
  4635.  where type = "business"
  4636.  
  4637.  
  4638.  
  4639.  ------------
  4640.  
  4641.  11.64
  4642.  
  4643.  
  4644.  
  4645.  (1 row affected)
  4646.  
  4647.  Without DISTINCT, the AVG function finds the average price of all business
  4648.  titles in the titles table:
  4649.  
  4650.  select avg(price)
  4651.  
  4652.  from titles
  4653.  
  4654.  where type = "business"
  4655.  
  4656.  
  4657.  
  4658.  ------------
  4659.  
  4660.  13.73
  4661.  
  4662.  
  4663.  
  4664.  (1 row affected)
  4665.  
  4666.  To find the number of different cities the authors live in, type
  4667.  
  4668.  select count(distinct city)
  4669.  
  4670.  from authors
  4671.  
  4672.  
  4673.  
  4674.  ------------
  4675.  
  4676.  16
  4677.  
  4678.  
  4679.  
  4680.  (1 row affected)
  4681.  
  4682.  
  4683.  Null Values and Aggregate Functions
  4684.  
  4685.  If there are any null values in the column on which the aggregate function
  4686.  is operating, they are ignored for the purposes of the function.
  4687.  
  4688.  For example, if you ask for the count of advances in the titles table, your
  4689.  answer is not the same as if you ask for the count of title names because of
  4690.  the null values in the advance column:
  4691.  
  4692.  select count(advance)
  4693.  
  4694.  from titles
  4695.  
  4696.  
  4697.  
  4698.  ------------
  4699.  
  4700.  16
  4701.  
  4702.  
  4703.  
  4704.  (1 row affected)
  4705.  
  4706.  
  4707.  
  4708.  select count(title)
  4709.  
  4710.  from titles
  4711.  
  4712.  
  4713.  
  4714.  -----------
  4715.  
  4716.  18
  4717.  
  4718.  
  4719.  
  4720.  (1 row affected)
  4721.  
  4722.  The exception to this rule is COUNT(*), which counts each row, even if every
  4723.  field in it is NULL.
  4724.  
  4725.  If no rows meet the condition(s) specified in the WHERE clause, COUNT
  4726.  returns a value of zero. The other functions all return NULL. Here are
  4727.  examples:
  4728.  
  4729.  select count(distinct title)
  4730.  
  4731.  from titles
  4732.  
  4733.  where type = "poetry"
  4734.  
  4735.  
  4736.  
  4737.  ------------
  4738.  
  4739.  0
  4740.  
  4741.  
  4742.  
  4743.  (1 row affected)
  4744.  
  4745.  
  4746.  
  4747.  
  4748.  
  4749.  select avg(advance)
  4750.  
  4751.  from titles
  4752.  
  4753.  where type = "poetry"
  4754.  
  4755.  
  4756.  
  4757.  ------------
  4758.  
  4759.  NULL
  4760.  
  4761.  
  4762.  
  4763.  (1 row affected)
  4764.  
  4765.  
  4766.  The GROUP BY Clause
  4767.  
  4768.  The GROUP BY clause is used in SELECT statements to divide a table into
  4769.  groups. You can group by a column name or by the results of computed columns
  4770.  when using numeric datatypes. You cannot group by columns of bit, text, or
  4771.  image datatypes. A GROUP BY clause almost always appears in statements that
  4772.  also include aggregate functions, in which case the aggregate function
  4773.  produces a value for each group. These values are called vector aggregates.
  4774.  (A scalar aggregate is a single value produced by an aggregate function
  4775.  without a GROUP BY clause.)
  4776.  
  4777.  This statement finds the average advance and sum of year-to-date sales for
  4778.  each type of book:
  4779.  
  4780.  select type, avg(advance), sum(ytd_sales)
  4781.  
  4782.  from titles
  4783.  
  4784.  group by type
  4785.  
  4786.  
  4787.  
  4788.  type
  4789.  
  4790.  -------------------------
  4791.  
  4792.  UNDECIDEDNULLNULL
  4793.  
  4794.  business6,281.2530788
  4795.  
  4796.  mod_cook7,500.0024278
  4797.  
  4798.  popular_comp7,500.0012875
  4799.  
  4800.  psychology4,255.009939
  4801.  
  4802.  trad_cook6,333.3319566
  4803.  
  4804.  
  4805.  
  4806.  (6 rows affected)
  4807.  
  4808.  The summary values produced by SELECT statements with GROUP BY and aggregate
  4809.  functions appear as new columns in the results.
  4810.  
  4811.  
  4812.  GROUP BY Syntax
  4813.  
  4814.  The GROUP BY clause has the following syntax:
  4815.  
  4816.    [GROUP BY [ALL]
  4817.     aggregate_free_expression
  4818.     [, aggregate_free_expression...]
  4819.     [HAVING search_conditions]
  4820.  
  4821.  The SQL Server Language Reference lists the complete syntax of the SELECT
  4822.  statement. Remember that the order of the clauses in the SELECT statement is
  4823.  significant. You are free to omit any of the optional clauses, but when you
  4824.  use them, they must appear in the order shown in the SQL Server Language
  4825.  Reference.
  4826.  
  4827.  There are no restrictions on what you can include in the select list of a
  4828.  SELECT statement that includes GROUP BY. The columns in the select list are
  4829.  not limited to the grouping columns or columns used with the aggregate
  4830.  functions. For example, the inclusion of the title_id column in the select
  4831.  list is allowed:
  4832.  
  4833.  select type, title_id, avg(price), avg(advance)
  4834.  
  4835.  from titles
  4836.  
  4837.  group by type
  4838.  
  4839.  
  4840.  
  4841.  typetitle_id
  4842.  
  4843.  -------------------------  --------
  4844.  
  4845.  businessBU103213.73  6,281.25
  4846.  
  4847.  businessBU111113.73  6,281.25
  4848.  
  4849.  businessBU207513.73  6,281.25
  4850.  
  4851.  businessBU783213.73  6,281.25
  4852.  
  4853.  mod_cookMC222211.49  7,500.00
  4854.  
  4855.  mod_cookMC302111.49  7,500.00
  4856.  
  4857.  UNDECIDEDMC3026NULL   NULL
  4858.  
  4859.  popular_compPC103521.48  7,500.00
  4860.  
  4861.  popular_compPC888821.48  7,500.00
  4862.  
  4863.  popular_compPC999921.48  7,500.00
  4864.  
  4865.  psychologyPS137213.50  4,255.00
  4866.  
  4867.  psychologyPS209113.50  4,255.00
  4868.  
  4869.  psychologyPS210613.50  4,255.00
  4870.  
  4871.  psychologyPS333313.50  4,255.00
  4872.  
  4873.  psychologyPS777713.50  4,255.00
  4874.  
  4875.  trad_cookTC321815.96  6,333.33
  4876.  
  4877.  trad_cookTC420315.96  6,333.33
  4878.  
  4879.  trad_cookTC777715.96  6,333.33
  4880.  
  4881.  
  4882.  
  4883.  (18 rows affected)
  4884.  
  4885.  You can group by an expression as long as it does not include aggregate
  4886.  functions. For example:
  4887.  
  4888.  select avg(ytd_sales), ytd_sales*royalty
  4889.  
  4890.  from titles
  4891.  
  4892.  group by ytd_sales * royalty
  4893.  
  4894.  
  4895.  
  4896.  --------------------
  4897.  
  4898.  1111110
  4899.  
  4900.  3753750
  4901.  
  4902.  203224384
  4903.  
  4904.  204524540
  4905.  
  4906.  333633360
  4907.  
  4908.  387638760
  4909.  
  4910.  407240720
  4911.  
  4912.  409540950
  4913.  
  4914.  8780140480
  4915.  
  4916.  15096211344
  4917.  
  4918.  18722449328
  4919.  
  4920.  22246533904
  4921.  
  4922.  
  4923.  
  4924.  (12 rows affected)
  4925.  
  4926.  However, you cannot group by an alias. This statement produces an error
  4927.  message:
  4928.  
  4929.    select Category = type, title_id, avg(price), avg(advance)
  4930.     from titles
  4931.     group by Category
  4932.  
  4933.  You can list more than one column in the GROUP BY clause to nest groups─that
  4934.  is, you can group a table by any combination of columns. For example, here's
  4935.  the statement that finds the average price and the sum of the year-to-date
  4936.  sales, grouped by type and within type by publisher identification number:
  4937.  
  4938.  select type, pub_id, avg(price), sum(ytd_sales)
  4939.  
  4940.  from titles
  4941.  
  4942.  group by type, pub_id
  4943.  
  4944.  
  4945.  
  4946.  typepub_id
  4947.  
  4948.  -----------------------  -----
  4949.  
  4950.  UNDECIDED0877NULL   NULL
  4951.  
  4952.  business07362.99   18722
  4953.  
  4954.  business138917.31  12066
  4955.  
  4956.  mod_cook087711.49  24278
  4957.  
  4958.  popular_comp138921.48  12875
  4959.  
  4960.  psychology073611.48  9564
  4961.  
  4962.  psychology087721.59  375
  4963.  
  4964.  trad_cook087715.96  19566
  4965.  
  4966.  
  4967.  
  4968.  (8 rows affected)
  4969.  
  4970.  Another kind of nesting, nesting a vector aggregate inside a scalar
  4971.  aggregate, is a TRANSACT-SQL extension. For example, to find the average
  4972.  price of all the types of books, type
  4973.  
  4974.  select avg(price)
  4975.  
  4976.  from titles
  4977.  
  4978.  group by type
  4979.  
  4980.  
  4981.  
  4982.  ------------
  4983.  
  4984.  NULL
  4985.  
  4986.  13.73
  4987.  
  4988.  11.49
  4989.  
  4990.  21.48
  4991.  
  4992.  13.50
  4993.  
  4994.  15.96
  4995.  
  4996.  
  4997.  
  4998.  (6 rows affected)
  4999.  
  5000.  You can find the highest average price of all the types of books in a single
  5001.  query:
  5002.  
  5003.  select max(avg(price))
  5004.  
  5005.  from titles
  5006.  
  5007.  group by type
  5008.  
  5009.  
  5010.  
  5011.  ------------
  5012.  
  5013.  21.48
  5014.  
  5015.  
  5016.  
  5017.  (1 row affected)
  5018.  
  5019.  By definition, the GROUP BY clause applies to the vector aggregate─in this
  5020.  case, AVG.
  5021.  
  5022.  
  5023.  GROUP BY without Aggregate Functions
  5024.  
  5025.  If GROUP BY is used without an aggregate function, it rearranges the table
  5026.  in the FROM clause into groups without producing any summary values. Each of
  5027.  the rows that make up a group contains the same value in the GROUP BY
  5028.  column. (The actual data in the database is not affected, of course.)
  5029.  
  5030.  Here's an example:
  5031.  
  5032.  select type, title_id, price
  5033.  
  5034.  from titles
  5035.  
  5036.  group by type
  5037.  
  5038.  
  5039.  
  5040.  typetitle_idprice
  5041.  
  5042.  -------------------------
  5043.  
  5044.  businessBU103219.99
  5045.  
  5046.  businessBU111111.95
  5047.  
  5048.  businessBU20752.99
  5049.  
  5050.  businessBU783219.99
  5051.  
  5052.  mod_cookMC222219.99
  5053.  
  5054.  mod_cookMC30212.99
  5055.  
  5056.  UNDECIDEDMC3026NULL
  5057.  
  5058.  popular_compPC103522.95
  5059.  
  5060.  popular_compPC888820.00
  5061.  
  5062.  popular_compPC9999NULL
  5063.  
  5064.  psychologyPS137221.59
  5065.  
  5066.  psychologyPS209110.95
  5067.  
  5068.  psychologyPS21067.00
  5069.  
  5070.  psychologyPS333319.99
  5071.  
  5072.  psychologyPS77777.99
  5073.  
  5074.  trad_cookTC321820.95
  5075.  
  5076.  trad_cookTC420311.95
  5077.  
  5078.  trad_cookTC777714.99
  5079.  
  5080.  
  5081.  
  5082.  (18 rows affected)
  5083.  
  5084.  
  5085.  GROUP BY and Null Values
  5086.  
  5087.  If the grouping column contains a null value, that row becomes a group in
  5088.  the results. If the grouping column contains more than one null value, the
  5089.  null values are put into a single group.
  5090.  
  5091.  The royalty column in the titles table contains some null values. Here's an
  5092.  example that uses GROUP BY and the royalty column:
  5093.  
  5094.  select royalty, avg(price * 2)
  5095.  
  5096.  from titles
  5097.  
  5098.  group by royalty
  5099.  
  5100.  
  5101.  
  5102.  royalty
  5103.  
  5104.  -------------
  5105.  
  5106.  NULLNULL
  5107.  
  5108.  1032.89
  5109.  
  5110.  1230.94
  5111.  
  5112.  1423.90
  5113.  
  5114.  1645.90
  5115.  
  5116.  245.98
  5117.  
  5118.  
  5119.  
  5120.  (6 rows affected)
  5121.  
  5122.  
  5123.  GROUP BY and the WHERE Clause
  5124.  
  5125.  You can use a WHERE clause in a statement with GROUP BY. Rows that don't
  5126.  satisfy the conditions in the WHERE clause are eliminated before any
  5127.  grouping is done. Here's an example:
  5128.  
  5129.  select type, avg(price)
  5130.  
  5131.  from titles
  5132.  
  5133.  where advance > 5000
  5134.  
  5135.  group by type
  5136.  
  5137.  
  5138.  
  5139.  type
  5140.  
  5141.  -----------------
  5142.  
  5143.  business2.99
  5144.  
  5145.  mod_cook2.99
  5146.  
  5147.  popular_comp21.48
  5148.  
  5149.  psychology14.30
  5150.  
  5151.  trad_cook17.97
  5152.  
  5153.  
  5154.  
  5155.  (5 rows affected)
  5156.  
  5157.  Only the rows with advances greater than $5000 are included in the groups
  5158.  shown in the query results.
  5159.  
  5160.  
  5161.  GROUP BY and ALL
  5162.  
  5163.  The ALL keyword in the GROUP BY clause is a TRANSACT-SQL enhancement to SQL.
  5164.  It is meaningful only if the SELECT statement in which it is used also
  5165.  includes a WHERE clause.
  5166.  
  5167.  If you use ALL, the query results will include all the groups produced by
  5168.  the GROUP BY clause, even if some of the groups don't have any rows that
  5169.  meet the search conditions. Without ALL, a SELECT statement that includes
  5170.  GROUP BY will not show groups for which no rows qualify.
  5171.  
  5172.  Here's an example:
  5173.  
  5174.  select type, avg(price)
  5175.  
  5176.  from titles
  5177.  
  5178.  where royalty = 10
  5179.  
  5180.  group by type
  5181.  
  5182.  
  5183.  
  5184.  type
  5185.  
  5186.  -----------------
  5187.  
  5188.  business17.31
  5189.  
  5190.  popular_comp20.00
  5191.  
  5192.  psychology14.14
  5193.  
  5194.  trad_cook17.97
  5195.  
  5196.  
  5197.  
  5198.  (4 rows affected)
  5199.  
  5200.  
  5201.  
  5202.  select type, avg(price)
  5203.  
  5204.  from titles
  5205.  
  5206.  where royalty = 10
  5207.  
  5208.  group by all type
  5209.  
  5210.  
  5211.  
  5212.  type
  5213.  
  5214.  --------------
  5215.  
  5216.  UNDECIDEDNULL
  5217.  
  5218.  business17.31
  5219.  
  5220.  mod_cookNULL
  5221.  
  5222.  popular_comp20.00
  5223.  
  5224.  psychology14.14
  5225.  
  5226.  trad_cook17.97
  5227.  
  5228.  
  5229.  
  5230.  (6 rows affected)
  5231.  
  5232.  The first statement produces groups only for those books that commanded
  5233.  royalties of 10%. Since no modern cookbooks have a royalty of 10%, there is
  5234.  no group in the results for the mod_cook type.
  5235.  
  5236.  The second statement produces groups for all types, including modern cooking
  5237.  and "UNDECIDED," even though the modern cooking group doesn't include any
  5238.  rows that meet the qualification specified in the WHERE clause.
  5239.  
  5240.  The column that holds the aggregate value (the average price) is NULL for
  5241.  groups that lack qualifying rows.
  5242.  
  5243.  
  5244.  GROUP BY and ORDER BY
  5245.  
  5246.  Use an ORDER BY clause when you want the results to be ordered in a
  5247.  particular way.
  5248.  
  5249.  Put the ORDER BY clause after the GROUP BY clause. For example, to find the
  5250.  average price of each type of book and order the results by average price,
  5251.  type
  5252.  
  5253.  select type, avg(price)
  5254.  
  5255.  from titles
  5256.  
  5257.  group by type
  5258.  
  5259.  order by avg(price)
  5260.  
  5261.  
  5262.  
  5263.  type
  5264.  
  5265.  ------------------
  5266.  
  5267.  UNDECIDEDNULL
  5268.  
  5269.  mod_cook11.49
  5270.  
  5271.  psychology13.50
  5272.  
  5273.  business13.73
  5274.  
  5275.  trad_cook15.96
  5276.  
  5277.  popular_comp21.48
  5278.  
  5279.  
  5280.  
  5281.  (6 rows affected)
  5282.  
  5283.  
  5284.  The HAVING Clause
  5285.  
  5286.  HAVING sets conditions for the GROUP BY clause. It is similar to WHERE, but
  5287.  HAVING places conditions on groups, whereas WHERE places conditions on rows.
  5288.  HAVING should only be used with GROUP BY.
  5289.  
  5290.  HAVING search conditions are identical to WHERE search conditions with one
  5291.  exception: WHERE search conditions cannot include aggregate functions, while
  5292.  HAVING search conditions often do. HAVING clauses can reference any of the
  5293.  items that appear in the select list. There is no limit on the number of
  5294.  conditions that can be included in a HAVING clause.
  5295.  
  5296.  The following statement is an example of a HAVING clause with an aggregate
  5297.  function. It groups the rows in the titles table by type but eliminates the
  5298.  groups that include only one book:
  5299.  
  5300.    select type
  5301.     from titles
  5302.     group by type
  5303.     having count(*) > 1
  5304.  
  5305.     type
  5306.     ------------
  5307.     business
  5308.     mod_cook
  5309.     popular_comp
  5310.     psychology
  5311.     trad_cook
  5312.  
  5313.     (5 rows affected)
  5314.  
  5315.  Here's an example of a HAVING clause without aggregate functions. It groups
  5316.  the titles table by type and eliminates those types that do not start with
  5317.  the letter "p":
  5318.  
  5319.    select type
  5320.     from titles
  5321.     group by type
  5322.     having type like 'p%'
  5323.  
  5324.     type
  5325.     ------------
  5326.     popular_comp
  5327.     psychology
  5328.  
  5329.     (2 rows affected)
  5330.  
  5331.  When more than one condition is included in the HAVING clause, they are
  5332.  combined with AND, OR, or NOT. For example, say you want to group the titles
  5333.  table by publishers, including only those groups of publishers with
  5334.  identification numbers greater than 0800. These publishers have paid more
  5335.  than $15,000 in total advances and sell books for less than $20 on the
  5336.  average. Type
  5337.  
  5338.  select pub_id, sum(advance), avg(price)
  5339.  
  5340.  from titles
  5341.  
  5342.  group by pub_id
  5343.  
  5344.  having sum(advance) > 15000
  5345.  
  5346.  and avg(price) < 20
  5347.  
  5348.  and pub_id > "0800"
  5349.  
  5350.  
  5351.  
  5352.  pub_id
  5353.  
  5354.  --------------------
  5355.  
  5356.  087741,000.0015.41
  5357.  
  5358.  138930,000.0018.98
  5359.  
  5360.  
  5361.  
  5362.  (2 rows affected)
  5363.  
  5364.  The following statement illustrates the use of GROUP BY, HAVING, WHERE and
  5365.  ORDER BY clauses in one SELECT statement. It produces the same groups and
  5366.  summary values as the previous example but does so after eliminating the
  5367.  titles with prices under $5. It also organizes the results by pub_id:
  5368.  
  5369.  select pub_id, sum(advance), avg(price)
  5370.  
  5371.  from titles
  5372.  
  5373.  where price >=5
  5374.  
  5375.  group by pub_id
  5376.  
  5377.  having sum(advance) > 15000
  5378.  
  5379.  and avg(price) < 20
  5380.  
  5381.  and pub_id > "0800"
  5382.  
  5383.  order by pub_id
  5384.  
  5385.  
  5386.  
  5387.  pub_id
  5388.  
  5389.  ---------------------
  5390.  
  5391.  087726,000.0017.89
  5392.  
  5393.  138930,000.0018.98
  5394.  
  5395.  
  5396.  
  5397.  (2 rows affected)
  5398.  
  5399.  
  5400.  The COMPUTE Clause
  5401.  
  5402.  The COMPUTE clause is used in SELECT statements with row aggregate
  5403.  functions─SUM, AVG, MIN, MAX, and COUNT─to generate summary values based on
  5404.  the values in groups of rows.
  5405.  
  5406.  These summary values appear as new rows in the query results, allowing you
  5407.  to see both detail and summary rows in one set of results. (Compare this to
  5408.  results from aggregate functions and the GROUP BY clause, which appear as
  5409.  new columns.)
  5410.  
  5411.  The results of a query that includes a COMPUTE clause are like a
  5412.  control-break report, which is a report whose summary values are controlled
  5413.  by the groupings ("breaks") that you specify. You can produce summary values
  5414.  for groups, and you can calculate more than one aggregate function for the
  5415.  same group.
  5416.  
  5417.  Here's how to use the COMPUTE clause to calculate the sum for the prices of
  5418.  the different types of cookbooks:
  5419.  
  5420.  select type, price
  5421.  
  5422.  from titles
  5423.  
  5424.  where type like "%cook"
  5425.  
  5426.  order by type, price
  5427.  
  5428.  compute sum(price) by type
  5429.  
  5430.  
  5431.  
  5432.  typeprice
  5433.  
  5434.  --------------------
  5435.  
  5436.  mod_cook2.99
  5437.  
  5438.  mod_cook19.99
  5439.  
  5440.  sum
  5441.  
  5442.  
  5443.  
  5444.  ------------
  5445.  
  5446.  22.98
  5447.  
  5448.  
  5449.  
  5450.  typeprice
  5451.  
  5452.  ---------------------
  5453.  
  5454.  trad_cook11.95
  5455.  
  5456.  trad_cook14.99
  5457.  
  5458.  trad_cook20.95
  5459.  
  5460.  sum
  5461.  
  5462.  ------------
  5463.  
  5464.  47.89
  5465.  
  5466.  
  5467.  
  5468.  (7 rows affected)
  5469.  
  5470.  Notice that the summary values appear as new rows in the results, labeled
  5471.  with the word "sum," and that all the detail rows are also included.
  5472.  
  5473.  The same summary information could be produced with this statement:
  5474.  
  5475.  select type, sum(price)
  5476.  
  5477.  from titles
  5478.  
  5479.  where type like "%cook"
  5480.  
  5481.  group by type
  5482.  
  5483.  
  5484.  
  5485.  type
  5486.  
  5487.  ---------------
  5488.  
  5489.  mod_cook22.98
  5490.  
  5491.  trad_cook47.89
  5492.  
  5493.  
  5494.  
  5495.  (2 rows affected)
  5496.  
  5497.  With GROUP BY, detail rows are not shown, and the summary values are
  5498.  displayed as new columns.
  5499.  
  5500.  
  5501.  COMPUTE Syntax
  5502.  
  5503.  The COMPUTE clause has the following syntax:
  5504.  
  5505.    [COMPUTE row_aggregate(column_name)
  5506.     [, row_aggregate(column_name)...]
  5507.     [BY column_name [, column_name...]]]
  5508.  
  5509.  See the SQL Server Language Reference for the complete syntax of the SELECT
  5510.  statement.
  5511.  
  5512.  ────────────────────────────────────────────────────────────────────────────
  5513.  NOTE
  5514.  You cannot include text or image datatypes in a COMPUTE or COMPUTE BY
  5515.  clause.
  5516.  ────────────────────────────────────────────────────────────────────────────
  5517.  
  5518.  
  5519.  Row Aggregate Functions
  5520.  
  5521.  The row aggregate functions used with COMPUTE are as follows:
  5522.  
  5523.  
  5524. ╓┌─────────────────────────────────┌─────────────────────────────────────────
  5525.  Row Aggregate Function            Result
  5526.  ────────────────────────────────────────────────────────────────────────────
  5527.  SUM                               Total of the values in the numeric column
  5528.  
  5529.  AVG                               Average of the values in the numeric
  5530.                                    column
  5531.  
  5532.  MAX                               Highest value in the expression
  5533.  
  5534.  MIN                               Lowest value in the expression
  5535.  
  5536.  COUNT                             Number of selected rows
  5537.  
  5538.  ────────────────────────────────────────────────────────────────────────────
  5539.  
  5540.  
  5541.  
  5542.  These row aggregate functions are the same aggregate functions that can be
  5543.  used with GROUP BY except that there is no row aggregate function equivalent
  5544.  to COUNT(*). To find the summary information produced by GROUP BY and
  5545.  COUNT(*), use a COMPUTE clause without BY.
  5546.  
  5547.  
  5548.  Rules for COMPUTE Clauses
  5549.  
  5550.  
  5551.    ■   The DISTINCT keyword is not allowed with row aggregate functions.
  5552.  
  5553.    ■   The columns in a COMPUTE clause must appear in the statement's select
  5554.        list.
  5555.  
  5556.    ■   You cannot use SELECT INTO in the same statement as a COMPUTE clause
  5557.        because statements that include COMPUTE do not generate normal rows.
  5558.  
  5559.    ■   If you use COMPUTE BY, you must also use an ORDER BY clause. The
  5560.        columns listed after COMPUTE BY must be identical to or a subset of
  5561.        those listed after ORDER BY, and must be in the same left-to-right
  5562.        order, start with the same expression, and not skip any expressions.
  5563.  
  5564.        For example, if the ORDER BY clause is
  5565.  
  5566.        order by a, b, c
  5567.  
  5568.        The COMPUTE BY clause can be any of these:
  5569.  
  5570.        compute row_aggregate (column_name) by a, b, c
  5571.         compute row_aggregate (column_name) by a, b
  5572.         compute row_aggregate (column_name) by a
  5573.  
  5574.        The COMPUTE BY clause cannot be any of these:
  5575.  
  5576.        compute row_aggregate (column_name) by b, c
  5577.         compute row_aggregate (column_name) by a, c
  5578.         compute row_aggregate (column_name) by c
  5579.  
  5580.    ■   You must use a column name or an expression in the ORDER BY clause;
  5581.        you cannot sort by a column heading.
  5582.  
  5583.    ■   The COMPUTE keyword can be used without BY to generate grand totals,
  5584.        grand counts, and so on. ORDER BY is optional if you use the COMPUTE
  5585.        keyword without BY. COMPUTE without BY is discussed later.
  5586.  
  5587.  
  5588.  
  5589.  More Than One Column after COMPUTE BY
  5590.  
  5591.  Listing more than one column after the keyword BY breaks a group into
  5592.  subgroups and applies the specified row aggregate function at each level of
  5593.  grouping. For example, the following query finds the sum of the prices of
  5594.  psychology books from each publisher:
  5595.  
  5596.  select type, pub_id, price
  5597.  
  5598.  from titles
  5599.  
  5600.  where type = "psychology"
  5601.  
  5602.  order by type, pub_id, price
  5603.  
  5604.  compute sum(price) by type, pub_id
  5605.  
  5606.  
  5607.  
  5608.  typepub_idprice
  5609.  
  5610.  ----------------------------
  5611.  
  5612.  psychology07367.00
  5613.  
  5614.  psychology07367.99
  5615.  
  5616.  psychology073610.95
  5617.  
  5618.  psychology073619.99
  5619.  
  5620.  sum
  5621.  
  5622.  ------------
  5623.  
  5624.  45.93
  5625.  
  5626.  
  5627.  
  5628.  typepub_idprice
  5629.  
  5630.  ----------------------------
  5631.  
  5632.  psychology087721.59
  5633.  
  5634.  sum
  5635.  
  5636.  ------------
  5637.  
  5638.  21.59
  5639.  
  5640.  
  5641.  
  5642.  (7 rows affected)
  5643.  
  5644.  
  5645.  Using More Than One COMPUTE Clause
  5646.  
  5647.  You can use different aggregate functions in the same statement by including
  5648.  more than one COMPUTE BY clause. Here's a query similar to the preceding
  5649.  one. It finds the sum of the prices of all psychology books, as well as the
  5650.  sum of the prices of psychology books by publisher:
  5651.  
  5652.  select type, pub_id, price
  5653.  
  5654.  from titles
  5655.  
  5656.  where type = "psychology"
  5657.  
  5658.  order by type, pub_id, price
  5659.  
  5660.  compute sum(price) by type, pub_id
  5661.  
  5662.  compute sum(price) by type
  5663.  
  5664.  
  5665.  
  5666.  typepub_idprice
  5667.  
  5668.  --------------------------
  5669.  
  5670.  psychology07367.00
  5671.  
  5672.  psychology07367.99
  5673.  
  5674.  psychology073610.95
  5675.  
  5676.  psychology073619.99
  5677.  
  5678.  sum
  5679.  
  5680.  ----------
  5681.  
  5682.  45.93
  5683.  
  5684.  
  5685.  
  5686.  typepub_idprice
  5687.  
  5688.  ---------------- ---------
  5689.  
  5690.  psychology087721.59
  5691.  
  5692.  
  5693.  
  5694.  sum
  5695.  
  5696.  ---------
  5697.  
  5698.  21.59
  5699.  
  5700.  sum
  5701.  
  5702.  ---------
  5703.  
  5704.  67.52
  5705.  
  5706.  
  5707.  
  5708.  (8 rows affected)
  5709.  
  5710.  
  5711.  Applying an Aggregate to More Than One Column
  5712.  
  5713.  One COMPUTE BY clause can apply the same aggregate function to several
  5714.  columns. This query finds the sum of the prices and advances for each type
  5715.  of cookbook:
  5716.  
  5717.  select type, price, advance
  5718.  
  5719.  from titles
  5720.  
  5721.  where type like "%cook"
  5722.  
  5723.  order by type
  5724.  
  5725.  compute sum(price), sum(advance) by type
  5726.  
  5727.  
  5728.  
  5729.  typepriceadvance
  5730.  
  5731.  --------------------------------
  5732.  
  5733.  mod_cook2.9915,000.00
  5734.  
  5735.  , mod_cook, 19.99, 0.00,
  5736.  
  5737.  sumsum
  5738.  
  5739.  ------------------------
  5740.  
  5741.  22.9815,000.00
  5742.  
  5743.  
  5744.  
  5745.  typepriceadvance
  5746.  
  5747.  ---------------------------------
  5748.  
  5749.  trad_cook11.954,000.00
  5750.  
  5751.  trad_cook14.998,000.00
  5752.  
  5753.  trad_cook20.957,000.00
  5754.  
  5755.  sumsum
  5756.  
  5757.  ------------------------
  5758.  
  5759.  47.8919,000.00
  5760.  
  5761.  
  5762.  
  5763.  (7 rows affected)
  5764.  
  5765.  Remember, the columns to which the aggregate functions apply must also be in
  5766.  the select list.
  5767.  
  5768.  
  5769.  Using Different Aggregate Functions in the Same COMPUTE BY Clause
  5770.  
  5771.  You can use different aggregate functions in the same COMPUTE BY clause:
  5772.  
  5773.  select type, pub_id, price
  5774.  
  5775.  from titles
  5776.  
  5777.  where type like "%cook"
  5778.  
  5779.  order by type, pub_id
  5780.  
  5781.  compute sum(price), max(pub_id) by type
  5782.  
  5783.  
  5784.  
  5785.  typepub_idprice
  5786.  
  5787.  --------------------------
  5788.  
  5789.  mod_cook08772.99
  5790.  
  5791.  mod_cook087719.99
  5792.  
  5793.  sum
  5794.  
  5795.  ------------
  5796.  
  5797.  22.98
  5798.  
  5799.  
  5800.  
  5801.  max
  5802.  
  5803.  -----
  5804.  
  5805.  0877
  5806.  
  5807.  
  5808.  
  5809.  typepub_idprice
  5810.  
  5811.  ---------------------------
  5812.  
  5813.  trad_cook087711.95
  5814.  
  5815.  trad_cook087714.99
  5816.  
  5817.  trad_cook087720.95
  5818.  
  5819.  sum
  5820.  
  5821.  ------------
  5822.  
  5823.  47.89
  5824.  
  5825.  max
  5826.  
  5827.  ----
  5828.  
  5829.  0877
  5830.  
  5831.  
  5832.  
  5833.  (7 rows affected)
  5834.  
  5835.  
  5836.  Grand Values: COMPUTE without BY
  5837.  
  5838.  The COMPUTE keyword can be used without BY to generate grand totals, grand
  5839.  counts, and so on.
  5840.  
  5841.  This statement finds the grand total of the prices and advances for all
  5842.  types of books over $20:
  5843.  
  5844.  select type, price,, advance
  5845.  
  5846.  from titles
  5847.  
  5848.  where price > $20
  5849.  
  5850.  compute sum(price), sum(advance)
  5851.  
  5852.  
  5853.  
  5854.  typepriceadvance
  5855.  
  5856.  ------------------------------------
  5857.  
  5858.  popular_comp22.957,000.00
  5859.  
  5860.  psychology21.597,000.00
  5861.  
  5862.  trad_cook20.957,000.00
  5863.  
  5864.  sumsum
  5865.  
  5866.  ------------------------
  5867.  
  5868.  65.4921,000.00
  5869.  
  5870.  
  5871.  
  5872.  (4 rows affected)
  5873.  
  5874.  You can use COMPUTE BY and COMPUTE without BY in the same query. The
  5875.  following query finds the sum of prices and advances by type, and then
  5876.  computes the grand total of prices and advances for all types of books:
  5877.  
  5878.  select type, price, advance
  5879.  
  5880.  from titles
  5881.  
  5882.  where type like "%cook"
  5883.  
  5884.  order by type
  5885.  
  5886.  compute sum(price), sum(advance) by type
  5887.  
  5888.  compute sum(price), sum(advance)
  5889.  
  5890.  
  5891.  
  5892.  typepriceadvance
  5893.  
  5894.  --------------------------------
  5895.  
  5896.  mod_cook2.9915,000.00
  5897.  
  5898.  mod_cook19.990.00
  5899.  
  5900.  sumsum
  5901.  
  5902.  ------------------------
  5903.  
  5904.  22.9815,000.00
  5905.  
  5906.  
  5907.  
  5908.  typepriceadvance
  5909.  
  5910.  ---------------------------------
  5911.  
  5912.  trad_cook11.954,000.00
  5913.  
  5914.  trad_cook14.998,000.00
  5915.  
  5916.  trad_cook20.957,000.00
  5917.  
  5918.  sumsum
  5919.  
  5920.  ------------------------
  5921.  
  5922.  47.8919,000.00
  5923.  
  5924.  sumsum
  5925.  
  5926.  ------------------------
  5927.  
  5928.  70.8734,000.00
  5929.  
  5930.  
  5931.  
  5932.  (8 rows affected)
  5933.  
  5934.  
  5935.  
  5936.  
  5937.  
  5938.  
  5939.  Chapter 5  Using Built-In Functions
  5940.  ────────────────────────────────────────────────────────────────────────────
  5941.  
  5942.  
  5943.  Introduction
  5944.  
  5945.  SQL Server provides a variety of built-in functions. They can be divided
  5946.  into the following categories:
  5947.  
  5948.  
  5949.    ■   System functions, most of which return information from the system
  5950.        tables
  5951.  
  5952.    ■   String functions for manipulating char, varchar, binary, and varbinary
  5953.        values
  5954.  
  5955.    ■   Text functions for manipulating text values
  5956.  
  5957.    ■   Mathematical functions for trigonometry, geometry, and other number
  5958.        handling
  5959.  
  5960.    ■   Date functions for manipulating datetime values
  5961.  
  5962.    ■   Conversion function (CONVERT) for converting expressions from one
  5963.        datatype to another and for formatting dates in a wide variety of
  5964.        styles
  5965.  
  5966.  
  5967.  
  5968.  System Functions
  5969.  
  5970.  System functions return special information from the database. Many of them
  5971.  provide a shorthand way of querying the system tables.
  5972.  
  5973.  System functions have the following syntax:
  5974.  
  5975.    select function_name(parameter[s])
  5976.  
  5977.  The system functions can be used in the select list, in the WHERE clause,
  5978.  and anywhere an expression is allowed.
  5979.  
  5980.  For example, to find the user identification number of your coworker who
  5981.  logs in as harold, type
  5982.  
  5983.    select user_id("harold")
  5984.  
  5985.  Assuming that harold's user ID is 13, the result is
  5986.  
  5987. ╓┌─────────────────────────────────┌─────────────────────────────────────────╖
  5988.  ────────────────────────────────────────────────────────────────────────────
  5989.                                    ------------
  5990.  
  5991.                                    13
  5992.  
  5993.                                    (1 row affected)
  5994.  
  5995.  
  5996.  
  5997.  Generally, as in this example, the name of the function tells you what kind
  5998.  of information will be returned.
  5999.  
  6000.  The USER_NAME system function takes an ID number as its parameter and
  6001.  returns the user's name:
  6002.  
  6003.    select username(13)
  6004.  
  6005.     ---------
  6006.     harold
  6007.  
  6008.     (1 row affected)
  6009.  
  6010.  To find the name of the current user (that is, your name), the parameter is
  6011.  omitted:
  6012.  
  6013.    select username()
  6014.  
  6015.     ------
  6016.     dbo
  6017.  
  6018.     (1 row affected)
  6019.  
  6020.  Note that the System Administrator's server user ID is always 1 and that a
  6021.  guest user is always given the server user ID - 1. Inside a database, the
  6022.  USER_NAME of the Database Owner is always dbo, with a user ID of 1. Inside a
  6023.  database, the guest user's ID (uid) is always 2. The System Administrator is
  6024.  treated as the Database Owner inside a user database. Built-in functions are
  6025.  always used with parentheses even if the parameter is NULL.
  6026.  
  6027.  This list gives the name of each system function, the parameter it takes,
  6028.  and the result it returns:
  6029.  
  6030. ╓┌────────────┌────────────────────────────────┌─────────────────────────────
  6031.  Function     Parameters                       Result
  6032.  ────────────────────────────────────────────────────────────────────────────
  6033.  COL_NAME     (object ID #, column ID #)       Returns the column name
  6034.  
  6035.  COL_LENGTH   ("object name", "column name")   Returns the column length
  6036.  
  6037.  DB_ID        (["database name"])              Returns the database ID #
  6038.  
  6039.  DB_NAME      ([database ID #])                Returns the database name
  6040.  
  6041.  HOST_ID      ( )                              Returns the host process ID #
  6042.  
  6043.  HOST_NAME    ( )                              Returns the current host
  6044.                                                computer name
  6045.  
  6046.  INDEX_COL    ("object name", index ID #, key  Returns the indexed column name
  6047.               #)
  6048.  
  6049.  ISNULL       (expression, value)              Returns the substitutes for the
  6050.  Function     Parameters                       Result
  6051.  ────────────────────────────────────────────────────────────────────────────
  6052. ISNULL       (expression, value)              Returns the substitutes for the
  6053.                                                specified value for NULL
  6054.                                                entries
  6055.  
  6056.  OBJECT_ID    ("database object name")         Returns the database object ID
  6057.                                                #
  6058.  
  6059.  OBJECT_NAME  (database object ID #)           Returns the database object
  6060.                                                name
  6061.  
  6062.  SUSER_ID     (["server user name"])           Returns the server user's ID #
  6063.  
  6064.  SUSER_NAME   ([server user ID #])             Returns the server user's name
  6065.  
  6066.  USER_ID      (["user name"])                  Returns the user's ID number
  6067.  
  6068.  USER_NAME    ([user ID number])               Returns the user's name
  6069.  
  6070.  ────────────────────────────────────────────────────────────────────────────
  6071.  Function     Parameters                       Result
  6072.  ────────────────────────────────────────────────────────────────────────────
  6073. ────────────────────────────────────────────────────────────────────────────
  6074.  
  6075.  
  6076.  
  6077.  When the parameter to a system function is optional, the current database,
  6078.  host computer, server user, or database user is assumed.
  6079.  
  6080.  
  6081.  
  6082.  
  6083.  System Function Examples
  6084.  
  6085.  
  6086.    1.  This query finds the length of the title column in the titles table:
  6087. ╓┌─────────────────────────────────┌─────────────────────────────────────────
  6088.  ────────────────────────────────────────────────────────────────────────────
  6089.                                    select x = col_length("titles", "title")
  6090.  
  6091.                                    x
  6092.  ────────────────────────────────────────────────────────────────────────────
  6093.                                   x
  6094.  
  6095.                                    ------------
  6096.  
  6097.                                    80
  6098.  
  6099.                                    (1 row affected)
  6100.  
  6101.  
  6102.  
  6103.  The "x =" in the preceding statement is included to give some column heading
  6104.  to the result.
  6105.  
  6106.    2.  This query finds the average of the prices of all titles, substituting
  6107.        the value "$10.00" for all NULL entries in price:
  6108.  
  6109.        select avg(isnull(price,$10.00))
  6110.         from titles
  6111.  
  6112.  
  6113.    3.  This query finds all rows in sysusers where the name is equal to the
  6114.        result of applying the system function USER_NAME to user ID 1:
  6115.  
  6116.        select name
  6117.         from sysusers
  6118.         where name = username(1)
  6119.  
  6120.         name
  6121.         ------------
  6122.         dbo
  6123.  
  6124.         (1 row affected)
  6125.  
  6126.  
  6127.  
  6128.  
  6129.  String Functions
  6130.  
  6131.  String functions are used for various operations on binary data, character
  6132.  strings, or expressions.
  6133.  
  6134.  String functions return values commonly needed for operations on character
  6135.  data. String function names are not keywords.
  6136.  
  6137.  String functions have the following syntax:
  6138.  
  6139.    select function_name(parameters)
  6140.  
  6141.  You can concatenate binary or character expressions like this:
  6142.  
  6143.    (expression + expression [+ expression]...)
  6144.  
  6145.  The string functions and concatenation can be used on char, varchar, binary,
  6146.  and varbinary datatypes only. In addition, the REPLICATE and RIGHT string
  6147.  functions can be used on datetime datatypes.
  6148.  
  6149.  String functions can be nested, and they can be used anywhere an expression
  6150.  is allowed. When you use constants with a string function, enclose them in
  6151.  single or double quotation marks.
  6152.  
  6153.  Function names, parameters, and results are listed in the following table:
  6154.  
  6155.  
  6156.  
  6157. ╓┌───────────┌─────────────────────────────────┌─────────────────────────────
  6158.  Function    Parameters                        Result
  6159.  ────────────────────────────────────────────────────────────────────────────
  6160.  ASCII       (char_expr)                       The ASCII code value of the
  6161.                                                leftmost character in a
  6162.                                                character expression.
  6163.  
  6164.  CHAR        (integer_expr)                    A character converted from an
  6165.                                                ASCII code. The ASCII code
  6166.                                                should be between 0 and 255;
  6167.                                                otherwise, NULL is returned.
  6168.  
  6169.  CHARINDEX   ("Pattern", expression)           The starting position of the
  6170.                                                specified pattern. The first
  6171.                                                parameter is the pattern. The
  6172.                                                second parameter is an
  6173.                                                expression, usually a column
  6174.                                                name, in which SQL Server
  6175.                                                searches for the pattern. Not
  6176.  Function    Parameters                        Result
  6177.  ────────────────────────────────────────────────────────────────────────────
  6178.                                               searches for the pattern. Not
  6179.                                                implemented for text and image
  6180.                                                data.
  6181.  
  6182.  DATALENGTH  (char_expr)                       The length of any type of data
  6183.                                                value. A NULL string returns a
  6184.                                                length of 1.
  6185.  
  6186.  DIFFERENCE  (char_expr1, char_expr2)          The difference between the
  6187.                                                values of two character
  6188.                                                expressions as returned by the
  6189.                                                SOUNDEX function.
  6190.  
  6191.  LOWER       (char_expr)                       Lowercase converted from
  6192.                                                uppercase.
  6193.  
  6194.  LTRIM       (char_expr)                       Data without leading blanks.
  6195.  
  6196.  REPLICATE   (char_expr, integer_expr)         A character expression repeated
  6197.  Function    Parameters                        Result
  6198.  ────────────────────────────────────────────────────────────────────────────
  6199. REPLICATE   (char_expr, integer_expr)         A character expression repeated
  6200.                                                a specified number of times. If
  6201.                                                integer_expr is negative, a NUL
  6202.                                                string is returned.
  6203.  
  6204.  RIGHT       (char_expr, integer_expr)         Part of a character string
  6205.                                                starting integer_expr character
  6206.                                                from the right. If integer_expr
  6207.                                                is negative, a NULL string is
  6208.                                                returned.
  6209.  
  6210.  RTRIM       (char_expr)                       Data without trailing blanks.
  6211.  
  6212.  SOUNDEX     (char_expr)                       A 4-digit (SOUNDEX) code for us
  6213.                                                in evaluating the similarity of
  6214.                                                two strings.
  6215.  
  6216.  SPACE       (integer_expr)                    A string of repeated spaces. Th
  6217.                                                number of spaces is equal to
  6218.  Function    Parameters                        Result
  6219.  ────────────────────────────────────────────────────────────────────────────
  6220.                                               number of spaces is equal to
  6221.                                                integer_expr. If integer_expr i
  6222.                                                negative, a NULL string is
  6223.                                                returned.
  6224.  
  6225.  STR         (float_expr                       Character data converted from
  6226.              [, length [, decimal]])            numeric data. The length is th
  6227.                                                total length, including decimal
  6228.                                                point, sign, digits, and spaces
  6229.                                                The decimal value is the number
  6230.                                                of spaces to the right of the
  6231.                                                decimal.
  6232.  
  6233.  STUFF       (char_expr1, start, length,       Data with length characters
  6234.              char_expr2)                       deleted from char_expr1 at star
  6235.                                                and char_expr2 inserted into
  6236.                                                char_expr1 at start. Not
  6237.                                                implemented for text data.
  6238.  
  6239.  Function    Parameters                        Result
  6240.  ────────────────────────────────────────────────────────────────────────────
  6241. 
  6242.  SUBSTRING   (expression, start, length)       Part of a character or binary
  6243.                                                string. The first parameter can
  6244.                                                be a character or binary string
  6245.                                                a column name, or an expression
  6246.                                                that includes a column name. (D
  6247.                                                not use expressions that includ
  6248.                                                functions or subqueries.) The
  6249.                                                second parameter specifies the
  6250.                                                position at which the substring
  6251.                                                begins. The third parameter
  6252.                                                specifies the number of
  6253.                                                characters in the substring. No
  6254.                                                implemented for text data.
  6255.  
  6256.  UPPER       (char_expr)                       Uppercase converted from
  6257.                                                lowercase.
  6258.  
  6259.  ++                                            The + option indicates two or
  6260.  Function    Parameters                        Result
  6261.  ────────────────────────────────────────────────────────────────────────────
  6262. ++                                            The + option indicates two or
  6263.                                                more concatenated character
  6264.                                                strings, binary strings, column
  6265.                                                names, or a combination of them
  6266.                                                Enclose character strings in
  6267.                                                single or double quotation
  6268.                                                marks.
  6269.  
  6270.  ────────────────────────────────────────────────────────────────────────────
  6271.  
  6272.  
  6273.  
  6274.  The following sections provide examples using string functions.
  6275.  
  6276.  
  6277.  SUBSTRING
  6278.  
  6279.  This example illustrates the SUBSTRING function. It displays the last name
  6280.  and first initial of each author, for example, Bennet A.
  6281.  
  6282.    select au_lname, substring(au_fname, 1, 1)
  6283.     from authors
  6284.  
  6285.  The SUBSTRING function does what its name implies─it returns a portion of a
  6286.  character or binary string.
  6287.  
  6288.  The SUBSTRING function always takes three parameters. The first can be a
  6289.  character or binary string, a column name, or a string-valued expression
  6290.  that includes a column name. The second parameter specifies the position at
  6291.  which the substring should begin. The third specifies the length (in number
  6292.  of characters) of the string to be returned.
  6293.  
  6294.  The SUBSTRING function has the following syntax:
  6295.  
  6296.    substring(expression, start, length)
  6297.  
  6298.  For example, here's how to take the second, third, and fourth characters of
  6299.  the string constant "abcdef":
  6300.  
  6301.    select x = substring("abcdef", 2, 3)
  6302.  
  6303.     x
  6304.     ----------
  6305.     bcd
  6306.  
  6307.  
  6308.  CHARINDEX
  6309.  
  6310.  The CHARINDEX function returns the starting position of a pattern you
  6311.  specify. It takes two parameters. The first is the pattern whose position
  6312.  you want. The pattern is a literal string that does not contain wildcard
  6313.  characters. The second parameter is a string-valued expression, usually a
  6314.  column name, in which SQL Server searches for the specified pattern.
  6315.  
  6316.  The CHARINDEX function has the following syntax:
  6317.  
  6318.    charindex("pattern", expression)
  6319.  
  6320.  To find the position at which the pattern "wonderful" begins in a certain
  6321.  row of the notes column in the titles table, type
  6322.  
  6323. ╓┌─────────────────────────────────┌─────────────────────────────────────────
  6324.  ────────────────────────────────────────────────────────────────────────────
  6325.                                    select charindex("wonderful", notes)
  6326.  
  6327.                                    from titles
  6328.  
  6329.                                    where title_id = "TC3218"
  6330.  
  6331.                                    ------------
  6332.  
  6333.                                    46
  6334.  
  6335.                                    (1 row affected)
  6336.  
  6337.  
  6338.  
  6339.  If you do not restrict the rows to be searched, the query returns all rows
  6340.  in the table and reports non-zero values for those rows in which the pattern
  6341.  was found.
  6342.  
  6343.  
  6344.  STR
  6345.  
  6346.  The STR function converts numbers to characters, with optional parameters
  6347.  for specifying the length of the integral (the part of the number before the
  6348.  decimal point) and the number of places after the decimal point.
  6349.  
  6350.  Length and decimal parameters to STR (if supplied) should be positive. The
  6351.  default length is 10. The number is rounded to an integer by default or if
  6352.  the decimal parameter is 0. The specified length should be at least equal to
  6353.  or greater than the part of the number before the decimal point plus the
  6354.  number's sign (if any). If the expression exceeds the specified length, the
  6355.  string returns "**" of the specified length. For example:
  6356.  
  6357.    select str(123.45, 2, 2)
  6358.  
  6359.     --
  6360.     **
  6361.  
  6362.     (1 row affected)
  6363.  
  6364.  A short expression is right justified in the specified length, and a long
  6365.  expression is truncated to the specified number of decimal places.
  6366.  
  6367.  
  6368.  STUFF
  6369.  
  6370.  The STUFF function inserts a string into another string. It deletes a
  6371.  specified length of characters in the first string at the start position. It
  6372.  then inserts the second string into the first string at the start position.
  6373.  If the start position or the length is negative, a NULL string is returned.
  6374.  
  6375.  
  6376.  If the start position is longer than the first string, a NULL string is
  6377.  returned. If the length to delete is longer than the first string, it is
  6378.  deleted to the first character in the first string. For example:
  6379.  
  6380.    select stuff("abc", 2, 3, "xyz")
  6381.  
  6382.     ----
  6383.     axyz
  6384.  
  6385.     (1 row affected)
  6386.  
  6387.  
  6388.  Testing Similarity of Patterns: SOUNDEX and DIFFERENCE
  6389.  
  6390.  The SOUNDEX function converts a character string to a 4-digit code for use
  6391.  in a comparison. Nonalphabetic characters are used to terminate the
  6392.  compression. This function always returns some value.
  6393.  
  6394.  The DIFFERENCE function compares the SOUNDEX values of two strings and
  6395.  evaluates the similarity between them, returning a value from 0 to 4. Four
  6396.  is the best match. For example:
  6397.  
  6398. ╓┌─────────────────────────────────┌─────────────────────────────────────────╖
  6399.  ────────────────────────────────────────────────────────────────────────────
  6400.                                    select difference("abc", "abc")
  6401.  
  6402.                                    ------------
  6403.  
  6404.                                    4
  6405.  
  6406.                                    (1 row affected)
  6407.  ────────────────────────────────────────────────────────────────────────────
  6408.                                   (1 row affected)
  6409.  
  6410.                                    select difference("abc", "abd")
  6411.  
  6412.                                    ------------
  6413.  
  6414.                                    3
  6415.  
  6416.                                    (1 row affected)
  6417.  
  6418.  
  6419.  
  6420.  Most of the remaining string functions are easy to use and to understand.
  6421.  For example:
  6422.  
  6423.    Statement       Result
  6424.  
  6425.     select right("abcde", 3)   cde
  6426.     select right("abcde", 6)   abcde
  6427.     select str(123.45, 6, 2)   123.45
  6428.     select stuff("abc", 2, 1, "xyz") axyzc
  6429.  
  6430.  
  6431.  Concatenation
  6432.  
  6433.  You can concatenate binary or character expressions, combining two or more
  6434.  character or binary strings, character or binary data, or a combination of
  6435.  them.
  6436.  
  6437.  If you're concatenating a character string, enclose it in single or double
  6438.  quotation marks.
  6439.  
  6440.  Concatenation has the following syntax:
  6441.  
  6442.    (expression + expression [+ expression]...)
  6443.  
  6444.  Here's how you'd combine two character strings:
  6445.  
  6446.    select ("abc" + "def")
  6447.  
  6448.     ------
  6449.     abcdef
  6450.  
  6451.     (1 row affected)
  6452.  
  6453.  This query displays California author names under the column heading Moniker
  6454.  in last-name, first-name order with a comma and space after the last name:
  6455.  
  6456.    select Moniker = (au_lname + ", " + au_fname)
  6457.     from authors
  6458.     where state = "CA"
  6459.  
  6460.     Moniker
  6461.     -------------------------
  6462.     White, Johnson
  6463.     Green, Marjorie
  6464.     Carson, Cheryl
  6465.     O'Leary, Michael
  6466.     Straight, Dick
  6467.     Bennet, Abraham
  6468.     Dull, Ann
  6469.     Gringlesby, Burt
  6470.     Locksley, Chastity
  6471.     Yokomoto, Akiko
  6472.     Stringer, Dirk
  6473.     MacFeather, Stearns
  6474.     Karsen, Livia
  6475.     Hunter, Sheryl
  6476.     McBadden, Heather
  6477.  
  6478.     (15 rows affected)
  6479.  
  6480.  
  6481.  Nested String Functions
  6482.  
  6483.  String functions can be nested. For example, to display the last name and
  6484.  the first initial of each author living in Oakland, with a comma after the
  6485.  last name and a period after the first name, type
  6486.  
  6487.    select (au_lname + "," + " " + substring(au_fname, 1, 1) + ".")
  6488.     from authors
  6489.     where city = "Oakland"
  6490.  
  6491.     ----------------------
  6492.     Green, M.
  6493.     Straight, D.
  6494.     Stringer, D.
  6495.     MacFeather, S.
  6496.     Karsen, L.
  6497.  
  6498.     (5 rows affected)
  6499.  
  6500.  To display the pub_id and the first two characters of each title_id for
  6501.  books over $20, type
  6502.  
  6503.    select substring(pub_id + title_id, 1, 6)
  6504.     from titles
  6505.     where price > $20
  6506.  
  6507.     -------
  6508.     1389PC
  6509.     0877PS
  6510.     0877TC
  6511.  
  6512.     (3 rows affected)
  6513.  
  6514.  
  6515.  Text and Image Functions
  6516.  
  6517.  Text functions are used for operations on text and image data. Text and
  6518.  image function names, parameters, and results are listed in the following
  6519.  table.
  6520.  
  6521.  
  6522. ╓┌─────────────┌───────────────────────────────────────────┌─────────────────
  6523.  Function      Parameters                                  Result
  6524.  ────────────────────────────────────────────────────────────────────────────
  6525.  PATINDEX      ("pattern", column_name)                    The starting positi
  6526.                                                            first occurrence of
  6527.                                                            the specified colum
  6528.                                                            use wildcard charac
  6529.                                                            pattern.
  6530.  
  6531.  SET TEXTSIZE  {n|0}                                       The limit in bytes
  6532.                                                            or image data to be
  6533.  Function      Parameters                                  Result
  6534.  ────────────────────────────────────────────────────────────────────────────
  6535.                                                           or image data to be
  6536.                                                            with a SELECT state
  6537.                                                            current setting is
  6538.                                                            the @TEXTSIZE globa
  6539.                                                            The integer n speci
  6540.                                                            limit on the number
  6541.                                                            be returned. 0 rest
  6542.                                                            default limit (32K
  6543.  
  6544.  TEXTPTR       (column_name)                               The text pointer va
  6545.                                                            varbinary format. T
  6546.                                                            is checked to ensur
  6547.                                                            to the first text p
  6548.  
  6549.  TEXTVALID     ("table_name.column_name",                  Returns 1 if the gi
  6550.                text_ptr)                                   pointer is valid an
  6551.                                                            pointer is invalid.
  6552.                                                            the identifier for
  6553.                                                            column must include
  6554.  Function      Parameters                                  Result
  6555.  ────────────────────────────────────────────────────────────────────────────
  6556.                                                           column must include
  6557.                                                            name.
  6558.  
  6559.  ────────────────────────────────────────────────────────────────────────────
  6560.  
  6561.  
  6562.  
  6563.  
  6564.  TEXTPTR
  6565.  
  6566.  This example uses the TEXTPTR function to locate the text column (blurb)
  6567.  associated with title_id BU7832 in table texttest. The text pointer (a long
  6568.  binary string) is put into a local variable @val and supplied as a parameter
  6569.  to the READTEXT statement, which returns 5 bytes starting at the second byte
  6570.  (offset of 1).
  6571.  
  6572.    declare @val varbinary(30)
  6573.     select @val = textptr(blurb) from texttest
  6574.     where title_id = "BU7832"
  6575.     readtext texttest.blurb @val 1 5
  6576.  
  6577.  Without using a local variable, a statement such as
  6578.  
  6579.    select textptr(text_col) from my_table
  6580.  
  6581.  returns a long binary string. It is a good idea to put this string into a
  6582.  local variable, as in the preceding example, and use it by reference.
  6583.  
  6584.  Explicit conversion using the CONVERT function is supported from text to
  6585.  varchar and from image to varbinary, but the text or image data is truncated
  6586.  to 255 bytes. Implicit conversion of text or image to another datatype is
  6587.  not supported.
  6588.  
  6589.  
  6590.  Mathematical Functions
  6591.  
  6592.  Mathematical functions return values commonly needed for operations on
  6593.  mathematical data.
  6594.  
  6595.  Mathematical functions have the following syntax:
  6596.  
  6597.    function_name(parameters)
  6598.  
  6599.  Function names, parameters, and results are listed in the following table.
  6600.  
  6601.  
  6602.  
  6603.  
  6604. ╓┌─────────┌──────────────────────────────────┌──────────────────────────────
  6605.  Function  Parameters                         Result
  6606.  ────────────────────────────────────────────────────────────────────────────
  6607.  ABS       (numeric_expr)                     An absolute value of a given
  6608.                                               expression. The expression can b
  6609.                                               of integer, float, or money type
  6610.                                               Results are of the same type as
  6611.                                               the numeric expression.
  6612.  
  6613.  ACOS      (float_expr)                       An angle (in radians) whose
  6614.                                               cosine is the specified
  6615.                                               floating-point value.
  6616.  
  6617.  Function  Parameters                         Result
  6618.  ────────────────────────────────────────────────────────────────────────────
  6619. 
  6620.  ASIN      (float_expr)                       An angle (in radians) whose sine
  6621.                                               is the specified floating-point
  6622.                                               value.
  6623.  
  6624.  ATAN      (float_expr)                       An angle (in radians) whose
  6625.                                               tangent is the specified
  6626.                                               floating-point value.
  6627.  
  6628.  ATN2      (float_expr1, float_expr2)         An angle (in radians) whose
  6629.                                               tangent is (
  6630.                                               float_expr1/float_expr2).
  6631.  
  6632.  CEILING   (numeric_expr)                     The smallest integer greater tha
  6633.                                               or equal to the specified value.
  6634.                                               The expression can be of integer
  6635.                                               float, or money type.  Results
  6636.                                               are of the same type as the
  6637.                                               numeric expression.
  6638.  Function  Parameters                         Result
  6639.  ────────────────────────────────────────────────────────────────────────────
  6640.                                              numeric expression.
  6641.  
  6642.  COS       (float_expr)                       The trigonometric cosine of the
  6643.                                               specified angle (in radians).
  6644.  
  6645.  COT       (float_expr)                       The trigonometric cotangent of
  6646.                                               the specified angle (in radians)
  6647.  
  6648.  DEGREES   (numeric_expr)                     Degrees converted from radians.
  6649.                                               The expression can be of integer
  6650.                                               float, or money type. Results ar
  6651.                                               of the same type as the numeric
  6652.                                               expression.
  6653.  
  6654.  EXP       (float_expr)                       The exponential value of the
  6655.                                               specified value.
  6656.  
  6657.  FLOOR     (numeric_expr)                     The largest integer less than or
  6658.                                               equal to the specified value. Th
  6659.  Function  Parameters                         Result
  6660.  ────────────────────────────────────────────────────────────────────────────
  6661.                                              equal to the specified value. Th
  6662.                                               expression can be of integer,
  6663.                                               float, or money type. Results ar
  6664.                                               of the same type as the numeric
  6665.                                               expression.
  6666.  
  6667.  LOG       (float_expr)                       The natural logarithm of the
  6668.                                               specified value.
  6669.  
  6670.  LOG10     (float_expr)                       The base 10 logarithm of the
  6671.                                               specified value.
  6672.  
  6673.  PI        ( )                                The constant value of
  6674.                                               3.1415926535897936.
  6675.  
  6676.  POWER     (numeric_expr, y)                  The value of numeric_expr to the
  6677.                                               power of y. The expression and y
  6678.                                               can be of integer, float, or
  6679.                                               money type. Results are of the
  6680.  Function  Parameters                         Result
  6681.  ────────────────────────────────────────────────────────────────────────────
  6682.                                              money type. Results are of the
  6683.                                               same type as numeric_expr.
  6684.  
  6685.  RADIANS   (numeric_expr)                     Radians converted from degrees.
  6686.                                               The expression can be of integer
  6687.                                               float, or money type. Results ar
  6688.                                               of the same type as numeric_expr
  6689.  
  6690.  RAND      ([int_expr])                       A random float number, using
  6691.                                               int_expr as the optional seed.
  6692.  
  6693.  ROUND     (numeric_expr, int_expr)           A numeric expression rounded off
  6694.                                               to the precision specified in
  6695.                                               int_expr. The expression can be
  6696.                                               of integer, float, or money type
  6697.                                               Results are of the same type as
  6698.                                               the numeric expression.
  6699.  
  6700.  SIGN      (numeric_expr)                     Positive (+1), zero (0), or
  6701.  Function  Parameters                         Result
  6702.  ────────────────────────────────────────────────────────────────────────────
  6703. SIGN      (numeric_expr)                     Positive (+1), zero (0), or
  6704.                                               negative (-1). The expression ca
  6705.                                               be of integer, float, or money
  6706.                                               type. Results are of the same
  6707.                                               type as the numeric expression.
  6708.  
  6709.  SIN       (float_expr)                       The trigonometric sine of the
  6710.                                               specified angle (measured in
  6711.                                               radians).
  6712.  
  6713.  SQRT      (float_expr)                       The square root of the specified
  6714.                                               value.
  6715.  
  6716.  TAN       (float_expr)                       The trigonometric tangent of the
  6717.                                               specified angle (measured in
  6718.                                               radians).
  6719.  
  6720.  ────────────────────────────────────────────────────────────────────────────
  6721.  
  6722.  Function  Parameters                         Result
  6723.  ────────────────────────────────────────────────────────────────────────────
  6724. 
  6725.  
  6726.  
  6727.  
  6728.  Examples of Mathematical Functions
  6729.  
  6730.  Mathematical functions operate on numeric data of integer, money, or float
  6731.  datatype. The precision of built-in operations on float datatype data is six
  6732.  decimal places by default.
  6733.  
  6734.  Error traps are provided to handle domain or range errors of mathematical
  6735.  functions. A user can set the options ARITHABORT or ARITHIGNORE, which
  6736.  respectively abort the query or return NULL when a mathematical function
  6737.  encounters a domain error condition. No warning message is displayed. If
  6738.  neither of these options is set, the system returns NULL and prints a
  6739.  warning message after the query is executed.
  6740.  
  6741.  Some simple examples follow:
  6742.  
  6743.    Statement   Result
  6744.  
  6745.    A. select floor(123.45) 123.000000
  6746.     select floor(-123.45) -124.000000
  6747.     select floor($123.45) $123.00
  6748.  
  6749.    B. select ceiling(123.45) 124.000000
  6750.     select ceiling(-123.45) -123.000000
  6751.     select ceiling($123.45) $124.00
  6752.  
  6753.    C. select round(123.4545, 2) 123.450000
  6754.     select round(123.45, -2) 100.000000
  6755.  
  6756.  The ROUND function always returns a value even if the length is illegal. If
  6757.  the specified length is positive and longer than the digits after the
  6758.  decimal point, 0 is added after the fraction digits.
  6759.  
  6760.  If the length is negative and larger than or equal to the digits before the
  6761.  decimal point, ROUND returns 0.00.
  6762.  
  6763.  The last digit in a floating-point number is always an estimate:
  6764.  
  6765.    round(123.9995, 3) = 123.999
  6766.     while
  6767.     round(123.9996, 3) = 124.000
  6768.  
  6769.  
  6770.  Date Functions
  6771.  
  6772.  Date functions are used to display information about dates and times. They
  6773.  manipulate datetime values, performing arithmetic operations on them.
  6774.  
  6775.  Date functions can be used in the select list, in the WHERE clause, or
  6776.  wherever an expression can be used.
  6777.  
  6778.  Values with the datetime datatype are stored internally by SQL Server as two
  6779.  4-byte integers. The first four bytes store the number of days before or
  6780.  after the base date, January 1, 1900. The base date is the system's
  6781.  reference date. The datetime values earlier than January 1, 1753 are not
  6782.  permitted. The other four bytes store the time of day represented as the
  6783.  number of milliseconds after midnight.
  6784.  
  6785.  The default display format for dates looks like this:
  6786.  
  6787.    Apr 15 1987 10:23PM
  6788.  
  6789.  When you enter datetime values, enclose them in single or double quotation
  6790.  marks. SQL Server recognizes a wide variety of datetime data entry formats.
  6791.  (For more information about datetime values, see Chapter 8, "Creating
  6792.  Defaults and Rules," and Chapter 10, "Creating Views."
  6793.  
  6794.  The date functions, their parameters, and the results they produce are
  6795.  listed in the following table.
  6796.  
  6797. ╓┌─────────┌──────────────────────────────────┌──────────────────────────────
  6798.  Function  Parameter                          Result
  6799.  ────────────────────────────────────────────────────────────────────────────
  6800.  DATEADD   (datepart, number, date)           A date produced by adding an
  6801.                                               interval to a date you specify.
  6802.                                               The result is a datetime value
  6803.                                               equal to the date plus the numbe
  6804.                                               of date parts.
  6805.  
  6806.  Function  Parameter                          Result
  6807.  ────────────────────────────────────────────────────────────────────────────
  6808. 
  6809.  DATEDIFF  (datepart, date1, date2)           The number of dateparts between
  6810.                                               two specified dates. The result
  6811.                                               is a signed integer value equal
  6812.                                               to date2 minus date1 in date
  6813.                                               parts.
  6814.  
  6815.  DATENAME  (datepart, date)                   The specified datepart (the firs
  6816.                                               parameter) of the specified date
  6817.                                               (the second parameter) as a
  6818.                                               character string.
  6819.  
  6820.  DATEPART  (datepart, date)                   The specified datepart (the firs
  6821.                                               parameter) of the specified date
  6822.                                               (the second parameter) as an
  6823.                                               integer.
  6824.  
  6825.  GETDATE   ( )                                The current date and time in SQL
  6826.                                               Server's standard internal forma
  6827.  Function  Parameter                          Result
  6828.  ────────────────────────────────────────────────────────────────────────────
  6829.                                              Server's standard internal forma
  6830.                                               for datetime values. GETDATE
  6831.                                               takes the NULL parameter, ( ).
  6832.  
  6833.  ────────────────────────────────────────────────────────────────────────────
  6834.  
  6835.  
  6836.  
  6837.  The DATENAME, DATEPART, DATEDIFF, and DATEADD functions take as parameters a
  6838.  date part─the year, month, hour, and so on. The following table gives each
  6839.  date part, its abbreviation if there is one, and the possible integer values
  6840.  for that date part. The DATENAME function produces ASCII values where
  6841.  appropriate, such as for day of week.
  6842.  
  6843. ╓┌────────────┌─────────────┌────────────────────────────────────────────────╖
  6844.  Date Part    Abbreviation  Values
  6845.  ────────────────────────────────────────────────────────────────────────────
  6846.  year         yy            1900-9999
  6847.  
  6848.  Date Part    Abbreviation  Values
  6849.  ────────────────────────────────────────────────────────────────────────────
  6850. 
  6851.  quarter      qq            1-4
  6852.  
  6853.  month        mm            1-12
  6854.  
  6855.  day of year  dy            1-366
  6856.  
  6857.  day          dd            1-31
  6858.  
  6859.  week         wk            0-51
  6860.  
  6861.  weekday      dw            1-7 (1 is Sunday)
  6862.  
  6863.  hour         hh            0-23
  6864.  
  6865.  minute       mi            0-59
  6866.  
  6867.  second       ss            0-59
  6868.  
  6869.  Date Part    Abbreviation  Values
  6870.  ────────────────────────────────────────────────────────────────────────────
  6871. 
  6872.  millisecond  ms            0-999
  6873.  
  6874.  ────────────────────────────────────────────────────────────────────────────
  6875.  
  6876.  
  6877.  
  6878.  
  6879.  GETDATE
  6880.  
  6881.  The GETDATE function produces the current date and time in SQL Server
  6882.  internal format for datetime values. GETDATE takes the NULL parameter, ( ).
  6883.  
  6884.  
  6885.  To find the current system date and time, type
  6886.  
  6887.    select getdate()
  6888.  
  6889.     --------------------------
  6890.     July 29 1986 2:50 PM
  6891.  
  6892.     (1 row affected)
  6893.  
  6894.  You might use GETDATE in designing a report so that the current date and
  6895.  time are printed every time the report is produced. GETDATE is also useful
  6896.  for functions such as logging the time a transaction occurred on an account.
  6897.  
  6898.  
  6899.  
  6900.  DATEPART and DATENAME
  6901.  
  6902.  The DATEPART and DATENAME functions produce the specified part of a datetime
  6903.  value─the year, quarter, day, hour, and so on─ as either an integer or an
  6904.  ASCII string.
  6905.  
  6906.  The following examples assume the July 29 date shown in the preceding
  6907.  example:
  6908.  
  6909. ╓┌─────────────────────────────────┌─────────────────────────────────────────╖
  6910.  ────────────────────────────────────────────────────────────────────────────
  6911.  ────────────────────────────────────────────────────────────────────────────
  6912.                                    select datepart(month, getdate())
  6913.  
  6914.                                    ------------
  6915.  
  6916.                                    7
  6917.  
  6918.                                    (1 row affected)
  6919.  
  6920.                                    select datename(month, getdate())
  6921.  
  6922.                                    -----------
  6923.  
  6924.                                    July
  6925.  
  6926.                                    (1 row affected)
  6927.  
  6928.  
  6929.  
  6930.  
  6931.  DATEDIFF
  6932.  
  6933.  The DATEDIFF function calculates the amount of time in date parts between
  6934.  the second and first of two dates you specify─in other words, it finds an
  6935.  interval between two dates. The result is a signed integer value equal to
  6936.  date2-date1 in date parts.
  6937.  
  6938.  This query uses the date November 30, 1985, and finds the number of days
  6939.  that elapsed between pubdate and that date:
  6940.  
  6941.    select newdate = datediff(day, pubdate, "Nov 30 1985")
  6942.     from titles
  6943.  
  6944.  For the rows in titles having a pubdate of October 21, 1985, the result
  6945.  produced by the previous query is 40. (There are 40 days between October 21
  6946.  and November 30.) To calculate an interval in months, type
  6947.  
  6948.    select interval = datediff(month, pubdate, "Nov 30 1985")
  6949.     from titles
  6950.  
  6951.  It produces a value of 1 for the rows with a pubdate in October and a value
  6952.  of 5 for the rows with a pubdate in June.
  6953.  
  6954.  When the first date in the DATEDIFF function is later than the second date
  6955.  specified, the resulting value is negative. Since two of the rows in titles
  6956.  have values for pubdate that are assigned using the GETDATE function as a
  6957.  default, these values will be set to the date that your pubs database was
  6958.  created and will return negative values in the two preceding queries.
  6959.  
  6960.  
  6961.  DATEADD
  6962.  
  6963.  DATEADD adds an interval to a date you specify.
  6964.  
  6965.  For example, if the publication dates of all the books in the titles table
  6966.  slipped three days, you could get the new publication dates with this
  6967.  statement:
  6968.  
  6969.    select dateadd(day, 3, pubdate)
  6970.  
  6971.     from titles
  6972.     -------------------
  6973.     Jun 15 1985 12:00AM
  6974.     Jun 12 1985 12:00AM
  6975.     Jul  3 1985 12:00AM
  6976.     Jun 25 1985 12:00AM
  6977.     Jun 12 1985 12:00AM
  6978.     Jun 21 1985 12:00AM
  6979.     Sep 11 1986 11:02AM
  6980.     Jul  3 1985 12:00AM
  6981.     Jun 15 1985 12:00AM
  6982.     Sep 11 1986 11:02AM
  6983.     Oct 24 1985 12:00AM
  6984.     Jun 18 1985 12:00AM
  6985.     Oct  8 1985 12:00AM
  6986.     Jun 15 1985 12:00AM
  6987.     Jun 15 1985 12:00AM
  6988.     Oct 24 1985 12:00AM
  6989.     Jun 15 1985 12:00AM
  6990.     Jun 15 1985 12:00AM
  6991.  
  6992.     (18 rows affected)
  6993.  
  6994.  
  6995.  Conversion Function
  6996.  
  6997.  The conversion function, CONVERT, is used to convert expressions of one
  6998.  datatype to another datatype whenever these conversions are not performed
  6999.  automatically by SQL Server. It is also used to obtain a variety of special
  7000.  date formats.
  7001.  
  7002.  The CONVERT function has the following syntax:
  7003.  
  7004.    CONVERT(datatype [(length)], expression [, style])
  7005.  
  7006.  The conversion function can be used in the select list, in the WHERE clause,
  7007.  and anywhere else an expression is allowed.
  7008.  
  7009.  Here's an example that uses CONVERT in the select list:
  7010.  
  7011. ╓┌───────┌───────────────────────────────────────────────────────────────────
  7012.  ────────────────────────────────────────────────────────────────────────────
  7013.          select title, convert(char(20), ytd_sales)
  7014.  
  7015.          from titles
  7016.  ────────────────────────────────────────────────────────────────────────────
  7017.         from titles
  7018.  
  7019.          where type = "trad_cook"
  7020.  
  7021.          title
  7022.  
  7023.          -------------------------------------------------<19
  7024.          6>-------------
  7025.  
  7026.          Onions, Leeks, and Garlic: Cooking Secrets of the Mediterranean
  7027.  
  7028.          Fifty Years in Buckingham Palace Kitchens
  7029.  
  7030.          Sushi, Anyone?
  7031.  
  7032.          (3 rows affected)
  7033.  
  7034.  
  7035.  
  7036.  In this example, the ytd_sales column, an int column, is converted to a
  7037.  char(20) column so that it can be used with the LIKE clause:
  7038.  
  7039. ╓┌───────┌───────────────────────────────────────────────────────────────────
  7040.  ────────────────────────────────────────────────────────────────────────────
  7041.          select title, ytd_sales
  7042.  
  7043.          from titles
  7044.  
  7045.          where convert(char(20), ytd_sales) like "15%"
  7046.  
  7047.          and type = "trad_cook"
  7048.  
  7049.  
  7050.  
  7051.          title
  7052.  
  7053.          -----------------------------------------
  7054.  
  7055.          Fifty Years in Buckingham Palace Kitchens
  7056.  
  7057.          (1 row affected)
  7058.  ────────────────────────────────────────────────────────────────────────────
  7059.         (1 row affected)
  7060.  
  7061.  
  7062.  
  7063.  SQL Server automatically handles certain datatype conversions. For example,
  7064.  if you compare a char expression and a datetime expression, or a smallint
  7065.  expression and an int expression, or char expressions of different lengths,
  7066.  SQL Server converts them automatically. You need not use the CONVERT
  7067.  function.
  7068.  
  7069.  It is never wrong to use the CONVERT function, even when you are comparing
  7070.  two expressions of exactly the same datatype.
  7071.  
  7072.  If you attempt a conversion that is not possible (for example, if you try to
  7073.  convert a char expression that includes letters to an int), SQL Server
  7074.  displays an error message.
  7075.  
  7076.  Table 5.1 shows the possibilities for converting datatypes.
  7077.  
  7078.  Table 5.1  Datatype Conversion Chart
  7079.  
  7080. ╓┌───────────────┌───────┌──────────┌──────────────┌───────────────┌─────────
  7081.  ────────────────────────────────────────────────────────────────────────────
  7082.  To:             binary  varbinary  tinyint(INT1)  smallint(INT2)  int(INT4)
  7083.  
  7084.  From:
  7085.  
  7086.  binary          -       I          I              I               I
  7087.  
  7088.  varbinary       I       -          I              I               I
  7089.  
  7090.  tinyint(INT1)   E       I          -              I               I
  7091.  
  7092.  smallint(INT2)  E       I          I              -               I
  7093.  
  7094.  int(INT4)       E       E          I              I               -
  7095.  
  7096.  float           N       N          I              I               I
  7097.  
  7098.  char            E       E          E              E               E
  7099.  
  7100.  ────────────────────────────────────────────────────────────────────────────
  7101. 
  7102.  varchar         E       E          E              E               E
  7103.  
  7104.  money           I       I          I              I               I
  7105.  
  7106.  bit             I       I          I              I               I
  7107.  
  7108.  datetime        E       E          N              N               N
  7109.  
  7110.  text            N       N          N              N               N
  7111.  
  7112.  image           E       E          N              N               N
  7113.  
  7114.  ────────────────────────────────────────────────────────────────────────────
  7115.  
  7116.  
  7117.  
  7118.  Key:
  7119.  I Implicit conversion
  7120.  E Explicit conversion, CONVERT function must be used
  7121.  N Conversion not allowed
  7122.  - Conversion of a datatype to itself; allowed but meaningless
  7123.  
  7124.  
  7125.  If you do not specify a length when converting to char, varchar, binary, or
  7126.  varbinary datatypes, the converted data adapts to any size necessary.
  7127.  
  7128.  When converting to datetime, SQL Server rejects all values it cannot
  7129.  recognize as dates (including dates earlier than January 1, 1753).
  7130.  
  7131.  Converting to bit changes any non-zero value to 1.
  7132.  
  7133.  When converting to money from integer datatypes, units are assumed to be
  7134.  dollars. For example, the integer value of 4 would be converted to the money
  7135.  equivalent of 4 dollars.
  7136.  
  7137.  Expressions of datatypes char or varchar that are being converted to an
  7138.  integer datatype must consist only of digits and an optional + or - sign.
  7139.  Leading blanks are ignored. Expressions of datatypes char or varchar that
  7140.  are being converted to money can also include an optional decimal point and
  7141.  dollar sign ($).
  7142.  
  7143.  Expressions of datatypes char or varchar that are being converted to float
  7144.  can also include optional exponential notation (a lowercase "e" or uppercase
  7145.  "E," followed by an optional + or - sign, and then a number).
  7146.  
  7147.  When expressions are converted to a datatype of a different size, values too
  7148.  long for the new datatype are truncated, and SQL Server displays an asterisk
  7149.  (*). Here's an example:
  7150.  
  7151. ╓┌───────┌───────────────────────────────────────────────────────────────────
  7152.  ────────────────────────────────────────────────────────────────────────────
  7153.          select title, convert(char(2), ytd_sales)
  7154.  
  7155.          from titles
  7156.  
  7157.          where type = "trad_cook"
  7158.  
  7159.          title
  7160.  
  7161.          -------------------------------------------------<19 6>-------------
  7162.  
  7163.  ────────────────────────────────────────────────────────────────────────────
  7164. 
  7165.          Onions, Leeks, and Garlic: Cooking Secrets of the Mediterranean
  7166.  
  7167.          Fifty Years in Buckingham Palace Kitchens
  7168.  
  7169.          Sushi, Anyone?
  7170.  
  7171.          (3 rows affected)
  7172.  
  7173.  
  7174.  
  7175.  When converting between datatypes with a different number of decimal points,
  7176.  the value is truncated. For example, the result of CONVERT(money, 10.3496)
  7177.  is $10.34.
  7178.  
  7179.  
  7180.  The Style Parameter
  7181.  
  7182.  The STYLE parameter of CONVERT provides a wide variety of date display
  7183.  formats when converting datetime data to char or varchar. The number
  7184.  parameter you supply as the STYLE parameter determines how the datetime data
  7185.  is displayed. The year can be displayed in either 2 digits or 4 digits. Add
  7186.  100 to a STYLE value to get a 4-place year, including the century (yyyy).
  7187.  
  7188.  The following table shows the possible values for STYLE and the variety of
  7189.  date formats you can use:
  7190.  
  7191. ╓┌────────────────────┌───────────────────┌────────────────────┌─────────────
  7192.  Without              With
  7193.  Century (yy)         Century (yyyy)      Standard             Output
  7194.  ────────────────────────────────────────────────────────────────────────────
  7195.  -                    0 or 100            default              mon dd yyyy
  7196.                                                                hh:miAM (or PM)
  7197.  
  7198.  1                    101                 USA                  mm/dd/yy
  7199.  
  7200.  2                    102                 ANSI                 yy.mm.dd
  7201.  
  7202.  3                    103                 English/French       dd/mm/yy
  7203.  
  7204.  4                    104                 German               dd.mm.yy
  7205.  Without              With
  7206.  Century (yy)         Century (yyyy)      Standard             Output
  7207. 4                    104                 German               dd.mm.yy
  7208.  
  7209.  5                    105                 Italian              dd-mm-yy
  7210.  
  7211.  6                    106                                      dd mon yy
  7212.  
  7213.  7                    107                                      mon dd yy
  7214.  
  7215.  8                    108                                      hh:mi:ss
  7216.  
  7217.  -                    9 or 109            default +            mon dd, yyyy
  7218.                                           milliseconds         hh:mi:sssAM (or
  7219.                                                                PM)
  7220.  
  7221.  10                   110                 USA                  mm-dd-yy
  7222.  
  7223.  11                   111                 Japan                yy/mm/dd
  7224.  
  7225.  12                   112                 ISO                  yymmdd
  7226.  Without              With
  7227.  Century (yy)         Century (yyyy)      Standard             Output
  7228. 12                   112                 ISO                  yymmdd
  7229.  
  7230.  ────────────────────────────────────────────────────────────────────────────
  7231.  
  7232.  
  7233.  
  7234.  The default values (STYLE 0 or 100, 9 or 109) always return the century
  7235.  (yyyy).
  7236.  
  7237.  The following example shows CONVERT with the STYLE parameter:
  7238.  
  7239.    select convert(char(12), getdate(), 3)
  7240.  
  7241.  This converts the current date to style "3," dd/mm/yy.
  7242.  
  7243.  
  7244.  
  7245.  
  7246.  
  7247.  
  7248.  Chapter 6  Building Subqueries
  7249.  ────────────────────────────────────────────────────────────────────────────
  7250.  
  7251.  
  7252.  Introduction
  7253.  
  7254.  A subquery is a SELECT statement that is nested inside another SELECT,
  7255.  INSERT, UPDATE, or DELETE statement or inside another subquery. A statement
  7256.  that includes a subquery operates on rows from one table based on its
  7257.  evaluation of the subquery's SELECT statement, which can refer to the same
  7258.  table as the outer query or to a different table. In TRANSACT-SQL, a
  7259.  subquery can also be used anywhere an expression is allowed if it returns a
  7260.  single value.
  7261.  
  7262.  SELECT statements that contain one or more subqueries are sometimes called
  7263.  nested queries or nested select statements. The practice of nesting one
  7264.  select statement inside another is the reason for the word "structured" in
  7265.  Structured Query Language.
  7266.  
  7267.  Many SQL statements that include subqueries can be alternatively formulated
  7268.  as joins. Other questions can be posed only with subqueries.
  7269.  
  7270.  Some people prefer subqueries to alternative formulations because they find
  7271.  subqueries easier to understand. Other SQL users prefer joins. In
  7272.  TRANSACT-SQL, there are no performance differences between a statement that
  7273.  includes a subquery and a semantically equivalent version that does not. You
  7274.  can choose whichever formulation you prefer.
  7275.  
  7276.  After giving subquery syntax, some general rules, and an introductory
  7277.  example, this chapter discusses:
  7278.  
  7279.  
  7280.    ■   Subqueries introduced with the keywords IN or NOT IN
  7281.  
  7282.    ■   Subqueries introduced with comparison operators and with comparison
  7283.        operators modified with the keywords ANY or ALL
  7284.  
  7285.    ■   Correlated subqueries (subqueries that cannot be evaluated
  7286.        independently, but depend on the outer query for their results)
  7287.  
  7288.    ■   Subqueries introduced with EXISTS (a variety of a correlated subquery)
  7289.  
  7290.  
  7291.  
  7292.  Subquery Syntax
  7293.  
  7294.  The SELECT statement that includes a subquery can display data from only one
  7295.  table. You can name more than one table in the outer query's FROM list,
  7296.  although there is no advantage to so doing. The SELECT statement of a
  7297.  subquery is always enclosed in parentheses.
  7298.  
  7299.  A subquery nested in the outer SELECT statement has the following restricted
  7300.  SELECT syntax:
  7301.  
  7302.    (SELECT [DISTINCT] subquery_select_list
  7303.     [FROM [[database.]owner.]{table_name | view_name} [HOLDLOCK]
  7304.     [,[[database.]owner.]{table_name | view_name} [HOLDLOCK]...]
  7305.     [WHERE search_conditions]
  7306.     [GROUP BY aggregate_free_expression [, aggregate_free_expression...]]
  7307.     [HAVING search_conditions] )
  7308.  
  7309.  Subqueries can be nested inside the WHERE or HAVING clause of an outer
  7310.  SELECT, INSERT, UPDATE, or DELETE statement, or inside another subquery.
  7311.  There is no limit on the level of nesting.
  7312.  
  7313.  In TRANSACT-SQL, a subquery can appear anywhere an expression can be used,
  7314.  so long as it returns a single value.
  7315.  
  7316.  Statements that include a subquery usually take one of these formats:
  7317.  
  7318.    A. WHERE expression [NOT] IN (subquery)
  7319.  
  7320.    B. WHERE expression comparison_operator [ANY | ALL] (subquery)
  7321.  
  7322.    C. WHERE [NOT] EXISTS (subquery)
  7323.  
  7324.  
  7325.  Subquery Rules
  7326.  
  7327.  A subquery is subject to a number of restrictions:
  7328.  
  7329.  
  7330.    ■   The select list of a subquery introduced with a comparison operator
  7331.        can include only one expression or column name (except that EXISTS and
  7332.        IN operate on "SELECT *" or a list, respectively). If the WHERE clause
  7333.        of the outer statement includes a column name, it must be
  7334.        join-compatible with the column named in the subquery select list.
  7335.  
  7336.    ■   The select list of a subquery introduced with EXISTS almost always
  7337.        consists of an asterisk (*) instead of the single column name. Do not
  7338.        specify more than one column name. The select list rules for a
  7339.        subquery introduced with EXISTS are identical to those for a standard
  7340.        select list because a subquery introduced with EXISTS constitutes an
  7341.        existence test and returns true or false rather than any data.
  7342.  
  7343.    ■   Subqueries cannot include ORDER BY or COMPUTE clauses or the INTO
  7344.        keyword.
  7345.  
  7346.    ■   Subqueries introduced by an unmodified comparison operator (a
  7347.        comparison operator not followed by the keyword ANY or ALL) cannot
  7348.        include GROUP BY and HAVING clauses because these subqueries must
  7349.        return a single value.
  7350.  
  7351.    ■   The DISTINCT keyword cannot be used with subqueries that include a
  7352.        GROUP BY clause.
  7353.  
  7354.  
  7355.  In some SQL statements, the subquery (also called the inner query) can be
  7356.  evaluated as if it were an independent query. Conceptually, the results of
  7357.  the subquery are substituted into the main statement, or outer query. (This
  7358.  is not how SQL Server actually processes SQL statements with subqueries
  7359.  though.)
  7360.  
  7361.  There are three basic types of subqueries:
  7362.  
  7363.  
  7364.    ■   Subqueries that operate on lists, introduced with IN, or with a
  7365.        comparison operator modified by ANY or ALL
  7366.  
  7367.    ■   Subqueries that are introduced with an unmodified comparison operator,
  7368.        and must return a single value
  7369.  
  7370.    ■   Subqueries that are an existence test, introduced with EXISTS
  7371.  
  7372.  
  7373.  
  7374.  An Example
  7375.  
  7376.  If you want to find all the books that are the same price as Straight Talk
  7377.  About Computers, you can perform the task in two steps. First, find the
  7378.  price of Straight Talk:
  7379.  
  7380. ╓┌─────────────────────────────────┌─────────────────────────────────────────
  7381.  ────────────────────────────────────────────────────────────────────────────
  7382.                                    select price
  7383.  
  7384.                                    from titles
  7385.  
  7386.                                    where title = "Straight Talk About
  7387.                                    Computers"
  7388.  
  7389.                                    price
  7390.  
  7391.                                    ------------
  7392.  
  7393.                                    $19.99
  7394.  ────────────────────────────────────────────────────────────────────────────
  7395.                                   $19.99
  7396.  
  7397.                                    (1 row affected)
  7398.  
  7399.  
  7400.  
  7401.  Now, use the result (the price) in a second query to find all the books that
  7402.  cost the same as Straight Talk:
  7403.  
  7404. ╓┌───────┌───────────────────────────────────────────────────────────────────
  7405.  ────────────────────────────────────────────────────────────────────────────
  7406.          select title, price
  7407.  
  7408.          from titles
  7409.  
  7410.          where price = $19.99
  7411.  
  7412.          title
  7413.  
  7414.          ---------------------------------------------
  7415.  ────────────────────────────────────────────────────────────────────────────
  7416.         ---------------------------------------------
  7417.  
  7418.          The Busy Executive's Database Guide
  7419.  
  7420.          Straight Talk About Computers
  7421.  
  7422.          Silicon Valley Gastronomic Treats
  7423.  
  7424.          Prolonged Data Deprivation: Four Case Studies
  7425.  
  7426.          (4 rows affected)
  7427.  
  7428.  
  7429.  
  7430.  With a subquery you can solve the problem with a single statement:
  7431.  
  7432. ╓┌───────┌───────────────────────────────────────────────────────────────────
  7433.  ────────────────────────────────────────────────────────────────────────────
  7434.          select title, price
  7435.  
  7436.  ────────────────────────────────────────────────────────────────────────────
  7437. 
  7438.          from titles
  7439.  
  7440.          where price =
  7441.  
  7442.          (select price
  7443.  
  7444.          from titles
  7445.  
  7446.          where title = "Straight Talk About Computers")
  7447.  
  7448.          title
  7449.  
  7450.          ---------------------------------------------
  7451.  
  7452.          The Busy Executive's Database Guide
  7453.  
  7454.          Straight Talk About Computers
  7455.  
  7456.          Silicon Valley Gastronomic Treats
  7457.  ────────────────────────────────────────────────────────────────────────────
  7458.         Silicon Valley Gastronomic Treats
  7459.  
  7460.          Prolonged Data Deprivation: Four Case Studies
  7461.  
  7462.          (4 rows affected)
  7463.  
  7464.  
  7465.  
  7466.  
  7467.  Subqueries Introduced with IN
  7468.  
  7469.  Subqueries that are introduced with the keyword IN have the following
  7470.  syntax:
  7471.  
  7472.    WHERE [expression [NOT] IN (subquery)
  7473.  
  7474.  The result of a subquery introduced with IN (or with NOT IN, discussed
  7475.  later) is a list of zero or more values. Once the subquery returns results,
  7476.  the outer query makes use of them.
  7477.  
  7478.  This query finds the names of the publishers who have published business
  7479.  books:
  7480.  
  7481.    select distinct pub_name
  7482.     from publishers
  7483.     where pub_id in
  7484.      (select pub_id
  7485.      from titles
  7486.      where type = "business")
  7487.  
  7488.     pub_name
  7489.     --------------------
  7490.     New Age Books
  7491.     Algodata Infosystems
  7492.  
  7493.     (2 rows affected)
  7494.  
  7495.  This statement is evaluated in two steps. First, the inner query returns the
  7496.  identification numbers of those publishers that have published business
  7497.  books (1389 and 0736). Second, these values are substituted into the outer
  7498.  query, which finds the names that go with the identification numbers in the
  7499.  publishers table. It looks like this:
  7500.  
  7501.    select pub_name
  7502.     from publishers
  7503.     where pub_id in ("1389", "0736")
  7504.  
  7505.  Another way to formulate this query using a subquery is
  7506.  
  7507.    select distinct pub_name
  7508.     from publishers
  7509.     where "business" in
  7510.      (select type
  7511.      from titles
  7512.      where pub_id = publishers.pub_id)
  7513.  
  7514.  Note that the expression following the WHERE keyword in the outer query can
  7515.  be a constant as well as a column name. Other types of expressions (for
  7516.  example, combinations of constants and column names) are also acceptable.
  7517.  
  7518.  The preceding queries, like many other subqueries, could be alternatively
  7519.  formulated as a join query:
  7520.  
  7521.    select distinct pub_name
  7522.     from publishers, titles
  7523.     where publishers.pub_id = titles.pub_id
  7524.      and type = "business"
  7525.  
  7526.  This statement and the subquery versions all find publishers who have put
  7527.  out business books. They all produce the same results, so in cases like
  7528.  this, choose the method you are most comfortable with.
  7529.  
  7530.  However, there is one advantage to using a join rather than a subquery for
  7531.  this and similar problems. The join lets you show columns from more than one
  7532.  table in the result. For example, if you wanted to include the titles of the
  7533.  business books in the result, you'd need to use the join version:
  7534.  
  7535.    select pub_name, title
  7536.     from publishers, titles
  7537.     where publishers.pub_id = titles.pub_id
  7538.      and type = "business"
  7539.  
  7540.     pub_name
  7541.      title
  7542.     --------------------
  7543.      ----------------------------------------------------
  7544.     Algodata Infosystems
  7545.      The Busy Executive's Database Guide
  7546.     Algodata Infosystems
  7547.      Cooking with Computers: Surreptitious Balance Sheets
  7548.     New Age Books
  7549.      You Can Combat Computer Stress!
  7550.     Algodata Infosystems
  7551.      Straight Talk About Computers
  7552.     (4 rows affected)
  7553.  
  7554.  Here's another example of a statement that can be formulated either with a
  7555.  subquery or with a join query. This query finds the names of all second
  7556.  authors who live in California and receive less than thirty percent of the
  7557.  royalties on some book:
  7558.  
  7559.    select au_lname, au_fname
  7560.     from authors
  7561.     where state = "CA"
  7562.      and au_id in
  7563.     (select au_id
  7564.     from titleauthor
  7565.     where royaltyper < 30
  7566.      and au_ord = 2)
  7567.  
  7568.     au_lname   au_fname
  7569.     ----------   --------
  7570.     MacFeather   Stearns
  7571.  
  7572.     (1 row affected)
  7573.  
  7574.  The inner query is evaluated, producing a list of the IDs of the three
  7575.  authors that meet the qualification. The outer query is then evaluated.
  7576.  Notice that you can include more than one condition in the WHERE clause of
  7577.  both the inner and the outer query.
  7578.  
  7579.  Using a join, the query is expressed like this:
  7580.  
  7581.    select au_lname, au_fname
  7582.     from authors, titleauthor
  7583.     where state = "CA"
  7584.      and authors.au_id = titleauthor.au_id
  7585.      and royaltyper < 30
  7586.      and au_ord = 2
  7587.  
  7588.  A join can always be expressed as a subquery. A subquery can often, but not
  7589.  always, be expressed as a join.
  7590.  
  7591.  
  7592.  Subqueries Introduced with NOT IN
  7593.  
  7594.  Subqueries introduced with the keywords NOT IN also return a list of zero or
  7595.  more values.
  7596.  
  7597.  This query finds the names of the publishers who have not published business
  7598.  books (the opposite of an earlier example):
  7599.  
  7600.    select distinct pub_name
  7601.     from publishers
  7602.     where pub_id not in
  7603.      (select pub_id
  7604.      from titles
  7605.      where type = "business")
  7606.  
  7607.     pub_name
  7608.     --------------------
  7609.     Binnet & Hardley
  7610.  
  7611.     (1 row affected)
  7612.  
  7613.  The query is exactly the same as the previous one except that NOT IN is
  7614.  substituted for IN. However, this statement cannot be converted to a join.
  7615.  The analogous "not equal" join has a different meaning─it finds the names of
  7616.  publishers who have published some book that is not a business book. (The
  7617.  difficulties with interpreting the meaning of joins not based on equality
  7618.  are discussed in more detail in Chapter 3, "Joining Two or More Tables.")
  7619.  
  7620.  
  7621.  Qualifying Column Names
  7622.  
  7623.  In the earlier example, the pub_id column in the WHERE clause of the outer
  7624.  query is implicitly qualified by the table name in the outer query's FROM
  7625.  clause, publishers. The reference to pub_id in the select list of the
  7626.  subquery is qualified by the subquery's FROM clause, that is, by the titles
  7627.  table.
  7628.  
  7629.  The general rule is that column names in a statement are implicitly
  7630.  qualified by the table referenced in the FROM clause at the same level.
  7631.  
  7632.  Here's what the query looks like with these implicit assumptions spelled
  7633.  out:
  7634.  
  7635.    select distinct pub_name
  7636.     from publishers
  7637.     where publishers.pub_id not in
  7638.      (select titles.pub_id
  7639.      from titles
  7640.      where type = "business")
  7641.  
  7642.  It is never wrong to state the table name explicitly, and it is always
  7643.  possible to override implicit assumptions about table names with explicit
  7644.  qualifications.
  7645.  
  7646.  
  7647.  Multiple Levels of Nesting
  7648.  
  7649.  A subquery can itself include one or more subqueries. Any number of
  7650.  subqueries can be nested in a statement.
  7651.  
  7652.  An example of a problem that can be solved using a statement with multiple
  7653.  levels of nested queries is, "Find the names of authors who have
  7654.  participated in writing at least one popular computer book."
  7655.  
  7656.    select au_lname, au_fname
  7657.     from authors
  7658.     where au_id in
  7659.      (select au_id
  7660.      from titleauthor
  7661.      where title_id in
  7662.       (select title_id
  7663.       from titles
  7664.       where type = "popular_comp") )
  7665.  
  7666.     au_lname  au_fname
  7667.     --------  -----------
  7668.     Carson   Cheryl
  7669.     Dull   Ann
  7670.     Hunter   Sheryl
  7671.     Locksley  Chastity
  7672.  
  7673.     (4 rows affected)
  7674.  
  7675.  The innermost query returns the title ID numbers PC1035, PC8888, and PC9999.
  7676.  The query the next level up is evaluated with these title IDs and returns
  7677.  the author ID numbers. Finally, the outer query uses the author IDs to find
  7678.  the names of the authors.
  7679.  
  7680.  You can also express this query as a join:
  7681.  
  7682.    select au_lname, au_fname
  7683.     from authors, titles, titleauthor
  7684.     where authors.au_id = titleauthor.au_id
  7685.      and titles.title_id = titleauthor.title_id
  7686.      and type = "popular_comp"
  7687.  
  7688.  
  7689.  Subqueries in UPDATE, DELETE, and INSERT
  7690.  
  7691.  Subqueries can be nested in UPDATE, DELETE, and INSERT statements, as well
  7692.  as in SELECT statements.
  7693.  
  7694.  ────────────────────────────────────────────────────────────────────────────
  7695.  NOTE
  7696.  Executing these example queries will change the sample database. Ask your
  7697.  System Administrator for help in getting a clean copy of the pubs sample
  7698.  database.
  7699.  ────────────────────────────────────────────────────────────────────────────
  7700.  
  7701.  The following query doubles the price of all books published by New Age
  7702.  Books. The statement updates the titles table; its subquery references the
  7703.  publishers table.
  7704.  
  7705.    update titles
  7706.     set price = price * 2
  7707.     where pub_id in
  7708.      (select pub_id
  7709.      from publishers
  7710.      where pub_name = "New Age Books")
  7711.  
  7712.  An equivalent UPDATE statement using a join is
  7713.  
  7714.    update titles
  7715.     set price = price * 2
  7716.     from titles, publishers
  7717.     where titles.pub_id = publishers.pub_id
  7718.      and pub_name = "New Age Books"
  7719.  
  7720.  You can remove all records of sales of business books with this nested
  7721.  select statement:
  7722.  
  7723.    delete sales
  7724.     where title_id in
  7725.     (select title_id
  7726.     from titles
  7727.     where type = "business"
  7728.  
  7729.  An equivalent DELETE statement using a join is
  7730.  
  7731.    delete sales
  7732.     from sales, titles
  7733.     where sales.title_id = titles.title_id
  7734.      and type = "business"
  7735.  
  7736.  
  7737.  Subqueries with Aliases
  7738.  
  7739.  Many statements in which the subquery and the outer query refer to the same
  7740.  table can be alternatively stated as self-joins (joining a table to itself).
  7741.  For example, you can find authors who live in the same city as Livia Karsen
  7742.  by using a subquery:
  7743.  
  7744.    select au_lname, au_fname, city
  7745.     from authors
  7746.     where city in
  7747.      (select city
  7748.      from authors
  7749.      where au_fname = "Livia"
  7750.       and au_lname = "Karsen")
  7751.  
  7752.     au_lname   au_fname   city
  7753.     ----------   ---------   -------
  7754.     Green    Marjorie   Oakland
  7755.     Straight   Dick    Oakland
  7756.     Stringer   Dirk    Oakland
  7757.     MacFeather   Stearns    Oakland
  7758.     Karsen    Livia    Oakland
  7759.  
  7760.     (5 rows affected)
  7761.  
  7762.  Or, you can use a self-join:
  7763.  
  7764.    select au1.au_lname, au1.au_fname, au1.city
  7765.     from authors au1, authors au2
  7766.     where au1.city = au2.city
  7767.      and au2.au_lname = "Karsen"
  7768.      and au2.au_fname = "Livia"
  7769.  
  7770.  You may recall from the discussion of self-joins in Chapter 3, "Joining Two
  7771.  or More Tables," that table aliases are required because the table being
  7772.  joined to itself appears in two different roles. Aliases can also be used in
  7773.  nested queries that refer to the same table in an inner and outer query:
  7774.  
  7775.    select au1.au_lname, au1.au_fname, au1.city
  7776.     from authors au1
  7777.     where au1.city in
  7778.      (select au2.city
  7779.      from authors au2
  7780.      where au2.au_fname = "Livia"
  7781.       and au2.au_lname = "Karsen")
  7782.  
  7783.  Explicit aliases make it clear that the reference to authors in the subquery
  7784.  does not mean the same thing as the reference in the outer query.
  7785.  
  7786.  
  7787.  Comparison Operator Subqueries
  7788.  
  7789.  This section discusses subqueries that are introduced with one of the
  7790.  comparison operators =, !=, >, >=, <, !>, !< or <=. These subqueries have
  7791.  the following syntax:
  7792.  
  7793.    WHERE expression comparison_operator (subquery)
  7794.  
  7795.  A subquery introduced with an unmodified comparison operator (a comparison
  7796.  operator not followed by ANY or ALL) must return a single value, rather than
  7797.  a list of values like subqueries introduced with IN. If such a subquery
  7798.  returns more than one value, SQL Server displays an error message.
  7799.  
  7800.  Ideally, to use a subquery introduced by an unmodified comparison operator,
  7801.  you must be familiar enough with your data and with the nature of the
  7802.  problem to know that the subquery will return exactly one value.
  7803.  
  7804.  For example, if you suppose each publisher to be located in only one city,
  7805.  and you wish to find the names of authors who live in the city where
  7806.  Algodata Infosystems is located, you can write an SQL statement with a
  7807.  subquery introduced with the simple comparison operator "=":
  7808.  
  7809.    select au_lname, au_fname
  7810.     from authors
  7811.     where city =
  7812.      (select city
  7813.      from publishers
  7814.      where pub_name = "Algodata Infosystems")
  7815.  
  7816.     au_lname  au_fname
  7817.     --------  --------
  7818.     Carson   Cheryl
  7819.     Bennet   Abraham
  7820.  
  7821.     (2 rows affected)
  7822.  
  7823.  Subqueries introduced with unmodified comparison operators often include
  7824.  aggregate functions, since these return a single value. For example, this
  7825.  statement finds the names of all the books priced higher than the current
  7826.  minimum price:
  7827.  
  7828.    select title
  7829.     from titles
  7830.     where price >
  7831.      (select min(price)
  7832.      from titles)
  7833.  
  7834.     title
  7835.     ----------------------------------------------------------
  7836.     The Busy Executive's Database Guide
  7837.     Cooking with Computers: Surreptitious Balance Sheets
  7838.     Straight Talk About Computers
  7839.     Silicon Valley Gastronomic Treats
  7840.     But Is It User Friendly?
  7841.     Secrets of Silicon Valley
  7842.     Computer Phobic and Non-Phobic Individuals: Behavior Variations
  7843.     Is Anger the Enemy?
  7844.     Life Without Fear
  7845.     Prolonged Data Deprivation: Four Case Studies
  7846.     Emotional Security: A New Algorithm
  7847.     Onions, Leeks, and Garlic: Cooking Secrets of the Mediterranean
  7848.     Fifty Years in Buckingham Palace Kitchens
  7849.     Sushi, Anyone?
  7850.  
  7851.     (14 rows affected)
  7852.  
  7853.  Because subqueries introduced by unmodified comparison operators must return
  7854.  a single value, they cannot include GROUP BY or HAVING clauses unless you
  7855.  know that the GROUP BY or HAVING clause itself returns a single value. For
  7856.  example, this query finds the books priced higher than the lowest priced
  7857.  book in the trad_cook category:
  7858.  
  7859.    select title
  7860.     from titles
  7861.     where price >
  7862.      (select min(price)
  7863.      from titles
  7864.      group by type
  7865.      having type = "trad_cook")
  7866.  
  7867.  
  7868.  Comparison Operators Modified with ANY or ALL
  7869.  
  7870.  Comparison operators that introduce a subquery can be modified by the
  7871.  keywords ALL or ANY.
  7872.  
  7873.  ────────────────────────────────────────────────────────────────────────────
  7874.  NOTE
  7875.  
  7876.  The "=ALL" construct is not supported.
  7877.  ────────────────────────────────────────────────────────────────────────────
  7878.  
  7879.  Subqueries introduced with a modified comparison operator have the following
  7880.  syntax:
  7881.  
  7882.    WHERE expression comparison_operator [ANY | ALL] (subquery)
  7883.  
  7884.  Subqueries introduced with a modified comparison operator return a list of
  7885.  zero or more values and can include a GROUP BY or HAVING clause. These
  7886.  subqueries can be restated with EXISTS, which is covered later in this
  7887.  chapter.
  7888.  
  7889.  Using the ">" comparison operator as an example, "> ALL" means greater than
  7890.  every value─in other words, greater than the maximum value. For example, ">
  7891.  ALL (1, 2, 3)" means greater than 3. "> ANY" means greater than at least one
  7892.  value─in other words, greater than the minimum. So "> ANY (1, 2, 3)" means
  7893.  greater than 1.
  7894.  
  7895.  In the context of a subquery, "> ALL" means that for a row to satisfy the
  7896.  condition specified in the outer query, the value in the column that
  7897.  introduces the subquery must be greater than each value in the list of
  7898.  values returned by the subquery.
  7899.  
  7900.  Similarly, "> ANY" means that for a row to satisfy the condition specified
  7901.  in the outer query, the value in the column that introduces the subquery
  7902.  must be greater than at least one of the values in the list of values
  7903.  returned by the subquery.
  7904.  
  7905.  The use of ALL and ANY can be confusing because computers can't tolerate the
  7906.  ambiguity that these words sometimes have in English. For example, you might
  7907.  ask the question, "Which books commanded an advance greater than any book
  7908.  published by Algodata Infosystems?"
  7909.  
  7910.  This question can be paraphrased to make the SQL "translation" of it
  7911.  clearer: "Which books commanded an advance greater than the largest advance
  7912.  paid by Algodata Infosystems?" The ALL keyword (not the ANY keyword) is
  7913.  required here:
  7914.  
  7915.    select title
  7916.     from titles
  7917.     where advance > all
  7918.      (select advance
  7919.      from publishers, titles
  7920.      where titles.pub_id = publishers.pub_id
  7921.       and pub_name = "Algodata Infosystems")
  7922.  
  7923.     title
  7924.     -------------------------------
  7925.     You Can Combat Computer Stress!
  7926.     The Gourmet Microwave
  7927.  
  7928.     (2 rows affected)
  7929.  
  7930.  For each title, the inner query finds a list of advance amounts paid by
  7931.  Algodata. The outer query looks at the largest value in the list and
  7932.  determines whether the title currently being considered has commanded an
  7933.  even bigger advance.
  7934.  
  7935.  If a subquery introduced with ALL and a comparison operator does not return
  7936.  any values, all the rows in the outer query satisfy the condition.
  7937.  
  7938.  The following query provides an example of a subquery introduced with a
  7939.  comparison operator modified by ANY. It finds the titles that got an advance
  7940.  larger than the minimum advance amount paid by Algodata Infosystems.
  7941.  
  7942.    select distinct title
  7943.     from titles
  7944.     where advance > any
  7945.      (select advance
  7946.      from titles, publishers
  7947.      where titles.pub_id = publishers.pub_id
  7948.       and pub_name = "Algodata Infosystems")
  7949.  
  7950.     title
  7951.     ---------------------------------------------------------------
  7952.     Sushi, Anyone?
  7953.     Life Without Fear
  7954.     The Gourmet Microwave
  7955.     But Is It User Friendly?
  7956.     Secrets of Silicon Valley
  7957.     You Can Combat Computer Stress!
  7958.     Computer Phobic and Non-Phobic Individuals: Behavior Variations
  7959.     Onions, Leeks, and Garlic: Cooking Secrets of the Mediterranean
  7960.  
  7961.     (8 rows affected)
  7962.  
  7963.  For each title, the inner query finds a list of advance amounts paid by
  7964.  Algodata. The outer query looks at all the values in the list and determines
  7965.  whether the title currently being considered has commanded an advance larger
  7966.  than any of those amounts. In other words, it finds titles with advances as
  7967.  large or larger than the lowest value paid by Algodata.
  7968.  
  7969.  ────────────────────────────────────────────────────────────────────────────
  7970.  NOTE
  7971.  
  7972.  The use of the DISTINCT keyword in the outer query suppresses false
  7973.  duplicates that result from the join condition in the subquery. DISTINCT is
  7974.  frequently needed when subqueries include a join.
  7975.  ────────────────────────────────────────────────────────────────────────────
  7976.  
  7977.  If the subquery does not return any values, all the rows in the outer query
  7978.  satisfy the condition.
  7979.  
  7980.  The "=ANY" operator is exactly equivalent to IN. For example, to find
  7981.  authors that live in the same city as some publisher, you can use either IN
  7982.  or =ANY:
  7983.  
  7984.    select au_lname, au_fname
  7985.     from authors
  7986.     where city in
  7987.      (select city
  7988.      from publishers)
  7989.  
  7990.     select au_lname, au_fname
  7991.     from authors
  7992.     where city = any
  7993.      (select city
  7994.      from publishers)
  7995.  
  7996.     au_lname   au_fname
  7997.     --------   ---------
  7998.     Carson    Cheryl
  7999.     Bennet    Abraham
  8000.  
  8001.     (2 rows affected)
  8002.  
  8003.  However, the "!=ANY" operator is different from NOT IN. !=ANY means "not = a
  8004.  or not = b or not = c". NOT IN means "not = a and not = b and not = c".
  8005.  
  8006.  For example, say you want to find the authors who live in a city where no
  8007.  publisher is located. You might try this query:
  8008.  
  8009.    select distinct au_lname, au_fname
  8010.     from authors
  8011.     where city != any
  8012.     (select city
  8013.     from publishers)
  8014.  
  8015.  The results include all 23 authors because every author lives in some city
  8016.  where no publisher is located, since each author lives in one and only one
  8017.  city.
  8018.  
  8019.  What's happened is that the inner query finds all the cities in which
  8020.  publishers are located, and then, for each city, the outer query finds the
  8021.  authors who don't live there. The DISTINCT keyword eliminates the
  8022.  duplicates.
  8023.  
  8024.  Here's what happens when you substitute NOT IN in this query:
  8025.  
  8026.    select au_lname, au_fname
  8027.     from authors
  8028.     where city not in
  8029.      (select city
  8030.      from publishers)
  8031.  
  8032.     au_lname    au_fname
  8033.     --------------   ----------
  8034.     del Castillo   Innes
  8035.     Blotchet-Halls   Reginald
  8036.     Gringlesby    Burt
  8037.     DeFrance    Michel
  8038.     Smith     Meander
  8039.     White     Johnson
  8040.     Greene     Morningstar
  8041.     Green     Marjorie
  8042.     Straight    Dick
  8043.     Stringer    Dirk
  8044.     MacFeather    Stearns
  8045.     Karsen     Livia
  8046.     Dull     Ann
  8047.     Hunter     Sheryl
  8048.     Panteley    Sylvia
  8049.     Ringer     Anne
  8050.     Ringer     Albert
  8051.     Locksley    Chastity
  8052.     O'Leary     Michael
  8053.     McBadden    Heather
  8054.     Yokomoto    Akiko
  8055.  
  8056.     (21 rows affected)
  8057.  
  8058.  These are the results you want. They include all the authors except Cheryl
  8059.  Carson and Abraham Bennet, who live in Berkeley, where Algodata Infosystems
  8060.  is located.
  8061.  
  8062.  You get the same results as in the previous example with the "!=ALL"
  8063.  operator, which is equivalent to NOT IN:
  8064.  
  8065.    select au_lname, au_fname
  8066.     from authors
  8067.     where city != all
  8068.      (select city
  8069.      from publishers)
  8070.  
  8071.  
  8072.  Correlated Subqueries
  8073.  
  8074.  Many of the previous queries could be evaluated by executing the subquery
  8075.  once and substituting the resulting value or values into the WHERE clause of
  8076.  the outer query. In queries that include a correlated or repeating subquery,
  8077.  the subquery depends on the outer query for its values. This means that the
  8078.  subquery is executed repeatedly, once for each row that might be selected by
  8079.  the outer query.
  8080.  
  8081.  This statement finds the names of all authors who earn 100% royalty on a
  8082.  book:
  8083.  
  8084.    select distinct au_lname, au_fname
  8085.     from authors
  8086.     where 100 in
  8087.      (select royaltyper
  8088.      from titleauthor
  8089.      where au_id = authors.au_id)
  8090.  
  8091.     au_lname    au_fname
  8092.     -------------   --------
  8093.     Carson     Cheryl
  8094.     Ringer     Albert
  8095.     Straight    Dick
  8096.     White     Johnson
  8097.     Green     Marjorie
  8098.     Panteley    Sylvia
  8099.     Locksley    Chastity
  8100.     del Castillo   Innes
  8101.     Blotchet-Halls   Reginald
  8102.  
  8103.     (9 rows affected)
  8104.  
  8105.  Unlike most of the subqueries previously considered, the subquery in this
  8106.  statement cannot be resolved independently of the main query. It needs a
  8107.  value for authors.au_id, but this value is a variable─it changes as SQL
  8108.  Server examines different rows of the authors table.
  8109.  
  8110.  That's exactly how this query is evaluated: TRANSACT-SQL considers each row
  8111.  of the authors table for inclusion in the results by substituting the value
  8112.  in each row into the inner query. Say that TRANSACT-SQL first examines the
  8113.  row for Cheryl Carson. The variable authors.au_id takes the value
  8114.  "238-95-7766," which TRANSACT-SQL substitutes into the inner query:
  8115.  
  8116.    select royaltyper
  8117.     from titleauthor
  8118.     where au_id = "238-95-7766"
  8119.  
  8120.  The result is 100, so the outer query evaluates to
  8121.  
  8122.    select au_lname, au_fname
  8123.     from authors
  8124.     where 100 in (100)
  8125.  
  8126.  Since this is true, the row for Cheryl Carson is included in the results. If
  8127.  you go through the same procedure with the row for Abraham Bennet, you will
  8128.  see that this row is not included in the results.
  8129.  
  8130.  
  8131.  Correlated Subqueries with Aliases
  8132.  
  8133.  A correlated subquery can be used to find the types of books that are
  8134.  published by more than one publisher:
  8135.  
  8136.    select distinct t1.type
  8137.     from titles t1
  8138.     where t1.type in
  8139.      (select t2.type
  8140.      from titles t2
  8141.      where t1.pub_id != t2.pub_id)
  8142.  
  8143.     type
  8144.     ----------
  8145.     business
  8146.     psychology
  8147.  
  8148.     (2 rows affected)
  8149.  
  8150.  Aliases are required here to distinguish the two different roles in which
  8151.  the titles table appears. This nested query is equivalent to the self-join
  8152.  statement:
  8153.  
  8154.    select distinct t1.type
  8155.     from titles t1, titles t2
  8156.     where t1.type = t2.type
  8157.      and t1.pub_id != t2.pub_id
  8158.  
  8159.  
  8160.  Correlated Subqueries with Comparison Operators
  8161.  
  8162.  To find sales where the quantity is less than the average quantity for sales
  8163.  of that title, type
  8164.  
  8165. ╓┌───────┌──────────────────────────────────────────────────────────┌────────
  8166.  ────────────────────────────────────────────────────────────────────────────
  8167.          select s1.ord_num, s1.title_id, s1.qty
  8168.  
  8169.          from sales s1
  8170.  
  8171.  ────────────────────────────────────────────────────────────────────────────
  8172. 
  8173.          where s1.qty <
  8174.  
  8175.          (select avg(s2.qty)
  8176.  
  8177.          from sales s2
  8178.  
  8179.          where s2.title_id = s1.title_id)
  8180.  
  8181.          ord_num                                                    title_id
  8182.  
  8183.          --------                                                   --------
  8184.  
  8185.          D4482                                                      PS2091
  8186.  
  8187.          N914008                                                    PS2091
  8188.  
  8189.          423LL922                                                   MC3021
  8190.  
  8191.          722a                                                       PS2091
  8192.  ────────────────────────────────────────────────────────────────────────────
  8193.         722a                                                       PS2091
  8194.  
  8195.          6871                                                       BU1032
  8196.  
  8197.          (5 rows affected)
  8198.  
  8199.  
  8200.  
  8201.  The outer query selects the rows of the sales table (that is, of s1,) one by
  8202.  one. The subquery calculates the average quantity for each sale being
  8203.  considered for selection in the outer query. For each possible value of s1,
  8204.  TRANSACT-SQL evaluates the subquery and puts the record being considered in
  8205.  the results if the quantity is less than the calculated average.
  8206.  
  8207.  Sometimes a correlated subquery mimics a GROUP BY statement. To find titles
  8208.  whose price is greater than the average for books of its type, type
  8209.  
  8210.    select t1.type, t1.title
  8211.     from titles t1
  8212.     where t1.price >
  8213.      (select avg(t2.price)
  8214.      from titles t2
  8215.      where t1.type = t2.type)
  8216.  
  8217.     type
  8218.      title
  8219.     -----
  8220.      -------------------------------
  8221.     business
  8222.      The Busy Executive's Database Guide
  8223.     business
  8224.      Straight Talk About Computers
  8225.     mod_cook
  8226.      Silicon Valley Gastronomic Treats
  8227.     popular_comp
  8228.      But Is It User Friendly?
  8229.     psychology
  8230.      Computer Phobic and Non-Phobic Individuals: Behavior Variations
  8231.     psychology
  8232.      Prolonged Data Deprivation: Four Case Studies
  8233.     trad_cook
  8234.      Onions, Leeks, and Garlic: Cooking Secrets of the Mediterranean
  8235.  
  8236.     (7 rows affected)
  8237.  
  8238.  For each possible value of t1, TRANSACT-SQL evaluates the subquery and
  8239.  includes the row in the results if the price value of that row is greater
  8240.  than the calculated average. It is not necessary to group by type
  8241.  explicitly, because the rows for which average price is calculated are
  8242.  restricted by the WHERE clause in the subquery.
  8243.  
  8244.  
  8245.  Correlated Subqueries in a HAVING Clause
  8246.  
  8247.  A correlated subquery can also be used in the HAVING clause of an outer
  8248.  query. This construction can be used to find the types of books in which the
  8249.  maximum advance is more than twice the average within a given group.
  8250.  
  8251.    select t1.type
  8252.     from titles t1
  8253.     group by t1.type
  8254.     having max(t1.advance) >=all
  8255.      (select 2 * avg(t2.advance)
  8256.      from titles t2
  8257.      where t1.type = t2.type)
  8258.  
  8259.     type
  8260.     --------
  8261.     mod_cook
  8262.  
  8263.     (1 row affected)
  8264.  
  8265.  In this case, the subquery is evaluated once for each group defined in the
  8266.  outer query─once for each type of book.
  8267.  
  8268.  
  8269.  Subqueries Introduced with EXISTS
  8270.  
  8271.  When a subquery is introduced with the keyword EXISTS, the subquery
  8272.  functions as an "existence test." In other words, the WHERE clause of the
  8273.  outer query tests for the existence of rows returned by the subquery. The
  8274.  subquery does not actually produce any data, but rather returns a value of
  8275.  "true" or "false."
  8276.  
  8277.  A subquery introduced with EXISTS has the following syntax:
  8278.  
  8279.    WHERE [NOT] EXISTS (subquery)
  8280.  
  8281.  To find the names of all the publishers who publish business books, type
  8282.  
  8283.    select distinct pub_name
  8284.     from publishers
  8285.     where exists
  8286.      (select *
  8287.      from titles
  8288.      where pub_id = publishers.pub_id
  8289.       and type = "business")
  8290.  
  8291.     pub_name
  8292.     --------------------
  8293.     New Age Books
  8294.     Algodata Infosystems
  8295.  
  8296.     (2 rows affected)
  8297.  
  8298.  To determine the results of this query, consider each publisher's name in
  8299.  turn. Does this value cause the subquery to return at least one row? In
  8300.  other words, does it cause the existence test to evaluate to true?
  8301.  
  8302.  In this case, the first publisher's name is Algodata Infosystems, with an
  8303.  identification number of 1389. Are there any rows in the titles table in
  8304.  which pub_id is 1389 and type is business? If so, "Algodata Infosystems"
  8305.  should be one of the values selected. The same process is repeated for each
  8306.  of the other publisher's names.
  8307.  
  8308.  Notice that subqueries introduced with EXISTS are a bit different from other
  8309.  subqueries in these ways:
  8310.  
  8311.  
  8312.    ■   The keyword EXISTS is not preceded by a column name, constant, or
  8313.        other expression.
  8314.  
  8315.    ■   The select list of a subquery introduced by EXISTS almost always
  8316.        consists of an asterisk (*). There is no real point in listing column
  8317.        names, since you are simply testing for the existence of rows that
  8318.        meet the conditions specified in the subquery. A subquery introduced
  8319.        with EXISTS evaluates to true or false rather than returning any data.
  8320.  
  8321.  
  8322.  The EXISTS keyword is very important because there is often no alternative,
  8323.  nonsubquery formulation. A subquery introduced by EXISTS will always be a
  8324.  correlated subquery.
  8325.  
  8326.  Although some queries formulated with EXISTS cannot be expressed any other
  8327.  way, all queries that use IN or a comparison operator modified by ANY or ALL
  8328.  can be expressed with EXISTS. Some examples of statements using EXISTS and
  8329.  their equivalent alternatives follow. You've seen some of them before.
  8330.  
  8331.  Here are two ways to find authors that live in the same city as some
  8332.  publisher:
  8333.  
  8334.    select au_lname, au_fname
  8335.     from authors
  8336.     where city =any
  8337.      (select city
  8338.     from publishers)
  8339.     select au_lname, au_fname
  8340.     from authors
  8341.     where exists
  8342.      (select *
  8343.      from publishers
  8344.      where authors.city = publishers.city)
  8345.  
  8346.     au_lname   au_fname
  8347.     --------   --------
  8348.     Carson    Cheryl
  8349.     Bennet    Abraham
  8350.  
  8351.     (2 rows affected)
  8352.  
  8353.  Here are two queries that find titles of books published by any publisher
  8354.  located in a city that begins with the letter "B":
  8355.  
  8356.    select title
  8357.     from titles
  8358.     where pub_id in
  8359.      (select pub_id
  8360.      from publishers
  8361.      where city like "B%")
  8362.  
  8363.     ----------------------------------------------------
  8364.     You Can Combat Computer Stress!
  8365.     Is Anger the Enemy?
  8366.     Life Without Fear
  8367.     Prolonged Data Deprivation: Four Case Studies
  8368.     Emotional Security: A New Algorithm
  8369.     The Busy Executive's Database Guide
  8370.     Cooking with Computers: Surreptitious Balance Sheets
  8371.     Straight Talk About Computers
  8372.     But Is It User Friendly?
  8373.     Secrets of Silicon Valley
  8374.     Net Etiquette
  8375.  
  8376.     (11 rows affected)
  8377.  
  8378.     select title
  8379.     from titles
  8380.     where exists
  8381.      (select *
  8382.      from publishers
  8383.      where pub_id = titles.pub_id
  8384.       and city like "B%")
  8385.  
  8386.  The second query produces the same results in a different order since it
  8387.  evaluates the tables in different order.
  8388.  
  8389.  
  8390.  Subqueries Introduced with NOT EXISTS
  8391.  
  8392.  NOT EXISTS is just like EXISTS, except that the WHERE clause in which it is
  8393.  used is satisfied if no rows are returned by the subquery.
  8394.  
  8395.  For example, to find the names of publishers who do not publish business
  8396.  books, type
  8397.  
  8398.    select pub_name
  8399.     from publishers
  8400.     where not exists
  8401.      (select *
  8402.      from titles
  8403.      where pub_id = publishers.pub_id
  8404.       and type = "business")
  8405.  
  8406.     pub_name
  8407.     ----------------
  8408.     Binnet & Hardley
  8409.  
  8410.     (1 row affected)
  8411.  
  8412.  This query finds the titles for which there have been no sales:
  8413.  
  8414.    select title
  8415.     from titles
  8416.     where not exists
  8417.      (select title_id
  8418.      from sales
  8419.      where title_id = titles.title_id)
  8420.  
  8421.     title
  8422.     ----------------------------------
  8423.     The Psychology of Computer Cooking
  8424.     Net Etiquette
  8425.  
  8426.     (2 rows affected)
  8427.  
  8428.  
  8429.  Using EXISTS and NOT EXISTS to Find Intersection and Difference
  8430.  
  8431.  Subqueries introduced with EXISTS and NOT EXISTS can be used for two set
  8432.  theory operations: intersection and difference. The intersection of two sets
  8433.  contains all elements that belong to both of the two original sets. The
  8434.  difference contains the elements that belong only to the first of the two
  8435.  sets.
  8436.  
  8437.  The intersection of authors and publishers over the city column is the set
  8438.  of cities in which both an author and a publisher are located:
  8439.  
  8440.    select distinct city
  8441.     from authors
  8442.     where exists
  8443.      (select *
  8444.      from publishers
  8445.      where authors.city = publishers.city)
  8446.  
  8447.     city
  8448.     --------
  8449.     Berkeley
  8450.  
  8451.     (1 row affected)
  8452.  
  8453.  The difference between authors and publishers over the city column is the
  8454.  set of cities where an author lives but no publisher is located (that is,
  8455.  all the cities except Berkeley):
  8456.  
  8457.    select distinct city
  8458.     from authors
  8459.     where not exists
  8460.      (select *
  8461.      from publishers
  8462.      where authors.city = publishers.city)
  8463.  
  8464.     city
  8465.     ----------
  8466.     Gary
  8467.     Covelo
  8468.     Oakland
  8469.     Lawrence
  8470.     San Jose
  8471.     Ann Arbor
  8472.     Corvallis
  8473.     Nashville
  8474.     Palo Alto
  8475.     Rockville
  8476.     Vacaville
  8477.     Menlo Park
  8478.     Walnut Creek
  8479.     San Francisco
  8480.     Salt Lake City
  8481.  
  8482.     (15 rows affected)
  8483.  
  8484.  
  8485.  Subqueries Used in Place of an Expression
  8486.  
  8487.  In TRANSACT-SQL, a subquery can be substituted any place an expression can
  8488.  be used in SELECT, UPDATE, INSERT, and DELETE statements. Here's an example
  8489.  that illustrates how you might use this TRANSACT-SQL enhancement.
  8490.  
  8491.  This statement finds the books that have been written by an author living in
  8492.  California and published there:
  8493.  
  8494.    select distinct title, type
  8495.     from titles
  8496.     where title in
  8497.      (select title
  8498.      from titles, titleauthor, authors
  8499.      where titles.title_id = titleauthor.title_id
  8500.       and titleauthor.au_id = authors.au_id
  8501.       and authors.state = "CA")
  8502.       and title in
  8503.       (select title
  8504.       from titles, publishers
  8505.       where titles.pub_id = publishers.pub_id
  8506.        and publishers.state = "CA")
  8507.  
  8508.     title              type
  8509.     ---------------------------------------------------   ------------
  8510.     Straight Talk About Computers        business
  8511.     The Busy Executive's Database Guide       business
  8512.     Cooking with Computers: Surreptitious Balance Sheets  business
  8513.     Net Etiquette            popular_comp
  8514.     But Is It User Friendly?         popular_comp
  8515.     Secrets of Silicon Valley         popular_comp
  8516.  
  8517.     (6 rows affected)
  8518.  
  8519.  
  8520.  
  8521.  
  8522.  
  8523.  
  8524.  Chapter 7  Creating Databases, Tables, and Indexes
  8525.  ────────────────────────────────────────────────────────────────────────────
  8526.  
  8527.  
  8528.  Introduction
  8529.  
  8530.  This chapter explains how to
  8531.  
  8532.  
  8533.    ■   Use and create a database
  8534.  
  8535.    ■   Create tables and define columns and their datatypes
  8536.  
  8537.    ■   Change tables─rename them, add columns, change the length of their
  8538.        columns
  8539.  
  8540.    ■   Create customized datatypes
  8541.  
  8542.    ■   Create and drop indexes
  8543.  
  8544.  
  8545.  This chapter also explains how to set up database objects. The process of
  8546.  setting up databases and database objects is called data definition.
  8547.  
  8548.  The database objects in SQL Server are
  8549.  
  8550.  
  8551.    ■   Tables
  8552.  
  8553.    ■   Rules
  8554.  
  8555.    ■   Defaults
  8556.  
  8557.    ■   Stored procedures
  8558.  
  8559.    ■   Triggers
  8560.  
  8561.    ■   Views
  8562.  
  8563.  
  8564.  An easy way to find out which components of a database are considered
  8565.  database objects is to look at the rows of the sysobjects system table.
  8566.  
  8567.  In covering these subjects, the following statements are discussed: USE;
  8568.  CREATE DATABASE, DROP DATABASE, and ALTER DATABASE; CREATE TABLE, DROP
  8569.  TABLE, and ALTER TABLE; and CREATE INDEX and DROP INDEX.
  8570.  
  8571.  In addition, these system procedures are discussed or mentioned: sp_addtype,
  8572.  sp_droptype, sp_commonkey, sp_primarykey, sp_foreignkey, sp_dropkey,
  8573.  sp_helpkey, sp_helpjoins, sp_rename, sp_defaultdb, sp_changedbowner,
  8574.  sp_spaceused, sp_help, sp_helpdb, and sp_helpindex.
  8575.  
  8576.  ────────────────────────────────────────────────────────────────────────────
  8577.  NOTE
  8578.  
  8579.  If you do not plan to create your own databases, tables, or indexes, relying
  8580.  on the System Administrator or another user to create them for you, you can
  8581.  read about the USE statement in this chapter and then skip to Chapter 8,
  8582.  "Creating Defaults and Rules."
  8583.  ────────────────────────────────────────────────────────────────────────────
  8584.  
  8585.  
  8586.  Help on Database Objects
  8587.  
  8588.  The sp_help system procedure reports information about a specified database
  8589.  object (any object listed in sysobjects), about a specified datatype (listed
  8590.  in systypes), or about all objects and types in the current database. (For
  8591.  information on databases, use sp_helpdb, which is discussed later in this
  8592.  chapter.)
  8593.  
  8594.  The sp_help system procedure has the following syntax:
  8595.  
  8596.    sp_help [objname]
  8597.  
  8598.  Here's the output for the publishers table:
  8599.  
  8600. ╓┌───────┌─────────────┌──────────────────┌─────────────┌────────────────────
  8601.  ────────────────────────────────────────────────────────────────────────────
  8602.          Name          Owner              type          Created_on
  8603.  
  8604.          ----------    -----              ----------    --------------------
  8605.  
  8606.          publishers    dbo                user table    Jan 28 1987  1:29 PM
  8607.  
  8608.          (0 rows
  8609.          affected)
  8610.  
  8611.          Column_nam    Type               Length        Nulls
  8612.  ────────────────────────────────────────────────────────────────────────────
  8613.         Column_nam    Type               Length        Nulls
  8614.  
  8615.          ----------    --------------     ------        -----
  8616.  
  8617.          pub_id        char nocase        4             0
  8618.  
  8619.          pub_name      varchar nocase     40            1
  8620.  
  8621.          city          varchar nocase     20            1
  8622.  
  8623.          state         char nocase        2             1
  8624.  
  8625.  
  8626.  
  8627.          (0 rows
  8628.          affected)
  8629.  
  8630.  
  8631.  
  8632.          index_name    index_description                index_keys
  8633.  ────────────────────────────────────────────────────────────────────────────
  8634.         index_name    index_description                index_keys
  8635.  
  8636.          ----------    -----------------                ----------
  8637.  
  8638.          pubind        clustered, unique                pub_id
  8639.  
  8640.          (1 row
  8641.          affected)
  8642.  
  8643.          No defined
  8644.          keys for
  8645.          this object.
  8646.  
  8647.  
  8648.  
  8649.  If you execute sp_help without supplying an object name, the resulting
  8650.  report shows a brief listing of each object in sysobjects, giving its name,
  8651.  owner, and object type. The report also shows a brief listing of each
  8652.  user-defined datatype in systypes, giving its name, storage type, length,
  8653.  nulltype (whether null values are allowed), and the names of any defaults or
  8654.  rules bound to it. The report also notes whether any primary or foreign key
  8655.  columns have been defined (for a table or view) with the sp_primarykey or
  8656.  sp_foreignkey system procedure.
  8657.  
  8658.  
  8659.  Permissions
  8660.  
  8661.  Whether or not you can create and drop databases and database objects
  8662.  depends on your permissions. Ordinarily, your System Administrator or
  8663.  Database Owner sets up the permissions for you, based on the kind of work
  8664.  you do and the functions you need. These permissions might be different for
  8665.  each user in a given installation.
  8666.  
  8667.  To make your experiments with database objects as convenient as possible,
  8668.  the sample database, pubs, has a guest user in its sysusers system table.
  8669.  The script that creates pubs grants a variety of permissions to guest. The
  8670.  guest mechanism means that anyone who has a login ID on SQL Server (that is,
  8671.  is listed in master..syslogins) has access to pubs and permission to create
  8672.  and drop objects such as tables, indexes, defaults, rules, procedures, and
  8673.  so on. The guest username also allows you to use certain stored procedures,
  8674.  create user datatypes, query the database, and modify the data in it.
  8675.  
  8676.  To use the pubs database, execute the USE statement. SQL Server checks to
  8677.  see if you are listed under your own name in pubs..sysusers. If not, you're
  8678.  admitted as a guest without any action on your part. If you are listed in
  8679.  pubs..sysusers, you'll be admitted as yourself, but your permissions may be
  8680.  different from guest's. All the examples in this chapter assume you are
  8681.  being treated as guest.
  8682.  
  8683.  
  8684.  Databases
  8685.  
  8686.  A database is a collection of related tables and other database objects.
  8687.  
  8688.  When SQL Server is first installed, it contains three system databases:
  8689.  
  8690.  
  8691.    ■   The master database controls the user databases and the operation of
  8692.        SQL Server as a whole.
  8693.  
  8694.    ■   The temporary database, tempdb, stores temporary tables, which
  8695.        disappear automatically at the end of a session.
  8696.  
  8697.    ■   The model database is a template in creating new user databases.
  8698.  
  8699.  
  8700.  The pubs database is a user database. All of your data─your reason for using
  8701.  a database management system─is stored in user databases.
  8702.  
  8703.  SQL Server manages each database by means of system tables. The data
  8704.  dictionary tables in the master database and in other databases are
  8705.  considered system tables.
  8706.  
  8707.  
  8708.  Choosing a Database: USE
  8709.  
  8710.  Most of the time, you will be using a database that already exists. The USE
  8711.  statement accesses an existing database and has the following syntax:
  8712.  
  8713.    USE database_name
  8714.  
  8715.  For example, to open the database called pubs, type
  8716.  
  8717.    use pubs
  8718.  
  8719.  This statement opens the pubs database if you are a known user in pubs. If
  8720.  you are not known in the database, SQL Server displays a message telling you
  8721.  so. It is up to the owner of the database to give you access to it by
  8722.  executing the sp_adduser system procedure.
  8723.  
  8724.  Users not recognized by name in the master database are allowed in and
  8725.  treated as a user named guest. The guest user is added to the master
  8726.  database in the script that creates the master database when it is
  8727.  installed.
  8728.  
  8729.  A Database Owner can add a guest user to any user database with the
  8730.  sp_adduser system procedure. The System Administrator automatically becomes
  8731.  the Database Owner of whatever database he or she uses. (For more
  8732.  information, see the SQL Server System Administrator's Guide or the SQL
  8733.  Server Language Reference.)
  8734.  
  8735.  It is likely that you will be automatically connected to the master database
  8736.  when you log in to SQL Server. You must execute the USE statement to access
  8737.  some other database. You or the System Administrator can change the database
  8738.  to which you initially connect, using the sp_defaultdb system procedure.
  8739.  Only the System Administrator can change the default database for another
  8740.  user.
  8741.  
  8742.  
  8743.  Creating a User Database: CREATE DATABASE
  8744.  
  8745.  You can create a new database if the System Administrator has granted you
  8746.  permission to use the CREATE DATABASE statement. You must be using the
  8747.  master database when you create a new database. In many environments, the
  8748.  System Administrator creates all databases.
  8749.  
  8750.  Another user who creates a database for you can transfer ownership of it to
  8751.  you with the sp_changedbowner system procedure. The creator of a database is
  8752.  its owner.
  8753.  
  8754.  The Database Owner is responsible for giving users access to the database
  8755.  and for granting and revoking certain other permissions to users. In some
  8756.  organizations, the Database Owner is also responsible for maintaining
  8757.  regular backups of the database and for reloading it in case of system
  8758.  failure. The Database Owner can always impersonate any other user of the
  8759.  database, temporarily attaining that user's permissions, with the SETUSER
  8760.  statement.
  8761.  
  8762.  Because each database is allocated a significant amount of space, even if it
  8763.  contains only small amounts of data, you may not be given permission to use
  8764.  the CREATE DATABASE statement. If this is the case, you may want to skip
  8765.  this section and go on to the discussion of creating database objects.
  8766.  
  8767.  A simplified syntax of the CREATE DATABASE statement is
  8768.  
  8769.    CREATE DATABASE database_name
  8770.  
  8771.  To create the newpubs database, be sure you are using the master database,
  8772.  and then type
  8773.  
  8774.    create database newpubs
  8775.  
  8776.  A database name must be unique on SQL Server and must follow the rules for
  8777.  identifiers given in Chapter 1, "Overview." SQL Server can manage up to
  8778.  32,767 databases. You can create only one database at a time.
  8779.  
  8780.  When creating a new database, SQL Server copies the model database, which
  8781.  contains the system tables that belong in every user database.
  8782.  
  8783.  The creation of a new database is recorded in the master database tables
  8784.  sysdatabases and sysusages.
  8785.  
  8786.  The complete syntax of the CREATE DATABASE statement is
  8787.  
  8788.    CREATE DATABASE database_name
  8789.     [ON {DEFAULT | database_device} [= size]
  8790.     [, database_device [= size]...]]
  8791.  
  8792.  The ON clause allows you to specify where to store the database and how much
  8793.  space to allocate for it in megabytes. If you use the DEFAULT keyword, the
  8794.  database is assigned to an available database device in the pool of default
  8795.  database devices indicated in the master database table sysdevices. To
  8796.  specify a size of 4 megabytes for a database to be stored in this default
  8797.  location, use "ON DEFAULT = size" like this:
  8798.  
  8799.    create database newpubs
  8800.     on default = 4
  8801.  
  8802.  If you wish to specify a different location for the database, give the
  8803.  sysdevices logical name of the database device on which you want it stored.
  8804.  A database can be stored on more than one database device with different
  8805.  amounts of space on each.
  8806.  
  8807.  This statement creates the newpubs database and allocates 3 megabytes to it
  8808.  on file1 and 2 megabytes on file2:
  8809.  
  8810.    create database newpubs
  8811.     on file1 = 3, file2 = 2
  8812.  
  8813.  If the ON clause or the size is omitted, the database is created with 2
  8814.  megabytes of space from the pool of default database devices indicated in
  8815.  sysdevices.
  8816.  
  8817.  A database allocation can range in size from a minimum of 2 megabytes to 215
  8818.  megabytes.
  8819.  
  8820.  
  8821.  Removing a Database: DROP DATABASE
  8822.  
  8823.  The DROP DATABASE statement removes a database. DROP DATABASE deletes the
  8824.  database and all of its contents from SQL Server, frees the storage space
  8825.  that had been allocated for it, and deletes references to it from the master
  8826.  database.
  8827.  
  8828.  The DROP DATABASE statement has the following syntax:
  8829.  
  8830.    DROP DATABASE database_name [, database_name...]
  8831.  
  8832.  As indicated, you can drop more than one database in a single statement. For
  8833.  example:
  8834.  
  8835.    drop database newpubs, newdb
  8836.  
  8837.  
  8838.  Changing the Size of a Database: ALTER DATABASE
  8839.  
  8840.  If the space allocated for a database is too small, the Database Owner can
  8841.  increase it with the ALTER DATABASE statement. ALTER DATABASE permission
  8842.  defaults to the Database Owner and cannot be transferred. You must be using
  8843.  master to use the ALTER DATABASE statement.
  8844.  
  8845.  If a database has filled all of its allocated storage space, you cannot add
  8846.  new data to it or update it. (Existing data, of course, is always
  8847.  preserved.)
  8848.  
  8849.  The minimum (and the default) increase is 1 megabyte from the default pool
  8850.  of disk space. This statement adds 1 megabyte to newpubs on the default
  8851.  database device:
  8852.  
  8853.    alter database newpubs
  8854.  
  8855.  The full ALTER DATABASE syntax allows you to extend a database by more than
  8856.  1 megabyte and to specify where the storage space is to be added:
  8857.  
  8858.    ALTER DATABASE database_name
  8859.     [ON {DEFAULT | database_device} [=size] [, database_device [= size]...]]
  8860.  
  8861.  The ON clause in the ALTER DATABASE statement is just like the ON clause in
  8862.  the CREATE DATABASE statement.
  8863.  
  8864.  To increase the space allocated for newpubs by 2 megabytes on the database
  8865.  device named file1 and by 3 megabytes on file2, type
  8866.  
  8867.    alter database newpubs
  8868.     on file1 = 2, file2 = 3
  8869.  
  8870.  
  8871.  Help on Databases
  8872.  
  8873.  The sp_helpdb system procedure reports information about a specified
  8874.  database or about all the databases on SQL Server and has the following
  8875.  syntax:
  8876.  
  8877.    sp_helpdb [dbname]
  8878.  
  8879.  Here's how you'd get a report on pubs:
  8880.  
  8881. ╓┌───────┌───────────────┌────────┌───────────────┌───────┌───────────────┌──
  8882.  ────────────────────────────────────────────────────────────────────────────
  8883.          sp_helpdb pubs
  8884.  
  8885.  ────────────────────────────────────────────────────────────────────────────
  8886. 
  8887.          name            db_size  owner           dbid    created         stat
  8888.  
  8889.          ----            -------  -----           -----   -----------     ----
  8890.  
  8891.          pubs            2 MB     sa              4       Jan 10 1988     no o
  8892.  
  8893.  
  8894.  
  8895.          (1 row
  8896.          affected)
  8897.  
  8898.  
  8899.  
  8900.          device          size     usage
  8901.  
  8902.          ------          ----     ------------
  8903.  
  8904.          master          2 MB     data and log
  8905.  
  8906.  ────────────────────────────────────────────────────────────────────────────
  8907. 
  8908.  
  8909.  
  8910.          (1 row
  8911.          affected)
  8912.  
  8913.  
  8914.  
  8915.  For complete information on system procedures, see the SQL Server Language
  8916.  Reference.
  8917.  
  8918.  
  8919.  Tables
  8920.  
  8921.  When you create a table, you name its columns and supply a datatype for each
  8922.  column. You also specify whether or not a particular column can hold null
  8923.  values.
  8924.  
  8925.  There can be as many as 2 billion tables per database.
  8926.  
  8927.  
  8928.  CREATE TABLE Basics
  8929.  
  8930.  To create a table, use the CREATE TABLE statement. A simplified syntax of
  8931.  the CREATE TABLE statement is
  8932.  
  8933.    CREATE TABLE table_name
  8934.     (column_name datatype)
  8935.  
  8936.  For example, to create a table named names with one column named some_name
  8937.  and a fixed length of 11 characters, type
  8938.  
  8939.    create table names
  8940.     (some_name char(11) )
  8941.  
  8942.  You can define up to 250 columns. Column names must follow the rules for
  8943.  identifiers. They must be unique within a given table, but you can use the
  8944.  same column name in different tables in the same database.
  8945.  
  8946.  There must be a datatype for each column. The word "char" after the column
  8947.  name refers to the datatype of the column─the type of values that a column
  8948.  will contain. Datatypes are described under "System-Supplied Datatypes"
  8949.  later in this chapter.
  8950.  
  8951.  The number in parentheses after the datatype gives the maximum number of
  8952.  characters that can be stored in the column. You give a maximum length for
  8953.  some datatypes. Others have a system-defined length.
  8954.  
  8955.  Be sure to put parentheses around the list of column names and commas after
  8956.  each column definition.
  8957.  
  8958.  
  8959.  Table Names
  8960.  
  8961.  The CREATE TABLE statement builds the new table in the currently open
  8962.  database. Table names must follow the rules for identifiers given in Chapter
  8963.  1, "Overview," and must be unique for each user.
  8964.  
  8965.  You can create temporary tables (which are automatically put into the
  8966.  temporary database, tempdb, and destroyed at the end of the current session)
  8967.  by preceding the table name with a pound sign (#), like this:
  8968.  
  8969.    create table #authors
  8970.     (au_id char (11))
  8971.  
  8972.  Since all temporary objects belong to the tempdb database you can create a
  8973.  temporary table with the same name as a table already in another database.
  8974.  
  8975.  ────────────────────────────────────────────────────────────────────────────
  8976.  NOTE
  8977.  
  8978.  Temporary tables and other temporary database objects are always created in
  8979.  the tempdb database. The names of temporary tables are assigned a number
  8980.  suffix internally.
  8981.  ────────────────────────────────────────────────────────────────────────────
  8982.  
  8983.  You can use any tables (or other objects) that you have created without
  8984.  qualifying their names. You can also use objects created by the Database
  8985.  Owner without qualifying their names, as long as you have the appropriate
  8986.  permissions on them. (These rules hold for all users, including the System
  8987.  Administrator and the Database Owner.)
  8988.  
  8989.  While table names must be unique for each user, different users can create a
  8990.  table of the same name. For example, a user named Jonah and one named Sally
  8991.  can both create a table named info. Users who have permission on both of
  8992.  those tables will have to qualify them as jonah.info and sally.info. Sally
  8993.  will have to qualify all references to Jonah's info table, although she can
  8994.  refer to her own simply as info.
  8995.  
  8996.  
  8997.  CREATE TABLE Syntax
  8998.  
  8999.  The complete syntax of the CREATE TABLE statement is
  9000.  
  9001.    CREATE TABLE [database.[owner.]]table_name
  9002.      (column_name datatype [NOT NULL | NULL]
  9003.      [, column_name datatype [NOT NULL | NULL]...])
  9004.  
  9005.  The CREATE TABLE statement for the titles table in the pubs database is
  9006.  
  9007.    create table titles
  9008.      (title_id tid,
  9009.      title varchar(80) not null,
  9010.      type char(12),
  9011.      pub_id char(4) null,
  9012.      price money null,
  9013.      advance money null,
  9014.      royalty int null,
  9015.      ytd_sales int null,
  9016.      notes varchar(200) null,
  9017.      pubdate datetime)
  9018.  
  9019.  The following sections define and discuss the system-supplied datatypes and
  9020.  user-defined datatypes. Then null values, temporary tables, and the DROP
  9021.  TABLE statement are explained. The section on tables ends with an example of
  9022.  the entire table creation process.
  9023.  
  9024.  
  9025.  System-Supplied Datatypes
  9026.  
  9027.  The datatype of a column specifies what kind of information (for example,
  9028.  characters, numbers, or dates) the column will hold and how the data will be
  9029.  stored. For example, the integer (int) datatype applies to a column that
  9030.  holds whole numbers in the range of plus or minus 2 billion, while the tiny
  9031.  integer (tinyint) datatype works with positive whole numbers between 0 and
  9032.  255 only.
  9033.  
  9034.  Thirteen system-supplied datatypes are available. You can also build
  9035.  customized user-defined datatypes (as explained later). Some of the
  9036.  system-supplied datatypes require you to specify a length in the form
  9037.  
  9038.    datatype(n)
  9039.  
  9040.  where n is the length. At data entry time, SQL Server checks to make sure
  9041.  that a value being entered is of the right type.
  9042.  
  9043.  If the value being entered is longer than n, SQL Server makes the entry,
  9044.  truncating it to the specified length. No warning message is given.
  9045.  
  9046.  Defaults and rules can be associated with user-defined datatypes by using
  9047.  the sp_bindrule and sp_bindefault system procedures. (Defaults and rules are
  9048.  discussed in Chapter 8, "Creating Defaults and Rules.")
  9049.  
  9050.  The datatypes provided by SQL Server are as follows:
  9051.  
  9052.  int
  9053.    An integer column that holds whole numbers between 231 -1 (2,147,483,647)
  9054.    and -231 +1 (-2,147,483,648), inclusive. However, you cannot enter
  9055.    -2,145,483,648, but you can enter -2,147,483,647 -1. Numbers may be
  9056.    positive or negative, but fractions and decimals are not permitted.
  9057.    Storage size is 4 bytes. All arithmetic operations and aggregate functions
  9058.    can be used with int data. Note that the maximum negative number should be
  9059.    added with INSERT and E-notation. Choose this datatype when the numbers
  9060.    you enter could be outside the range of smallint size.
  9061.  
  9062.  smallint
  9063.    A small integer column that holds whole numbers between 215 -1 (32,767)
  9064.    and -215 (-32,768), inclusive. Numbers may be positive or negative, but
  9065.    fractions and decimals are not permitted. Storage size is 2 bytes. All
  9066.    arithmetic operations and aggregate functions can be used with smallint
  9067.    data. Use this datatype for whole numbers within the given size range.
  9068.  
  9069.  tinyint
  9070.    A tiny integer column that holds whole numbers between 0 and 255,
  9071.    inclusive. Negative numbers, fractions, and decimals are not permitted.
  9072.    Storage size is 1 byte. All arithmetic operations and aggregate functions
  9073.    can be used with tinyint data. Use this datatype for whole numbers that
  9074.    will never exceed 255 or be less than 0.
  9075.  
  9076.  float
  9077.    A floating-point column that stores floating-point numbers. Storage size
  9078.    is 8 bytes. Use this datatype for positive and negative decimal numbers
  9079.    and for numbers with exponents. All arithmetic operations and aggregate
  9080.    functions except modulo are available with float. For float data with an
  9081.    exponential component, enter a number (with or without a decimal point and
  9082.    positive or negative sign), followed by e or E, followed by a number that
  9083.    can include a sign but not a decimal point. The value represented by a
  9084.    float is the product of the first number and the power of 10 of the second
  9085.    number.
  9086.  
  9087.  char(n)
  9088.    A character column that holds any combination of up to 255 letters,
  9089.    numbers, and symbols. Specify the maximum length of the column with n.
  9090.    Storage size is n, no matter what the actual entry length. Built-in string
  9091.    functions for concatenation and for finding substrings are provided for
  9092.    char, varchar, binary, and varbinary data. Columns of the char datatype
  9093.    (with fixed lengths) are accessed a little faster than columns of the
  9094.    varchar datatype (with variable lengths). They use more storage space if
  9095.    the number of characters you enter in this column is less than the fixed
  9096.    length you have specified. Choose char when you are using fixed-length
  9097.    data (as in a social security number or a zip code). Char data must be
  9098.    enclosed in single or double quotation marks when it's input or when you
  9099.    are searching for it. You can use the LIKE keyword and wildcard characters
  9100.    with char, varchar, and datetime data. (For details on LIKE, see Chapter
  9101.    2, "Querying Databases.") Rules for entering literal quotes and strings
  9102.    longer than the width of a screen are explained later. Numbers can be
  9103.    stored in char columns but they must be converted to a numeric datatype
  9104.    before you can do arithmetic on them.
  9105.  
  9106.  varchar(n)
  9107.    A variable-length character column that holds any combination of letters,
  9108.    numbers, and symbols from 1 to 255 characters. Specify the maximum size of
  9109.    the columns with n. Storage size is the actual size of the data values
  9110.    entered, not n. Built-in string functions for concatenation and for
  9111.    finding substrings are provided for char, varchar, binary, and varbinary
  9112.    data.
  9113.  
  9114.    Because of the way it uses space, varchar is best suited for data in which
  9115.    the length of an entry can vary considerably. Names, for example, can
  9116.    fluctuate from short entries like Ho to long ones like
  9117.    Wynglosphringfenster-Dundee y San Carlos Clemente. Like char data, varchar
  9118.    data must be enclosed in single or double quotation marks when it's input.
  9119.    You can use the LIKE keyword and wildcard characters with varchar, char,
  9120.    and datetime data.
  9121.  
  9122.  text
  9123.    A column of variable length that can hold up to 2,147,483,647 characters.
  9124.    The text data is stored on linked lists of data pages. When you initialize
  9125.    a text column with an INSERT, UPDATE, or WRITETEXT statement, SQL Server
  9126.    assigns a text pointer and allocates an entire data page, 2K bytes, to
  9127.    hold the text value.
  9128.  
  9129.    Text data can be converted to char, varchar, binary, and varbinary
  9130.    datatypes only.
  9131.  
  9132.    You can use the WRITETEXT statement to add text data without saving large
  9133.    blocks of text in your transaction log. See the SQL Server Language
  9134.    Reference for details.
  9135.  
  9136.  binary(n)
  9137.    A column that holds up to 255 bytes of fixed-length binary data. The
  9138.    binary datatypes such as bit patterns are meant to hold programming code
  9139.    or pictures.
  9140.  
  9141.    Specify the maximum length of the column with n. Storage size is n, no
  9142.    matter what the actual entry length is. Built-in string functions for
  9143.    concatenation and for finding substrings are provided for char, varchar,
  9144.    binary, and varbinary data. Binary columns (with fixed lengths) are
  9145.    accessed a little faster than varbinary columns (with variable lengths).
  9146.    They can use more storage space if the number of characters you enter in
  9147.    this column is less than the fixed length you have specified. Choose
  9148.    binary when you think the data entries in the column will be close to the
  9149.    same size. Data of type binary is specified with the characters 0 to 9 and
  9150.    A to F, and must be preceded with "0x" when it's input. For example, to
  9151.    input FF, type 0xFF.
  9152.  
  9153.  varbinary(n)
  9154.    A variable-length binary column that holds up to 255 bytes of
  9155.    variable-length binary data. The binary datatypes are not for hexadecimal
  9156.    data, but rather for bit patterns. They are used for storing programming
  9157.    code or pictures, not for hexadecimal numbers. Specify the maximum size of
  9158.    the columns with n. A varbinary column can contain 0 bytes, but n must be
  9159.    between 1 and 255. Storage size is the actual size of the data values
  9160.    entered, not n. Built-in string functions for concatenation and for
  9161.    finding substrings are provided for char, varchar, binary, and varbinary
  9162.    data. Since it stores values as variable lengths, choose varbinary when
  9163.    you expect variation in the size of binary data.
  9164.  
  9165.    Data of type varbinary consists of the characters 0 to 9 and A to F, and
  9166.    must be preceded with 0x when it's input.
  9167.  
  9168.  image
  9169.    A variable-length column that holds between 0 and 2,147,483,648 bytes of
  9170.    binary data. Like binary data, image data must be preceded with "0x" when
  9171.    it is input. The image data is stored on linked lists of data pages. When
  9172.    you initialize an image column with an INSERT or UPDATE statement, SQL
  9173.    Server assigns a text pointer and allocates an entire data page, 2K bytes,
  9174.    to hold the image value.
  9175.  
  9176.    Image data can be converted to char, varchar, binary, and varbinary
  9177.    datatypes only.
  9178.  
  9179.    You can use the WRITETEXT statement to add image date without saving large
  9180.    blocks of text in your transaction log. See the SQL Server Language
  9181.    Reference for details.
  9182.  
  9183.  bit
  9184.    A column that holds either 0 or 1. Integer values other than 0 or 1 are
  9185.    accepted but are always interpreted as 1. Storage size is 1 bit. Multiple
  9186.    bit types in a table can be collected into bytes. For example, 7 bit
  9187.    columns fit into 1 byte; 9 bit columns take 2 bytes. Columns of type bit
  9188.    cannot be NULL and cannot have indexes on them. The status column in the
  9189.    syscolumns system table indicates the unique offset position for bit
  9190.    columns. Use bit for true/false or yes/no types of data.
  9191.  
  9192.  money
  9193.    A column that stores dollar and cent values between
  9194.    ±922,337,203,685,447.5807 dollars with accuracy to a ten-thousandth of a
  9195.    dollar. Storage size is 8 bytes. All arithmetic operations and aggregate
  9196.    functions can be used with money data. Use money for all decimal currency
  9197.    entries. Data of type money must be preceded with a dollar sign ($) when
  9198.    it's input. If there is no dollar sign, SQL Server treats the value as a
  9199.    float. Depending on the exact input, SQL Server may not accept it or may
  9200.    lose some of the value's precision. The minus sign, representing negative
  9201.    money values, must be placed after the dollar sign. You cannot enter money
  9202.    values with commas, although the default print format for money data
  9203.    places a comma after every three digits. When money values are displayed,
  9204.    they are rounded up to the nearest cent. All the arithmetic operations
  9205.    except modulo are available with money.
  9206.  
  9207.  datetime
  9208.    A column that holds dates and times of day. Storage size is two 4-byte
  9209.    integers: 4 bytes for the number of days since the base date of January 1,
  9210.    1900, and 4 bytes for the number of milliseconds after midnight on that
  9211.    day. The maximum datetime value is the last day of the year 9999. SQL
  9212.    Server stores datetime data to an accuracy of .003 seconds, truncating to
  9213.    the nearest three-thousandth. In other words, the entries .001, .002, and
  9214.    .003 are stored as .000, while an entry of .004 is stored as .003. SQL
  9215.    Server rejects all values it cannot recognize as a date. The earliest
  9216.    permissible date is midnight, January 1, 1753.
  9217.  
  9218.    You can do some arithmetic calculations on datetime values with the
  9219.    built-in date functions. When you enter datetime values, always enclose
  9220.    them in single or double quotation marks. Case is always ignored and
  9221.    spaces can occur anywhere between date parts. The default display format
  9222.    for dates is "Apr 15 1987 10:23PM". SQL Server recognizes a wide variety
  9223.    of data entry formats for date and time values. The entry rules are
  9224.    discussed in Chapter 9, "Adding, Changing, and Removing Data." You can
  9225.    also use the CONVERT function for even more styles of date display.
  9226.  
  9227.  timestamp
  9228.    A column that is automatically updated when you use browse mode in a
  9229.    DB-LIBRARY application (see the SQL Server Language Reference). Every time
  9230.    a row containing a timestamp column is inserted or updated, the timestamp
  9231.    column is automatically updated. A table can have only one column of
  9232.    timestamp type. Its definition is varbinary (8) null.
  9233.  
  9234.    When a table is created that contains timestamp data, both the column and
  9235.    the datatype must be named "timestamp."
  9236.  
  9237.  
  9238.  Entering Character and Date Data
  9239.  
  9240.  Remember that you must enclose all character and date data─the char,
  9241.  varchar, text, and datetime datatypes─in single or double quotation marks
  9242.  when inputting it or searching for it.
  9243.  
  9244.  To specify literal quotes within a character entry, use two consecutive
  9245.  single or double quotation marks, or enclose a quote in the opposite kind of
  9246.  quotation mark. (For details and examples, see Chapter 2,"Querying
  9247.  Databases.")
  9248.  
  9249.  To continue a character string for more than one line on your screen when
  9250.  using the isql program, enter a backslash (\) before going to the following
  9251.  line.
  9252.  
  9253.  
  9254.  Converting between Datatypes
  9255.  
  9256.  Many conversions from one datatype to another are handled automatically by
  9257.  SQL Server. Others are available with the CONVERT function. See Chapter 5,
  9258.  "Using Built-In Functions," for more information on CONVERT.
  9259.  
  9260.  
  9261.  User-Defined Datatypes
  9262.  
  9263.  As a TRANSACT-SQL enhancement to SQL, you can name and design your own
  9264.  datatypes to supplement the system-supplied datatypes. A user datatype is
  9265.  defined in terms of system datatypes. You can give one name to a frequently
  9266.  used type definition. This makes it easy for you to custom fit datatypes to
  9267.  columns.
  9268.  
  9269.  ────────────────────────────────────────────────────────────────────────────
  9270.  NOTE
  9271.  
  9272.  To use a user-defined datatype in more than one database, create it in the
  9273.  model database. The user-defined datatype definition then becomes known to
  9274.  all new databases you create. See your System Administrator for more
  9275.  details.
  9276.  ────────────────────────────────────────────────────────────────────────────
  9277.  
  9278.  If you look at the table definition for titles given earlier in this
  9279.  chapter, you'll see that the title_id column has a tid datatype. This is a
  9280.  user-defined datatype based on a char(6).
  9281.  
  9282.  The advantage of user-defined datatypes is that you can bind rules and
  9283.  defaults to them for use in several tables. (Chapter 8, "Creating Defaults
  9284.  and Rules," explains defaults and rules.)
  9285.  
  9286.  The sp_addtype system procedure is used to create user datatypes. It takes
  9287.  as parameters the name of the user datatype being created, the SQL
  9288.  Server-supplied datatype from which it is being built, a length (if one is
  9289.  required for SQL Server datatype), and an optional NULL or NOT NULL
  9290.  specification.
  9291.  
  9292.  The sp_addtype system procedure has the following syntax:
  9293.  
  9294.    sp_addtype typename, phystype [(length)] [, nulltype]
  9295.  
  9296.  Here's how tid was defined:
  9297.  
  9298.    sp_addtype tid, "char(6)", "not null"
  9299.  
  9300.  You need to specify a length after the physical datatype only for char,
  9301.  varchar, binary, and varbinary. (Double or single quotation marks are
  9302.  required around procedure parameters only when the string includes a blank
  9303.  or some form of punctuation.) In this example, quotation marks are required
  9304.  around char(6) because of the parentheses and around not null because of the
  9305.  blank. They are not required around tid.
  9306.  
  9307.  If you don't specify NULL or NOT NULL, NOT NULL is assumed. The length
  9308.  specification cannot be changed when you include the user-defined datatype
  9309.  in a CREATE TABLE statement, but you can override the NULL/NOT NULL
  9310.  assignment.
  9311.  
  9312.  Once a user datatype is defined, it can be used as the datatype for any
  9313.  column in the database. For example, tid is used as the datatype for columns
  9314.  in several pubs tables: titles.title_id, titleauthor.title_id,
  9315.  sales.title_id, and roysched.title_id.
  9316.  
  9317.  A user-defined datatype, sysname, is distributed on the SQL Server
  9318.  distribution diskette and used in the system tables. Its definition is
  9319.  "varchar(30)" "NOT NULL."
  9320.  
  9321.  To drop a user-defined datatype, execute sp_droptype:
  9322.  
  9323.    sp_droptype typename
  9324.  
  9325.  ────────────────────────────────────────────────────────────────────────────
  9326.  NOTE
  9327.  
  9328.  You cannot drop a type that is already in use in a table.
  9329.  ────────────────────────────────────────────────────────────────────────────
  9330.  
  9331.  To get a report on a user-defined datatype, execute sp_help. (For complete
  9332.  information on the system procedures, see the SQL Server Language
  9333.  Reference.)
  9334.  
  9335.  
  9336.  Null Values
  9337.  
  9338.  For each column, you can indicate whether null values are to be allowed. A
  9339.  null value is not the same as "zero" or "blank." NULL means no entry has
  9340.  been made and usually implies "value unknown" or "value inapplicable." It
  9341.  indicates that the user did not make any entry. For example, a null value in
  9342.  the price column of the titles table does not mean that the book is being
  9343.  given away free but that the price is not known or has not been set.
  9344.  
  9345.  If the user fails to make an entry in a column defined with the keyword
  9346.  NULL, SQL Server supplies the value NULL. A column defined with the keyword
  9347.  NULL also accepts an explicit entry of NULL from the user, no matter what
  9348.  datatype it is. However, be careful when you enter null values in character
  9349.  columns: if you put the value NULL inside single or double quotation marks,
  9350.  SQL Server interprets the entry as a character string rather than as the
  9351.  value NULL.
  9352.  
  9353.  In the CREATE TABLE statement, NOT NULL is the default. If neither the NULL
  9354.  nor NOT NULL keyword is specified, NOT NULL is assumed. In effect, you need
  9355.  to specify NULL whenever a column should accept a nonentry.
  9356.  
  9357.  For a column defined with the keywords NOT NULL (or without the NULL
  9358.  keyword), SQL Server insists on an entry. If there is no entry for a NOT
  9359.  NULL column, you'll get an error message.
  9360.  
  9361.  User-defined defaults (a value supplied automatically if no entry is made)
  9362.  can be connected with both NULL and NOT NULL columns. A default counts as an
  9363.  entry. (Defaults and their relationship to NULL columns are discussed in
  9364.  Chapter 8, "Creating Defaults and Rules.")
  9365.  
  9366.  Defining columns as NULL provides a placeholder for data you may not yet
  9367.  know. For example, in the titles table, price, advance, royalty, and
  9368.  ytd_sales are set up to allow NULL.
  9369.  
  9370.  However, title_id and title are not because the lack of an entry in these
  9371.  columns would be meaningless and confusing. A price without a title would
  9372.  make no sense, whereas a title without a price would simply mean the price
  9373.  had not been decided upon or was not available.
  9374.  
  9375.  In the CREATE TABLE statement, use the keywords NOT NULL (or simply omit the
  9376.  NULL keyword) when the information in the column is critical to the meaning
  9377.  of the other columns.
  9378.  
  9379.  
  9380.  Temporary Tables
  9381.  
  9382.  If you use the pound sign (#) before the name of the table in the CREATE
  9383.  TABLE statement, the new table is temporary. The new table is created in the
  9384.  temporary database, no matter what database you are using when you create
  9385.  it. It exists only during the current work session. A temporary table
  9386.  disappears either when it is destroyed (with a DROP TABLE statement) or at
  9387.  the end of the session, whichever comes first.
  9388.  
  9389.  If you do not use the pound sign before the table name, the table is created
  9390.  as a permanent table. A permanent table stays in the database until it is
  9391.  dropped by its owner.
  9392.  
  9393.  The following statement creates a temporary table:
  9394.  
  9395.    create table #myjobs
  9396.      (task char(30),
  9397.      start datetime,
  9398.      stop datetime,
  9399.      notes varchar(200))
  9400.  
  9401.  You can use this table to keep a list of today's chores and errands, along
  9402.  with a record of when you start and finish and any comments you may have.
  9403.  This table and its data will vanish at the end of the current work session.
  9404.  
  9405.  
  9406.  You cannot create a view on a temporary table, nor can you associate rules,
  9407.  defaults, or triggers with temporary tables. You can use a user-defined
  9408.  datatype when creating a temporary table only if that type is in
  9409.  tempdb..systypes.
  9410.  
  9411.  There are two ways to add a user-defined datatype (or any other object) to
  9412.  the tempdb database. To add an object for the current session only, execute
  9413.  sp_addtype while using tempdb. To add a user-defined datatype permanently,
  9414.  execute sp_addtype in the model database and then restart SQL Server so that
  9415.  model is copied to tempdb.
  9416.  
  9417.  
  9418.  Creating a Table in a Different Database
  9419.  
  9420.  As the CREATE TABLE syntax shows, you can create a table in a database other
  9421.  than the current one by qualifying the table name with the name of the other
  9422.  database. However, you must be an authorized user of the database in which
  9423.  you are creating the table, and you must have CREATE TABLE permission in it.
  9424.  
  9425.  
  9426.  If you are using pubs and there is another database called newpubs, you can
  9427.  create a table called newtab in newpubs like this:
  9428.  
  9429.    create table newpubs..newtab (col1 int, etc.)
  9430.  
  9431.  You cannot create other database objects─views, rules, defaults, stored
  9432.  procedures, or triggers─in a database other than the current one.
  9433.  
  9434.  
  9435.  Removing a Table
  9436.  
  9437.  Use the DROP TABLE statement to remove a table from a database. The DROP
  9438.  TABLE statement has the following syntax:
  9439.  
  9440.    DROP TABLE [[database.]owner.]table_name
  9441.     [, [[database.]owner.]table_name...]
  9442.  
  9443.  When you execute this statement, SQL Server removes the specified table(s)
  9444.  from the database, together with its contents and all the indexes and
  9445.  permissions associated with it. Rules or defaults bound to the table are no
  9446.  longer bound but are otherwise not affected.
  9447.  
  9448.  You must be the owner of a table to drop it. However, no one can drop a
  9449.  table while it is in use─being read or written by a user or a front-end
  9450.  program. The DROP TABLE statement cannot be used on any of the system
  9451.  tables, either in the master database or in a user database.
  9452.  
  9453.  As the syntax indicates, you can drop a table in another database as long as
  9454.  you are the table owner.
  9455.  
  9456.  If you DELETE all the rows in a table or use the TRUNCATE TABLE statement on
  9457.  it, the table still exists until you drop it.
  9458.  
  9459.  DROP TABLE (and TRUNCATE TABLE) permission cannot be transferred to other
  9460.  users.
  9461.  
  9462.  
  9463.  Space Used
  9464.  
  9465.  You can find out how much space a table (or index) uses with the
  9466.  sp_spaceused system procedure. The sp_spaceused system procedure has the
  9467.  following syntax:
  9468.  
  9469.    sp_spaceused [objname]
  9470.  
  9471.  This procedure computes and displays the number of rows and data pages used
  9472.  by a table or index. Here's how you'd get a report on the space used by the
  9473.  titles table:
  9474.  
  9475.    sp_spaceused titles
  9476.  
  9477.     name  rows reserved  data index_size   unused
  9478.     ------  ---- --------  ---- ----------  ------
  9479.     titles  18  48 KB   6 KB 4 KB   38 KB
  9480.  
  9481.     (0 rows affected)
  9482.  
  9483.  If no object name is given as a parameter, a summary of space used by all
  9484.  database objects is displayed. (For complete information on the system
  9485.  procedures, see the SQL Server Language Reference.)
  9486.  
  9487.  
  9488.  Table Creation Process
  9489.  
  9490.  This section describes the steps you must take to create a practice table of
  9491.  your own. If you do not have CREATE TABLE permission, see your System
  9492.  Administrator or the owner of the database in which you're working.
  9493.  
  9494.  Creating a table usually implies creating indexes, defaults, and rules to go
  9495.  with it. Custom datatypes, triggers, and views are frequently involved, too.
  9496.  
  9497.  
  9498.  Of course, you can create a table, input some data, and work with it for a
  9499.  while before you create indexes, defaults, rules, triggers, or views. This
  9500.  gives you a chance to see what kind of transactions are most common and what
  9501.  kind of data is frequently entered.
  9502.  
  9503.  On the other hand, it's often most efficient to design a table and all the
  9504.  components that go with it at once. Here's an outline of the steps you go
  9505.  through. You might find it easiest to sketch your plans on paper before you
  9506.  actually create a table and its accompanying objects.
  9507.  
  9508.  
  9509.    ■   Decide what columns you need in the table and the datatype (and
  9510.        length, if required) for each.
  9511.  
  9512.    ■   Create any new user-defined datatypes before you define the table they
  9513.        are to be used in.
  9514.  
  9515.    ■   Decide which columns should accept null values and which should not.
  9516.  
  9517.    ■   Decide whether or not you need defaults and rules, and if so, where
  9518.        and what kind. Consider the relationship between the NULL/NOT NULL
  9519.        status of a column and defaults and rules.
  9520.  
  9521.    ■   Decide what kind of indexes you need and where. (Indexes are discussed
  9522.        later in this chapter.)
  9523.  
  9524.    ■   Create the table and its index(es) with the CREATE TABLE and CREATE
  9525.        INDEX statements.
  9526.  
  9527.    ■   Create new defaults and rules you need with the CREATE DEFAULT and
  9528.        CREATE RULE statements. (These statements are discussed in Chapter 8,
  9529.        "Creating Defaults and Rules.")
  9530.  
  9531.    ■   Bind any defaults and rules you need (new or old) with the
  9532.        sp_bindefault and sp_bindrule system procedures. If there were any
  9533.        defaults or rules on a user-defined datatype that you used in a CREATE
  9534.        TABLE statement, they are automatically in force. (These system
  9535.        procedures are discussed in Chapter 8, "Creating Defaults and Rules.")
  9536.  
  9537.    ■   Create triggers with the CREATE TRIGGER statement. (Triggers are
  9538.        discussed in Chapter 13, "Creating Triggers.")
  9539.  
  9540.    ■   Create views with the CREATE VIEW statement. (Views are discussed in
  9541.        Chapter 10, "Creating Views.")
  9542.  
  9543.  
  9544.  
  9545.  Sample Table
  9546.  
  9547.  This table is called friends_etc. It holds names, addresses, telephone
  9548.  numbers, and personal information about your friends.
  9549.  
  9550.  If you're planning to follow the examples and create all the objects that go
  9551.  with friends_etc yourself, check with your System Administrator or Database
  9552.  Owner. He or she will make sure that if the table has already been created
  9553.  by another user, it and the indexes, defaults, rules, and triggers that go
  9554.  with it have been dropped so that there will be no conflict when you create
  9555.  the objects.
  9556.  
  9557.  The following table shows the proposed structure of the table and the
  9558.  indexes, defaults, and rules that will go with each column.
  9559.  
  9560. ╓┌────────┌────────────────┌────────────────┌───────────────────────┌────────
  9561.  Column   Datatype         Null/Not Null    Index                   Default
  9562.  ────────────────────────────────────────────────────────────────────────────
  9563.  pname    nm               NOT NULL         nmind
  9564.                                             (composite)
  9565.  
  9566.  sname    nm               NOT NULL         nmind
  9567.                                             (composite)
  9568.  
  9569.  address  varchar(30)      NULL
  9570.  
  9571.  city     varchar(30)      NOT NULL                                 citydflt
  9572.  
  9573.  state    char(2)          NOT NULL                                 statedflt
  9574.  
  9575.  zip      char(5)          NULL             zipind                  zipdflt
  9576.  
  9577.  phone    p#               NULL
  9578.  Column   Datatype         Null/Not Null    Index                   Default
  9579.  ────────────────────────────────────────────────────────────────────────────
  9580. phone    p#               NULL
  9581.  
  9582.  age      tinyint          NULL
  9583.  
  9584.  bday     datetime         NOT NULL                                 bdflt
  9585.  
  9586.  sex      bit              NOT NULL                                 sexdflt
  9587.  
  9588.  debt     money            NOT NULL                                 debtdflt
  9589.  
  9590.  notes    varchar(255)     NULL
  9591.  
  9592.  ────────────────────────────────────────────────────────────────────────────
  9593.  
  9594.  
  9595.  
  9596.  
  9597.  Datatypes
  9598.  
  9599.  The first two columns are for personal name and surname. They are defined as
  9600.  nm datatype. Before you create the table, you need to create the datatype.
  9601.  The same is true of the p# datatype for phone.
  9602.  
  9603.  The nm datatype allows for a variable-length character entry with a maximum
  9604.  of 30 characters. The p# datatype allows for a char datatype with a
  9605.  fixed-length of 10 characters.
  9606.  
  9607.  Enter the user datatype definitions for nm and p# like this:
  9608.  
  9609.    execute sp_addtype nm, "varchar(30)"
  9610.  
  9611.     execute sp_addtype p#, "char(10)"
  9612.  
  9613.  
  9614.  Null Values
  9615.  
  9616.  Except for columns that are assigned user-defined datatypes, each column has
  9617.  an explicit NULL or NOT NULL entry. Recall that you don't need to specify
  9618.  NOT NULL in the table definition because it is the default. This table
  9619.  design specifies NOT NULL for readability.
  9620.  
  9621.  The NOT NULL default means that some entry is required, for example, for the
  9622.  two name columns in this table. The other data is meaningless without the
  9623.  names. In addition, the sex column must be NOT NULL because you cannot use
  9624.  NULL with bit datatypes.
  9625.  
  9626.  If a column is designated NULL and a default is bound to it, the default
  9627.  value (rather than NULL) is entered when no other value is given on input.
  9628.  Binding a rule to a column, on the other hand, has no effect on the way null
  9629.  values are handled. This is because a rule does not input any data; rather,
  9630.  it checks whatever is entered to make sure it conforms to the limits given
  9631.  in the rule. (Columns can have both defaults and rules. The relationship
  9632.  between these two is discussed in Chapter 8, "Creating Defaults and Rules.")
  9633.  
  9634.  
  9635.  
  9636.  Table Definition
  9637.  
  9638.  You are ready to write the CREATE TABLE statement:
  9639.  
  9640.    create table friends_etc
  9641.      (pname nm not null,
  9642.      sname nm not null,
  9643.      address varchar(30) null,
  9644.      city varchar(30) not null,
  9645.      state char(2) not null,
  9646.      zip char(5) null,
  9647.      phone p# null,
  9648.      age tinyint null,
  9649.      bday datetime not null,
  9650.      sex bit not null,
  9651.      debt money not null,
  9652.      notes varchar(255) null)
  9653.  
  9654.  You have columns defined for personal name and surname, address, city,
  9655.  state, zip code, telephone number, age, birthday, sex, debt information, and
  9656.  notes. The following section shows how to create indexes. (Defaults and
  9657.  rules are discussed in Chapter 8, "Creating Defaults and Rules.")
  9658.  
  9659.  
  9660.  Changing an Existing Table
  9661.  
  9662.  If you change your mind about a table's structure after you have used it for
  9663.  a while and decide you need to modify the way the table is put together, you
  9664.  have these options:
  9665.  
  9666.  
  9667.    ■   You can add columns (except bit datatype columns) with the ALTER TABLE
  9668.        statement.
  9669.  
  9670.    ■   You can change the name of a table, a column, or any other database
  9671.        object with the sp_rename system procedure.
  9672.  
  9673.  
  9674.  
  9675.  Adding Columns: ALTER TABLE
  9676.  
  9677.  You can add new columns (except columns with the bit datatype) to a table at
  9678.  any time with the ALTER TABLE statement.
  9679.  
  9680.  The ALTER TABLE statement has the following syntax:
  9681.  
  9682.    ALTER TABLE [[database.]owner.]table_name
  9683.     ADD column_name datatype NULL [, column_name datatype NULL...]
  9684.  
  9685.  For example, to add a column to the friends_etc table, type
  9686.  
  9687.    alter table friends_etc
  9688.     add first_met datetime NULL
  9689.  
  9690.  The number of columns in a table cannot exceed 250, whether they are added
  9691.  with an ALTER TABLE statement or defined with the original CREATE TABLE
  9692.  statement.
  9693.  
  9694.  Columns added with the ALTER TABLE statement must allow null values because
  9695.  when the new column is added to the existing rows, there must be some value
  9696.  for it.
  9697.  
  9698.  
  9699.  Renaming Tables and Other Objects
  9700.  
  9701.  To rename tables and other database objects─views, indexes, rules, defaults,
  9702.  procedures, and triggers─use the sp_rename stored procedure. You must be the
  9703.  owner of an object to rename it.
  9704.  
  9705.  The sp_rename system procedure has the following syntax:
  9706.  
  9707.    sp_rename objname, newname
  9708.  
  9709.  For example, to change the name of friends_etc to infotable, type
  9710.  
  9711.    sp_rename friends_etc, infotable
  9712.  
  9713.  You can use sp_rename to rename other objects as well: columns, defaults,
  9714.  rules, procedures, views, triggers, and user datatypes. If you are renaming
  9715.  a column, use the form "table.column".
  9716.  
  9717.  Here's how you'd change the name of the user datatype tid to t_id:
  9718.  
  9719.    exec sp_rename tid, "t_id"
  9720.  
  9721.  You cannot change the name of databases, system datatypes, or most system
  9722.  objects. The object whose name you are changing must be in the current
  9723.  database.
  9724.  
  9725.  ────────────────────────────────────────────────────────────────────────────
  9726.  WARNING
  9727.  
  9728.  Although it is possible to rename system procedures and the model and master
  9729.  databases, doing so will cause serious system problems.
  9730.  ────────────────────────────────────────────────────────────────────────────
  9731.  
  9732.  A user can change the names only of those objects he or she owns. The
  9733.  Database Owner can change the name of any user's objects.
  9734.  
  9735.  Procedures, triggers, and views that depend on an object whose name has been
  9736.  changed work fine until they are recompiled. However, recompilation takes
  9737.  place for many reasons and without notification to the user. When the
  9738.  procedure, trigger, or view is recompiled by SQL Server, it will no longer
  9739.  work. The user must change its text to reflect the new name of the object on
  9740.  which it depends. The safest course is to change the definitions of any
  9741.  dependent objects when you execute sp_rename.
  9742.  
  9743.  
  9744.  Indexes
  9745.  
  9746.  Indexes are created on column(s) to speed retrieval of data. A simplified
  9747.  syntax of the CREATE INDEX statement is
  9748.  
  9749.    CREATE INDEX index_name
  9750.     ON table_name (column_name)
  9751.  
  9752.  To create an index on the au_id column of the authors table, type
  9753.  
  9754.    create index au_id_ind
  9755.     on authors(au_id)
  9756.  
  9757.  The index name must conform to the rules for identifiers. The column and
  9758.  table name specify the column you want indexed and the table that contains
  9759.  it.
  9760.  
  9761.  You must be the owner of a table to CREATE (or DROP) an index. The owner of
  9762.  a table can CREATE (or DROP) an index at any time, whether or not there is
  9763.  data in the table. Indexes can be created on tables in another database by
  9764.  qualifying the table name. Columns of the bit datatype cannot be indexed.
  9765.  
  9766.  The complete syntax of the CREATE INDEX statement is
  9767.  
  9768.    CREATE [UNIQUE] [CLUSTERED | NONCLUSTERED]
  9769.     INDEX index_name
  9770.     ON [[database.]owner.]table_name (column_name [, column_name...])
  9771.     [WITH {FILLFACTOR = x , IGNORE_DUP_KEY ,
  9772.     [IGNORE_DUP_ROW | ALLOW_DUP_ROW]}]
  9773.  
  9774.  The following subsections explain the various options of the CREATE INDEX
  9775.  statement.
  9776.  
  9777.  
  9778.  How, What, and Why to Index
  9779.  
  9780.  Indexes speed the retrieval of data. Putting an index on a column often
  9781.  makes the difference between a nearly immediate response to a query and a
  9782.  long wait.
  9783.  
  9784.  So why not index every column? The most significant reason is that building
  9785.  an index takes time and disk space.
  9786.  
  9787.  Note that nonclustered indexes are automatically re-created when a clustered
  9788.  index is rebuilt.
  9789.  
  9790.  A second reason is that inserting, deleting, or updating data in indexed
  9791.  columns takes a little longer than in unindexed columns. But this cost is
  9792.  usually outweighed by the extent to which indexes improve retrieval
  9793.  performance.
  9794.  
  9795.  Here are some general guidelines on when to index:
  9796.  
  9797.  
  9798.    ■   A column that is often accessed in sorted order (that is, specified in
  9799.        the ORDER BY clause) probably should be indexed so that SQL Server can
  9800.        take advantage of the indexed order.
  9801.  
  9802.    ■   Columns that are regularly used in joins should always be indexed
  9803.        since the system can perform the join faster if the columns are in
  9804.        sorted order.
  9805.  
  9806.    ■   The column that stores the primary key of the table often has a
  9807.        clustered index, especially if it is frequently joined to columns in
  9808.        other tables. (There is only one clustered index per table. See
  9809.        "Clustered and Nonclustered Indexes.")
  9810.  
  9811.    ■   A column that is often searched for ranges of values might be a good
  9812.        choice for a clustered index. Once the row with the first value in the
  9813.        range is found, rows with subsequent values are guaranteed to be
  9814.        physically adjacent. A clustered index does not offer as much of an
  9815.        advantage for searches on single values.
  9816.  
  9817.  
  9818.  There are some cases where indexes are not useful:
  9819.  
  9820.  
  9821.    ■   Columns that are seldom or never referenced in queries don't benefit
  9822.        from indexes since the system seldom or never has to search for rows
  9823.        on the basis of values in these columns.
  9824.  
  9825.    ■   Columns that can have only two or three values (for example, male,
  9826.        female, or unknown) get no real advantage from indexes.
  9827.  
  9828.  
  9829.  If the system does have to search an unindexed column, it does so by looking
  9830.  at the rows one by one. The length of time it takes to perform this kind of
  9831.  scan is directly proportional to the number of rows in the table.
  9832.  
  9833.  
  9834.  Indexing More Than One Column: Composite Indexes
  9835.  
  9836.  You can specify two or more column names if you want to create a composite
  9837.  index on the combined values in all the specified columns.
  9838.  
  9839.  Composite indexes are used when two or more columns are best searched as a
  9840.  unit. For example, the friends_etc table has a composite index on pname and
  9841.  sname. List all the columns to be included in the composite index (in
  9842.  sort-priority order) inside the parentheses after the table name, like this:
  9843.  
  9844.  
  9845.    create index nmind
  9846.     on friends_etc(pname, sname)
  9847.  
  9848.  The columns in a composite index don't have to be in the same order as the
  9849.  columns in the CREATE TABLE statement. The order of pname and sname could be
  9850.  reversed in the preceding index creation statement.
  9851.  
  9852.  Up to 16 columns can be combined into a single composite index. All the
  9853.  columns in a composite index must be in the same table. The maximum
  9854.  allowable size of the combined index values is 256 bytes. (That is, the sum
  9855.  of the lengths of the columns that make up the composite index cannot exceed
  9856.  256.)
  9857.  
  9858.  
  9859.  The UNIQUE Keyword
  9860.  
  9861.  A unique index is one in which no two rows are permitted to have the same
  9862.  index value. The system checks for duplicate values when the index is
  9863.  created (if data already exists) and checks each time data is added with an
  9864.  INSERT or UPDATE statement.
  9865.  
  9866.  Specifying a unique index makes sense only when uniqueness is a
  9867.  characteristic of the data itself. For example, you would not want a unique
  9868.  index on a last_name column since there is likely to be more than one Smith
  9869.  or Wong in tables of even a few hundred rows.
  9870.  
  9871.  On the other hand, a unique index on a column holding social security
  9872.  numbers is a good idea. Uniqueness is a characteristic of the data─each
  9873.  person has a different social security number. Furthermore, a unique index
  9874.  serves as an integrity check: a duplicate social security number probably
  9875.  reflects some kind of error in data entry or on the part of the government.
  9876.  
  9877.  
  9878.  If you try to create a unique index on existing data that includes duplicate
  9879.  values, the statement is aborted, and SQL Server displays an error message
  9880.  that gives the first duplicate.
  9881.  
  9882.  If you try to change data on which there is a unique index in such a way as
  9883.  to generate duplicate values (either with an INSERT or UPDATE statement),
  9884.  the entire transaction is rolled back and SQL Server displays an error
  9885.  message. This is true even if the transaction would have changed many rows
  9886.  but would have caused only one duplicate.
  9887.  
  9888.  You can use the UNIQUE keyword on composite indexes. This was not done for
  9889.  the friends_etc index we just created.
  9890.  
  9891.  
  9892.  Clustered and Nonclustered Indexes
  9893.  
  9894.  With a clustered index, SQL Server sorts rows on an ongoing basis so that
  9895.  their physical order is the same as their logical (indexed) order. The
  9896.  bottom, or leaf level, of a clustered index contains the actual data pages
  9897.  of the table. Create the clustered index before creating any nonclustered
  9898.  indexes, since nonclustered indexes are automatically rebuilt when a
  9899.  clustered index is created.
  9900.  
  9901.  By definition, there can be only one clustered index per table. It is often
  9902.  created on the primary key─the column or columns that uniquely identify the
  9903.  row.
  9904.  
  9905.  Logically, a primary key is determined by the design of the database.
  9906.  However, you can define primary keys, foreign keys, and common keys (pairs
  9907.  of keys that are frequently joined) with the sp_primarykey, sp_foreignkey,
  9908.  and sp_commonkey system procedures. You can display information about keys
  9909.  with sp_helpkey and about frequently joined columns with sp_helpjoins. (For
  9910.  a definition of primary and foreign key, see Chapter 13, "Creating
  9911.  Triggers." For complete information on the system procedures, see the SQL
  9912.  Server Language Reference.)
  9913.  
  9914.  With a nonclustered index, the physical order of the rows is not the same as
  9915.  their indexed order. The leaf level of a nonclustered index contains
  9916.  pointers to rows on data pages. More precisely, each leaf page contains an
  9917.  indexed value and a pointer to the row with that value. In other words, a
  9918.  nonclustered index has an extra level between the index structure and the
  9919.  data itself.
  9920.  
  9921.  You can have up to 250 nonclustered indexes per table; however, you cannot
  9922.  exceed a total of 250 indexes, both clustered and nonclustered.
  9923.  
  9924.  Using a clustered index to find data is almost always faster than using a
  9925.  nonclustered index. In addition, a clustered index is advantageous when many
  9926.  rows with contiguous key values are being retrieved─that is, on columns that
  9927.  are often searched for ranges of values. Once the row with the first key
  9928.  value is found, rows with subsequent indexed values are guaranteed to be
  9929.  physically adjacent, and no further disk accesses are necessary.
  9930.  
  9931.  If neither the CLUSTERED nor the NONCLUSTERED keyword is used, a
  9932.  nonclustered index is created.
  9933.  
  9934.  The following example shows how the index on the title_id column of the
  9935.  titles table is created. (If you want to try this statement, you must drop
  9936.  the index first with DROP INDEX.)
  9937.  
  9938.    create clustered index titleidind
  9939.     on titles(title_id)
  9940.  
  9941.  Since you think you'll often want to sort the people in friends_etc by zip
  9942.  code, you should create a nonclustered index on the zip column, like this:
  9943.  
  9944.    create nonclustered index zipind
  9945.     on friends_etc(zip)
  9946.  
  9947.  A unique index would not make sense here since some of your contacts are
  9948.  likely to have the same zip code. A clustered index wouldn't be appropriate
  9949.  since the zip code is not the primary key.
  9950.  
  9951.  The clustered index in friends_etc should be a composite index on the
  9952.  personal name and surname columns. To create this clustered index, you must
  9953.  drop the nmind index first:
  9954.  
  9955.    drop index friends_etc.nmind
  9956.  
  9957.  Then create the clustered index:
  9958.  
  9959.    create clustered index nmind
  9960.     on friends_etc(pname, sname)
  9961.  
  9962.  
  9963.  The FILLFACTOR Option
  9964.  
  9965.  With the FILLFACTOR option, the user can specify how full SQL Server should
  9966.  make each index page. The amount of empty space on an index page is a matter
  9967.  of concern because when an index page fills up (after enough rows are
  9968.  added), the system must take the time to split it to make room for new rows.
  9969.  
  9970.  
  9971.  It is seldom necessary to include the FILLFACTOR option in your CREATE INDEX
  9972.  statement. This option is provided for fine-tuning of performance. It is
  9973.  useful only when you are creating a new index on existing data, and even
  9974.  then only when you can accurately predict future changes in that data.
  9975.  
  9976.  Allowable FILLFACTOR values are between 0 and 100. The default is 0. The
  9977.  System Administrator can change the default with the sp_configure system
  9978.  procedure. (See the SQL Server System Administrator's Guide.)
  9979.  
  9980.  Here's a CREATE INDEX statement that uses the FILLFACTOR option:
  9981.  
  9982.    create nonclustered index zip_ind
  9983.     on authors(zip)
  9984.     with fillfactor = 100
  9985.  
  9986.  A FILLFACTOR of 100 fills every page completely and makes sense only when
  9987.  you know that no index values in the table will ever change.
  9988.  
  9989.  
  9990.  The IGNORE_DUP_KEY Option
  9991.  
  9992.  The IGNORE_DUP_KEY option is used very infrequently. Its most common
  9993.  function is to sort through a batch of data that includes errors you want to
  9994.  eliminate.
  9995.  
  9996.  IGNORE_DUP_KEY controls what happens when you attempt to enter duplicate
  9997.  keys in a unique clustered index. The phrase is not allowed with a
  9998.  nonclustered index. IGNORE_DUP_KEY is meaningful only when the UPDATE or
  9999.  INSERT that would generate the duplicate affects multiple rows.
  10000.  
  10001.  If IGNORE_DUP_KEY is not set and an attempt is made to enter data that would
  10002.  create duplicate keys, the entire UPDATE or INSERT statement fails─if the
  10003.  statement would have affected more than one row, no rows are changed. (If
  10004.  there are other statements in the same transaction, they execute normally.)
  10005.  
  10006.  
  10007.  If IGNORE_DUP_KEY is set and you give an UPDATE or INSERT statement that
  10008.  would create duplicate keys, the row that would cause duplicate keys is not
  10009.  added or changed─in fact, in the case of UPDATE, the row is discarded. (See
  10010.  the warning below.) Other changes to the database caused by the UPDATE or
  10011.  INSERT attempt (for example, changes to index pages) are also backed out.
  10012.  However, if the UPDATE or INSERT affects multiple rows, the other rows are
  10013.  added or changed as usual.
  10014.  
  10015.  ────────────────────────────────────────────────────────────────────────────
  10016.  WARNING
  10017.  
  10018.  With IGNORE_DUP_KEY set, if you try to update a row in such a way that a
  10019.  duplicate key would be created, that row is discarded. Neither the new value
  10020.  nor the original value of the row that would have produced the duplicate
  10021.  exists in the updated table. For example, if you try to update "Smith" to
  10022.  "Jones" and "Jones" already exists, you wind up with one "Jones" and no
  10023.  "Smith." The disappearance of the row for "Smith" is unavoidable because an
  10024.  UPDATE operation is actually a DELETE followed by an INSERT. SQL Server has
  10025.  no way to know about the disallowed duplicate when it deletes the row, and
  10026.  the whole transaction can't be rolled back because the point of
  10027.  IGNORE_DUP_KEY (and of the IGNORE_DUP_ROW option) is to allow a transaction
  10028.  to proceed despite the presence of duplicates.
  10029.  ────────────────────────────────────────────────────────────────────────────
  10030.  
  10031.  You cannot create a unique index on a column that already includes duplicate
  10032.  values, whether or not IGNORE_DUP_KEY is set. If you attempt to do so, SQL
  10033.  Server displays an error message and a list of the duplicate values. You
  10034.  must eliminate duplicates before you create a unique index on the column.
  10035.  
  10036.  Here's an example of using the IGNORE_DUP_KEY option:
  10037.  
  10038.    create unique clustered index stor_id_ind
  10039.     on stores(stor_id)
  10040.     with ignore_dup_key
  10041.  
  10042.  
  10043.  The IGNORE_DUP_ROW and ALLOW_DUP_ROW Options
  10044.  
  10045.  IGNORE_DUP_ROW and ALLOW_DUP_ROW are allowed only with a nonunique clustered
  10046.  index. (From the point of view of a nonclustered index, there are never any
  10047.  duplicate rows─even for identical data values─because nonclustered indexes
  10048.  include a unique row identification number along with the index value.)
  10049.  
  10050.  Only one or the other of the IGNORE_DUP_ROW and ALLOW_DUP_ROW options can be
  10051.  set.
  10052.  
  10053.  The ALLOW_DUP_ROW option allows duplicate rows in a table. If ALLOW_DUP_ROW
  10054.  is set, you can create a new clustered index on a table that includes
  10055.  duplicate rows, and you can insert or update rows so that they would
  10056.  duplicate already existing rows.
  10057.  
  10058.  If ALLOW_DUP_ROW is not set, the handling of duplicate rows depends on
  10059.  whether IGNORE_DUP_ROW is set. You cannot set ALLOW_DUP_ROW if
  10060.  IGNORE_DUP_ROW is set.
  10061.  
  10062.  If any index in the table is unique, the requirement for uniqueness─the most
  10063.  stringent requirement─takes precedence over the ALLOW_DUP_ROW option. Thus,
  10064.  ALLOW_DUP_ROW applies only to tables with nonunique indexes: you cannot use
  10065.  this keyword if a unique clustered index exists on any column in the table.
  10066.  
  10067.  
  10068.  (However, you might create a table with a nonunique clustered index and the
  10069.  ALLOW_DUP_ROW option, and then create a unique nonclustered index on the
  10070.  same table. If at that time the existing data does not include any duplicate
  10071.  rows, the CREATE UNIQUE NONCLUSTERED INDEX statement will succeed, but
  10072.  subsequent attempts to enter duplicate rows will fail because of the
  10073.  requirement for uniqueness on the new nonclustered index. If duplicate rows
  10074.  do exist when you attempt to create a unique nonclustered index, the
  10075.  statement fails.)
  10076.  
  10077.  The IGNORE_DUP_ROW option (like IGNORE_DUP_KEY) is used infrequently. Its
  10078.  most common function is to sort through a batch of data that includes
  10079.  duplicates you wish to eliminate.
  10080.  
  10081.  IGNORE_DUP_ROW controls what happens when you attempt to enter duplicate
  10082.  rows into a table in which they're not allowed. IGNORE_DUP_ROW applies only
  10083.  to tables with nonunique indexes: you cannot use this keyword if a unique
  10084.  index exists on any column in the table. If ALLOW_DUP_ROW is set,
  10085.  IGNORE_DUP_ROW is meaningless.
  10086.  
  10087.  If IGNORE_DUP_ROW is not set (and ALLOW_DUP_ROW is not set) and you try to
  10088.  insert a duplicate row, the entire statement fails. (If there are other
  10089.  statements in the same transaction, they are executed normally.)
  10090.  
  10091.  If IGNORE_DUP_ROW is set, the row that would duplicate another row is not
  10092.  added or changed, and you get an error message. Changes to the database
  10093.  caused by the attempt to duplicate a row (for example, changes to index
  10094.  pages) are also backed out. Other rows are added or changed, or the rest of
  10095.  the index is created as usual.
  10096.  
  10097.  ────────────────────────────────────────────────────────────────────────────
  10098.  WARNING
  10099.  
  10100.  The same warning about discarded rows applies to IGNORE_DUP_ROW with UPDATE
  10101.  as to IGNORE_DUP_KEY.
  10102.  ────────────────────────────────────────────────────────────────────────────
  10103.  
  10104.  In the default situation (neither ALLOW_DUP_ROW nor IGNORE_DUP_ROW is set),
  10105.  attempting to insert duplicate rows or create a unique clustered index on a
  10106.  table with duplicate rows causes the entire statement to fail.
  10107.  
  10108.  Here's an example:
  10109.  
  10110.    create unique clustered index salesind
  10111.     on sales(stor_id)
  10112.  
  10113.  This statement fails on the duplicate key.
  10114.  
  10115.  This table illustrates how ALLOW_DUP_ROW and IGNORE_DUP_ROW affect attempts
  10116.  to create a nonunique index on a table that includes duplicate rows and to
  10117.  enter duplicate rows into a table.
  10118.  
  10119. ╓┌───────────────────┌─────────────────────────────┌─────────────────────────
  10120.  Option              Has Duplicates                Enter Duplicates
  10121.  ────────────────────────────────────────────────────────────────────────────
  10122.  Neither option set  CREATE INDEX statement        Enter duplicate rows
  10123.                      fails.                        statement fails.
  10124.  Option              Has Duplicates                Enter Duplicates
  10125.  ────────────────────────────────────────────────────────────────────────────
  10126.                     fails.                        statement fails.
  10127.  
  10128.  ALLOW_DUP_ROW set   Command is completed.         Command is completed.
  10129.  
  10130.  IGNORE_DUP_ROW set  Index created but duplicate   All rows accepted except
  10131.                      rows thrown out; error        duplicates; error message.
  10132.                      message.                      See earlier warning.
  10133.  
  10134.  ────────────────────────────────────────────────────────────────────────────
  10135.  
  10136.  
  10137.  
  10138.  
  10139.  Help on Indexes
  10140.  
  10141.  To see the indexes that exist on a table, you can use the sp_helpindex
  10142.  system procedure. Here's a report on the authors table:
  10143.  
  10144.    sp_helpindex authors
  10145.  
  10146.     index_name   index_description   index_keys
  10147.     ----------   -----------------   ------------------
  10148.     auidind    clustered,unique   au_id
  10149.     aunmind    nonclustered    au_lname, au_fname
  10150.  
  10151.     (2 rows affected)
  10152.  
  10153.  The sp_help system procedure also reports indexes on a table.
  10154.  
  10155.  ────────────────────────────────────────────────────────────────────────────
  10156.  WARNING
  10157.  
  10158.  Only eight indexes are displayed when you execute sp_helpindex. The
  10159.  sysindexes system table contains information on all indexes.
  10160.  ────────────────────────────────────────────────────────────────────────────
  10161.  
  10162.  
  10163.  Removing an Index: DROP INDEX
  10164.  
  10165.  The DROP INDEX statement is used to remove an index from the database. The
  10166.  DROP INDEX statement has the following syntax:
  10167.  
  10168.    DROP INDEX table_name.index_name [, table_name.index_name...]
  10169.  
  10170.  When you execute this statement, SQL Server removes the specified index(es)
  10171.  from the database, reclaiming its storage space.
  10172.  
  10173.  Only the owner of the index can drop it. DROP INDEX permission cannot be
  10174.  transferred to other users. The DROP INDEX statement cannot be used on any
  10175.  of the system tables in the master database or in the user database.
  10176.  
  10177.  You might want to drop an index if it is not used for most or all of your
  10178.  queries.
  10179.  
  10180.  To drop the index auidind in the authors table, type
  10181.  
  10182.    drop index authors.auidind
  10183.  
  10184.  
  10185.  
  10186.  
  10187.  
  10188.  
  10189.  Chapter 8  Creating Defaults and Rules
  10190.  ────────────────────────────────────────────────────────────────────────────
  10191.  
  10192.  
  10193.  Introduction
  10194.  
  10195.  A default is a value that SQL Server inserts into a column if the user does
  10196.  not explicitly enter one. A rule specifies what you are or are not allowed
  10197.  to enter in a particular column or in any column with a given user-defined
  10198.  datatype.
  10199.  
  10200.  This chapter explains how to create and drop defaults and rules, and how to
  10201.  associate defaults and rules with a column or with a user-defined datatype,
  10202.  using the sp_bindefault, sp_bindrule, sp_unbindefault, and sp_unbindrule
  10203.  system procedures.
  10204.  
  10205.  
  10206.  Defaults
  10207.  
  10208.  In a relational database management system, every data element (that is, a
  10209.  particular column in a particular row) must contain some value─even if that
  10210.  value is NULL. As discussed in the last chapter, some columns do not accept
  10211.  the null value. Some other value must be entered, either a value entered by
  10212.  the user or a default entered by SQL Server.
  10213.  
  10214.  Defaults allow you to specify a value that SQL Server inserts if no value is
  10215.  entered (in either a NULL or NOT NULL column). For example, you can create a
  10216.  default that has the value "???" or the value "fill in later", and then
  10217.  instruct SQL Server to enter it if a user does not make an entry.
  10218.  
  10219.  Defaults can be created or dropped at any time, before or after data has
  10220.  been entered in a table. A default is created with the CREATE DEFAULT
  10221.  statement and dropped with the DROP DEFAULT statement.
  10222.  
  10223.  A default can be connected to a particular column, to a number of columns,
  10224.  or to all the columns in the database having a given user-defined datatype.
  10225.  A default is associated with a column or user-defined datatype with the
  10226.  sp_bindefault system procedure. The association is removed with the
  10227.  sp_unbindefault system procedure.
  10228.  
  10229.  Here are some things you should check when you are creating and binding
  10230.  defaults:
  10231.  
  10232.  
  10233.    ■   Make sure the column is large enough for the default. A char(2) column
  10234.        will not hold a 17-character string like "Nobody knows yet."
  10235.  
  10236.    ■   Be careful when you put different defaults on a user datatype and on
  10237.        an individual column of that type. If you bind the user datatype
  10238.        default first and then the column default, the column default replaces
  10239.        the user datatype default for the named column only. The user datatype
  10240.        default is bound to all the other columns having that datatype.
  10241.        However, once you bind another default to a column that had a default
  10242.        because of its type, that column ceases to be influenced by defaults
  10243.        bound to its datatype. This issue is discussed in more detail later in
  10244.        this chapter.
  10245.  
  10246.    ■   Watch out for conflicts between defaults and rules. Be sure that the
  10247.        default value is allowed by the rule; otherwise, the default can be
  10248.        eliminated by the rule.
  10249.  
  10250.        If a rule allows entries between 1 and 100, for example, and the
  10251.        default is set to 0, the rule will force the default entry to be
  10252.        rejected every time and you'll get an error (unless the column accepts
  10253.        NULL, in which case "NULL" will be entered). Either the default or the
  10254.        rule will have to be changed.
  10255.  
  10256.  
  10257.  
  10258.  Creating Defaults
  10259.  
  10260.  The CREATE DEFAULT statement has the following syntax:
  10261.  
  10262.    CREATE DEFAULT [owner.]default_name
  10263.     AS constant_expression
  10264.  
  10265.  Default names must follow the rules for identifiers. You can create a
  10266.  default in the current database only.
  10267.  
  10268.  Within a database, default names must be unique. You cannot create two
  10269.  defaults called phonedflt. However, as guest you can create a phonedflt even
  10270.  if dbo.phonedflt already exists because the owner names make each one
  10271.  distinct.
  10272.  
  10273.  The next example shows how to create a default value of "Oakland" to use
  10274.  with the city column of friends_etc (the table whose creation was discussed
  10275.  in Chapter 7, "Creating Databases, Tables, and Indexes") and possibly with
  10276.  other columns or user datatypes. (As you continue to follow this example,
  10277.  you can use any city name that works for the demographic distribution of the
  10278.  people you're planning to enter in your personal table.) To create the
  10279.  default, type
  10280.  
  10281.    create default citydflt
  10282.     as "Oakland"
  10283.  
  10284.  After the AS keyword, you can use any constant. Enclose character and date
  10285.  constants in quotation marks; money, integer, and floating-point constants
  10286.  do not require them. Binary data must be preceded with "0x", and money data
  10287.  must be preceded by a dollar sign ($). The default value must be compatible
  10288.  with the datatype of the column. For example, you cannot use "none" as a
  10289.  default for a numeric column, but "0" (zero) is appropriate.
  10290.  
  10291.  If you specify NOT NULL when you create a column and do not associate a
  10292.  default with it, SQL Server will produce an error message whenever anyone
  10293.  fails to make an entry in that column.
  10294.  
  10295.  Often, default values are created when a table is created. However, in a
  10296.  session in which you want to enter many rows having the same values in one
  10297.  or more columns, it may be convenient to create a default tailored to that
  10298.  session before you begin.
  10299.  
  10300.  
  10301.  Binding Defaults
  10302.  
  10303.  After you've created a default, use the sp_bindefault system procedure to
  10304.  bind the default to a column or user-defined datatype.
  10305.  
  10306.  The default applies to new rows only. It does not change already existing
  10307.  rows. It takes effect only when no entry is made. If the user supplies a
  10308.  value for the column, the default has no effect.
  10309.  
  10310.  Here's how to bind citydflt to the city column in friends_etc:
  10311.  
  10312.    sp_bindefault citydflt, "friends_etc.city"
  10313.  
  10314.  Notice that the table and column name are enclosed in quotation marks
  10315.  because of the embedded punctuation (the period).
  10316.  
  10317.  You can't bind a default to a system datatype (the target would be too
  10318.  broad), but you can bind it to a user-defined datatype.
  10319.  
  10320.  If you create a special datatype for all city columns in every table in your
  10321.  database, you can bind citydflt to that datatype, and "Oakland" will show up
  10322.  only where city names are appropriate. For example, if the user datatype is
  10323.  called citytype, here's how you'd bind citydflt to it:
  10324.  
  10325.    sp_bindefault citydflt, citytype
  10326.  
  10327.  Here's how you create and bind a default for the state column of
  10328.  friends_etc:
  10329.  
  10330.    create default statedflt
  10331.     as "CA"
  10332.  
  10333.     sp_bindefault statedflt, "friends_etc.state"
  10334.  
  10335.  If most of the people in your table live in the same zip code area, you can
  10336.  create a default to save data-entry time. Here's one that's appropriate for
  10337.  a section of Oakland along with its binding:
  10338.  
  10339.    create default zipdflt
  10340.     as "94609"
  10341.  
  10342.     sp_bindefault zipdflt, "friends_etc.zip"
  10343.  
  10344.  The sp_bindefault system procedure has the following syntax:
  10345.  
  10346.    sp_bindefault defname, objname, [, futureonly]
  10347.  
  10348.  The defname is the name of the default created with CREATE DEFAULT. The
  10349.  objname is the name of the table and column, or of the user-defined datatype
  10350.  to which the default is to be bound. If the parameter is not of the form
  10351.  "table.column", it is assumed to be a user datatype.
  10352.  
  10353.  The default must be compatible with the datatype of the column. For example,
  10354.  you cannot use "N/A" as a default for a numeric column. If the default is
  10355.  not compatible with the column to which you've bound it, SQL Server will
  10356.  generate an error message when it tries to insert the default value (not
  10357.  when you bind it).
  10358.  
  10359.  All columns of a specified user datatype become associated with the
  10360.  specified default unless
  10361.  
  10362.  
  10363.    ■   You use the optional third parameter, futureonly, which prevents
  10364.        existing columns of that user datatype from inheriting the default
  10365.  
  10366.    ■   The column's default has previously been changed, in which case the
  10367.        changed default is maintained
  10368.  
  10369.  
  10370.  For example, you create a table called foes with a column named city of type
  10371.  citytype (a user-defined datatype). Initially, the user-defined datatype
  10372.  citytype has no default. After creating a default called citydflt, you bind
  10373.  it to foes.city. Now you bind another default, newcitydflt, to the user
  10374.  datatype citytype. Although foes.city is a citytype column, the new default
  10375.  does not bind to it since its default has previously been changed.
  10376.  
  10377.  
  10378.  Unbinding Defaults
  10379.  
  10380.  Unbinding a default means disconnecting it from a particular column or
  10381.  user-defined datatype. An unbound default is still stored in the database
  10382.  and is available for future use.
  10383.  
  10384.  There are two ways to unbind a default:
  10385.  
  10386.  
  10387.    ■   Use the sp_unbindefault system procedure to remove the binding between
  10388.        a default and a column or datatype.
  10389.  
  10390.    ■   Use the sp_bindefault system procedure to bind a new default to that
  10391.        column or datatype. The old one is automatically unbound.
  10392.  
  10393.  
  10394.  Here's how you unbind the current default from the city column of the
  10395.  friends_etc table:
  10396.  
  10397.    execute sp_unbindefault "friends_etc.city"
  10398.  
  10399.  At this point, the default still exists, but it has no effect on the city
  10400.  column because it isn't connected to that column.
  10401.  
  10402.  To unbind a default from the user-defined datatype nm, type
  10403.  
  10404.    sp_unbindefault nm
  10405.  
  10406.  The sp_unbindefault system procedure has the following syntax:
  10407.  
  10408.    sp_unbindefault objname [, futureonly]
  10409.  
  10410.  If the objname parameter you supply is not of the form "table.column", SQL
  10411.  Server assumes it is a user-defined datatype.
  10412.  
  10413.  When you unbind a default from a user-defined datatype, the default is
  10414.  unbound from all columns of that type unless:
  10415.  
  10416.  
  10417.    ■   You give the optional second parameter, futureonly, which prevents
  10418.        existing columns of that datatype from losing their binding with the
  10419.        default
  10420.  
  10421.    ■   The default on a column of that user-defined datatype has been changed
  10422.        so that its current value is different from the default being unbound
  10423.  
  10424.  
  10425.  Here's an example that demonstrates the second case:
  10426.  
  10427.  
  10428.    1.  Create a user-defined datatype called nm.
  10429.  
  10430.    2.  Use nm in the CREATE statements for the tables friends_etc and enemies
  10431.        to create the columns friends_etc.pname, friends_etc.sname, and
  10432.        enemies.nickname.
  10433.  
  10434.    3.  Create a default called nmdflt and bind it to nm.
  10435.  
  10436.    4.  Change the default on enemies.nickname by creating a new default
  10437.        called nastydflt and binding it to enemies.nickname.
  10438.  
  10439.    5.  Now, if you unbind nmdflt from nm, only friends.pname and
  10440.        friends.sname are affected. Since the original default on
  10441.        enemies.nickname has been changed, that column's default is not
  10442.        unbound even though it is defined as type nm.
  10443.  
  10444.  
  10445.  
  10446.  Dropping Defaults
  10447.  
  10448.  If you want to remove a default from the database entirely, use the DROP
  10449.  DEFAULT statement. The default must be unbound from all columns and user
  10450.  datatypes before you can drop it. If you try to drop a default that is still
  10451.  bound, SQL Server displays an error message, and the DROP DEFAULT statement
  10452.  fails. However, you need not unbind and then drop a default to bind a new
  10453.  one. Simply bind another default in its place.
  10454.  
  10455.  Here's how to remove citydflt:
  10456.  
  10457.    drop default citydflt
  10458.  
  10459.  The DROP DEFAULT statement has the following syntax:
  10460.  
  10461.    DROP DEFAULT [owner.]default_name
  10462.     [, [owner.]default_name...]
  10463.  
  10464.  A default can be dropped only by its owner.
  10465.  
  10466.  
  10467.  Defaults and Null Values
  10468.  
  10469.  If you specify NOT NULL when you create a column and do not create a default
  10470.  for it, SQL Server will produce an error message whenever anyone inserts a
  10471.  row and fails to make an entry in that column.
  10472.  
  10473.  When you drop a default for a NULL column, NULL will from then on be
  10474.  inserted in that position by SQL Server when you add rows without entering
  10475.  any value for that column. When you drop a default for a NOT NULL column,
  10476.  you'll get an error message when rows are added but no value for that column
  10477.  is entered.
  10478.  
  10479.  The following table illustrates the relationship between the existence of a
  10480.  default and the definition of a column as NULL or NOT NULL. The entries in
  10481.  the table show the result:
  10482.  
  10483. ╓┌─────────┌─────────┌────────┌──────┌───────────────────────────────────────╖
  10484.            No entry
  10485.  ────────────────────────────────────────────────────────────────────────────
  10486.  NULL      null      default  null   null
  10487.  
  10488.  NOT NULL  error     default  error  error
  10489.  
  10490.  ────────────────────────────────────────────────────────────────────────────
  10491.  
  10492.  
  10493.  
  10494.  
  10495.  Rules
  10496.  
  10497.  Rules are integrity constraints that go beyond those implied by a column's
  10498.  datatype. They can be connected to a specific column, to several specific
  10499.  columns, or to all the columns in a database with a specified user-defined
  10500.  datatype.
  10501.  
  10502.  Every time a user enters a value (with an INSERT or UPDATE statement), SQL
  10503.  Server checks it against any rules that have been created for the specified
  10504.  column. Data entered prior to the creation and binding of a rule is not
  10505.  checked.
  10506.  
  10507.  ────────────────────────────────────────────────────────────────────────────
  10508.  NOTE
  10509.  
  10510.  You can bind a character type rule to a numeric type column even though it
  10511.  makes no sense to do so. Rules are checked when an INSERT or UPDATE is
  10512.  attempted, not at the time of binding.
  10513.  ────────────────────────────────────────────────────────────────────────────
  10514.  
  10515.  Rules are created with the CREATE RULE statement, and then bound to a column
  10516.  or user datatype with the sp_bindrule system procedure.
  10517.  
  10518.  
  10519.  Creating Rules
  10520.  
  10521.  The CREATE RULE statement has the following syntax:
  10522.  
  10523.    CREATE RULE [owner.]rule_name
  10524.     AS condition_expression
  10525.  
  10526.  Rule names must follow the rules for identifiers. You can create a rule in
  10527.  the current database only.
  10528.  
  10529.  Within a database, rule names must be unique for each user. A user cannot
  10530.  create two rules called socsecrule. However, two different users can create
  10531.  a rule named socsecrule because the owner names make each one distinct.
  10532.  
  10533.  Here's how the rule permitting five different pub_id numbers and one dummy
  10534.  value (99 followed by any two digits) was created:
  10535.  
  10536.    create rule pubidrule
  10537.     as @pub_id in("1389", "0736", "0877", "1622", "1756")
  10538.     or @pub_id like "99[0-9][0-9]"
  10539.  
  10540.  The AS clause contains the name of the rule's parameter (prefixed with @)
  10541.  and the definition of the rule itself. The parameter refers to the column
  10542.  value that is affected by the UPDATE or INSERT statement.
  10543.  
  10544.  In the preceding example, the parameter is @pub_id, a convenient name since
  10545.  this rule is to be bound to the pub_id column. You can use any name for the
  10546.  parameter, but the first character must be "@." Using the name of the column
  10547.  or datatype to which the rule will be bound can help you remember what it is
  10548.  for.
  10549.  
  10550.  The rule definition can contain any expression that is valid in a WHERE
  10551.  clause and can include arithmetic operators, comparison operators, LIKE, IN,
  10552.  BETWEEN, and so on. However, it cannot reference any column or other
  10553.  database object directly. Built-in functions that do not reference database
  10554.  objects can be included. (See the SQL Server Language Reference for a full
  10555.  definition of WHERE syntax.)
  10556.  
  10557.  
  10558.  Binding Rules
  10559.  
  10560.  After you've created a rule, use the sp_bindrule system procedure to link
  10561.  the rule to a column or user-defined datatype.
  10562.  
  10563.  This is how pubidrule was bound to publishers.pub_id:
  10564.  
  10565.    sp_bindrule pubidrule, "publishers.pub_id"
  10566.  
  10567.  Here's a rule to use when you are sure all the zip codes you enter will have
  10568.  946 as their first three digits:
  10569.  
  10570.    create rule ziprule946
  10571.     as @zip like "946[0-9][0-9]"
  10572.  
  10573.  Bind it to the zip column in friends_etc like this:
  10574.  
  10575.    sp_bindrule ziprule946, "friends_etc.zip"
  10576.  
  10577.  The following example creates a rule that forces the values you enter to
  10578.  comply with a particular format. In this case, each value entered in the
  10579.  column must begin with the digits "415" followed by seven more characters:
  10580.  
  10581.    create rule phonerule
  10582.     as @phone like '415_______'
  10583.  
  10584.  You can't bind a rule to a system datatype, but you can bind one to a
  10585.  user-defined datatype. To bind phonerule to a user-defined datatype called
  10586.  p#, type
  10587.  
  10588.    sp_bindrule phonerule, "p#"
  10589.  
  10590.  To make sure that the ages you enter for your friends are between 1 and 120
  10591.  but never 17, type
  10592.  
  10593.    create rule agerule
  10594.     as @age between 1 and 120 and @age !=17
  10595.  
  10596.  When you are entering data that requires special constraints on some
  10597.  columns, you can unbind any existing rules for those columns and create new
  10598.  rules to help check the data. For example, suppose that you are adding data
  10599.  to the debt column of the friends_etc table. You know that all the debts you
  10600.  want to record today are between $5 and $200. To avoid accidentally typing
  10601.  an amount outside these limits, create a rule like this one. (It allows for
  10602.  an entry of $0.00 because that is the default for this column.)
  10603.  
  10604.    create rule debtrule
  10605.     as @debt = $0.00 or @debt between $5.00 and $200.00
  10606.  
  10607.  Bind it to the debt column like this:
  10608.  
  10609.    sp_bindrule debtrule, "friends_etc.debt"
  10610.  
  10611.  The sp_bindrule system procedure has the following syntax:
  10612.  
  10613.    sp_bindrule rulename, objname [, futureonly]
  10614.  
  10615.  The rulename is the name of the rule created with CREATE RULE. The objname
  10616.  is the name of the table and column, or of the user-defined datatype to
  10617.  which the rule is to be bound. If the parameter is not of the form
  10618.  "table.column", it is assumed to be a user datatype.
  10619.  
  10620.  All columns of a specified user datatype become associated with the
  10621.  specified rule unless you use the optional third parameter, futureonly,
  10622.  which prevents existing columns of that user datatype from inheriting the
  10623.  rule, or unless their defaults have previously been changed. (See the
  10624.  "Defaults" section for examples of this second situation.)
  10625.  
  10626.  
  10627.  Unbinding Rules
  10628.  
  10629.  Unbinding a rule means disconnecting it from a particular column or
  10630.  user-defined datatype. An unbound rule's definition is still stored in the
  10631.  database and is available for future use.
  10632.  
  10633.  There are two ways to unbind a rule:
  10634.  
  10635.  
  10636.    ■   Use the sp_unbindrule system procedure to remove the binding between a
  10637.        rule and a column or datatype.
  10638.  
  10639.    ■   Use the sp_bindrule system procedure to bind a new rule to that column
  10640.        or datatype. The old one is automatically unbound.
  10641.  
  10642.  
  10643.  Here's how you'd disassociate debtrule or any other currently bound rule
  10644.  from friends_etc.debt:
  10645.  
  10646.    sp_unbindrule "friends_etc.debt"
  10647.  
  10648.  The rule is still in the database but has no connection to friends_etc.debt.
  10649.  
  10650.  
  10651.  To unbind a rule from the user-defined datatype p#, type
  10652.  
  10653.    sp_unbindrule "p#"
  10654.  
  10655.  The sp_unbindrule system procedure has the following syntax:
  10656.  
  10657.    sp_unbindrule objname [, futureonly]
  10658.  
  10659.  If the objname parameter you give is not of the form "table.column", SQL
  10660.  Server assumes it is a user-defined datatype.
  10661.  
  10662.  As is the case with defaults, when you unbind a rule from a user-defined
  10663.  datatype, the rule is unbound from all columns of that type unless
  10664.  
  10665.  
  10666.    ■   You give the optional second parameter, futureonly, which prevents
  10667.        existing columns of that datatype from losing their binding with the
  10668.        rule
  10669.  
  10670.    ■   The rule on a column of that user-defined datatype has been changed so
  10671.        that its current value is different from the rule being unbound
  10672.  
  10673.  
  10674.  
  10675.  Dropping Rules
  10676.  
  10677.  If you want to remove a rule from the database entirely, use the DROP RULE
  10678.  statement. The rule must be unbound from all columns and user datatypes
  10679.  before you can drop it. If you try to drop a rule that is still bound, SQL
  10680.  Server displays an error message and the DROP RULE statement fails. However,
  10681.  you need not unbind and then drop a rule to bind a new one. Simply bind a
  10682.  new one in its place.
  10683.  
  10684.  Here's how to remove phonerule:
  10685.  
  10686.    drop rule phonerule
  10687.  
  10688.  The DROP RULE statement has the following syntax:
  10689.  
  10690.    DROP RULE [owner.]rule_name
  10691.     [, [owner.]rule_name...]
  10692.  
  10693.  After you drop a rule, new data entered into the columns that were
  10694.  previously governed by it goes in without these constraints. Already
  10695.  existing data is not affected in any way.
  10696.  
  10697.  A rule can be dropped only by its owner.
  10698.  
  10699.  
  10700.  
  10701.  
  10702.  
  10703.  
  10704.  Chapter 9  Adding, Changing, and Removing Data
  10705.  ────────────────────────────────────────────────────────────────────────────
  10706.  
  10707.  
  10708.  Introduction
  10709.  
  10710.  Once you've created a database, tables, and indexes, you'll want to put data
  10711.  into the tables and work with it─adding, changing, and removing data as
  10712.  necessary.
  10713.  
  10714.  The INSERT statement lets you add new rows to the database. The UPDATE
  10715.  statement lets you change existing rows in the database. The DELETE
  10716.  statement lets you remove rows from the database.
  10717.  
  10718.  These three operations are collectively called data modification statements.
  10719.  The TRUNCATE TABLE statement, which deletes all the rows in a table, is also
  10720.  discussed in this chapter. Another method of adding data to a table is to
  10721.  transfer it from a file, using the bulk copy program, bcp. (For information
  10722.  about this utility program, see the SQL Server System Administrator's
  10723.  Guide.)
  10724.  
  10725.  You can modify (INSERT, UPDATE, or DELETE) data in only one table per
  10726.  statement. However, the modifications you make can be based on data in other
  10727.  tables, even those in other databases. (This is a TRANSACT-SQL enhancement
  10728.  to standard versions of SQL.)
  10729.  
  10730.  The data modification statements work on views as well as on tables, with
  10731.  some restrictions. (See Chapter 10, "Creating Views," for details.)
  10732.  
  10733.  
  10734.  Permissions
  10735.  
  10736.  Data modification statements are not necessarily available to everyone. The
  10737.  Database Owner and the owners of database objects can use the GRANT and
  10738.  REVOKE statements to decide who has access to which data-modification
  10739.  functions.
  10740.  
  10741.  Permissions can be granted to individual users, groups, or the public to use
  10742.  any combination of the data modification statements. (Permissions are
  10743.  discussed in Chapter 14, "Advanced Topics for Database Owners," and in
  10744.  greater detail in the SQL Server System Administrator's Guide.)
  10745.  
  10746.  
  10747.  Referential Integrity
  10748.  
  10749.  INSERT, UPDATE, DELETE, and TRUNCATE TABLE statements all allow you to
  10750.  change the data in the database. However, if you change data in one table
  10751.  without changing related data in other tables, disparities can develop.
  10752.  
  10753.  For example, if you discover that the au_id entry for Sylvia Panteley is
  10754.  incorrect and change it in the authors table, you must also change it in the
  10755.  titleauthor table (and in any other table in the database with a column
  10756.  containing that value). If you don't, you'll never be able to find
  10757.  information such as the names of Ms. Panteley's books, because it'll be
  10758.  impossible to make joins on her au_id column.
  10759.  
  10760.  The general problem of keeping data modifications consistent throughout all
  10761.  tables in a database is called referential integrity. One way to deal with
  10762.  it is to create special stored procedures called triggers that automatically
  10763.  go into effect when you give INSERT, UPDATE, and DELETE statements for
  10764.  particular tables or columns. A TRUNCATE TABLE statement is not caught by a
  10765.  DELETE trigger. (Triggers are discussed in Chapter 13, "Creating Triggers.")
  10766.  
  10767.  
  10768.  
  10769.  Transactions
  10770.  
  10771.  A copy of the old and new state of each row affected by each data
  10772.  modification statement is written to the transaction log. This means that if
  10773.  you begin a transaction by executing a BEGIN TRANSACTION statement, realize
  10774.  you have made a mistake, and roll the transaction back, the database can be
  10775.  restored to its previous condition. (A more complete explanation of
  10776.  transactions appears in Chapter 14, "Advanced Topics for Database Owners.")
  10777.  
  10778.  
  10779.  
  10780.  Using the Sample Database
  10781.  
  10782.  If you follow the examples in this chapter on your own screen, you will
  10783.  probably want to start with a clean copy of the pubs database. You should
  10784.  return it to its original state when you are finished. See your System
  10785.  Administrator for help in getting a clean copy of pubs.
  10786.  
  10787.  If you are starting with a clean copy of pubs, you can prevent any changes
  10788.  you make from becoming permanent by enclosing all the statements you enter
  10789.  inside a transaction and then aborting the transaction when you've finished
  10790.  with this chapter. Start the transaction by typing
  10791.  
  10792.    begin tran ch9
  10793.  
  10794.  This transaction is named ch9 for Chapter 9, "Adding, Changing, and Removing
  10795.  Data." You can cancel the transaction at any time and return the database to
  10796.  the condition it was in before you began the transaction by typing
  10797.  
  10798.    rollback tran ch9
  10799.  
  10800.  
  10801.  Datatype Entry Rules
  10802.  
  10803.  Several of the SQL Server-supplied datatypes have special rules for entering
  10804.  and searching for data. These rules are reviewed in the following
  10805.  subsections. (For more information on datatypes, see Chapter 7, "Creating
  10806.  Databases, Tables, and Indexes.")
  10807.  
  10808.  
  10809.  Char, Varchar, and Text
  10810.  
  10811.  Don't forget that all char, text, and datetime data must be enclosed in
  10812.  single or double quotation marks when it's input and when you're searching
  10813.  for it. See the SQL Server Language Reference for details on inserting text
  10814.  data.
  10815.  
  10816.  If you enter strings that are longer than the specified length of a char or
  10817.  varchar column, the entry is truncated without warning.
  10818.  
  10819.  There are two ways to specify literal quotes within a character entry. The
  10820.  first method is to use two quotation marks. For example, if you have begun a
  10821.  character entry with a single quotation mark and want to include a single
  10822.  quotation mark as part of the entry, use two single quotation marks:
  10823.  
  10824.    'I don"t understand.'
  10825.  
  10826.  With double quotation marks:
  10827.  
  10828.    "He said, ""It's not really confusing."""
  10829.  
  10830.  The second method is to enclose a quote in the opposite kind of quotation
  10831.  mark. In other words, surround an entry containing a double quotation mark
  10832.  with single quotation marks (or vice versa). For example:
  10833.  
  10834.    'George said, "There must be a better way."'
  10835.     "Isn't there a better way?"
  10836.     'George asked, "Isn't there a better way?"'
  10837.  
  10838.  To enter a character string longer than the width of your screen, enter a
  10839.  backslash (\) before going to the following line.
  10840.  
  10841.  The LIKE keyword and wildcards can be used when searching for char, text,
  10842.  and datetime data. (See Chapter 2, "Querying Databases.")
  10843.  
  10844.  
  10845.  Datetime
  10846.  
  10847.  When you enter datetime values, always enclose them in single or double
  10848.  quotation marks.
  10849.  
  10850.  SQL Server recognizes a wide variety of data entry formats. Case is always
  10851.  ignored, and spaces can occur anywhere between date parts. The default
  10852.  display format for dates is Apr 15 1987 10:23PM.
  10853.  
  10854.  When time data is entered, the order of time components is significant.
  10855.  Enter hours; then minutes; then seconds; then milliseconds; and then AM, am,
  10856.  PM, or pm (12AM is midnight; 12PM is noon). To be recognized as time, a
  10857.  value must contain either a colon or an AM/PM signifier.
  10858.  
  10859.  Milliseconds can be preceded either with a colon or a period. If preceded
  10860.  with a colon, the number means thousandths of a second. If preceded by a
  10861.  period, a single digit means tenths of a second, two digits mean hundredths
  10862.  of a second, and three digits mean thousandths of a second. For example,
  10863.  12:30:20:1 means twenty and one-thousandth of a second past 12:30;
  10864.  12:30:20.1 means twenty and one-tenth of a second past 12:30.
  10865.  
  10866.  The following formats are acceptable for time data:
  10867.  
  10868.    14:30
  10869.     14:30[:20:999]
  10870.     14:30[:20.9]
  10871.     4am
  10872.     4 PM
  10873.     [0]4[:30:20:500]AM
  10874.  
  10875.  When date data is entered, the order of components can vary. Months can be
  10876.  in alphabetic or numeric format. Alphabetic format is either the full name
  10877.  of the month or its first three letters. Case is not significant.
  10878.  
  10879.  If the month is given in numeric format, you can use any of the separators.
  10880.  Use a slash (/), hyphen (-), period (.), or space ( ). You can also give a
  10881.  date without separators. You can enter January 1, 1998, as 19980101 or
  10882.  980101.
  10883.  
  10884.  If the month is given in alphabetic format, the day and year can be in any
  10885.  location either before or after the month. In addition to these separators,
  10886.  the day can optionally be followed by a comma (,). When the month is
  10887.  alphabetic and the values for day and year are grouped together, the first
  10888.  value is assumed to be the day. For example, 2 3 mar is stored as Mar 2 2003
  10889.  12:00:00AM.
  10890.  
  10891.  If the year is given with two digits, <50 is the century 2000 and >=50 is
  10892.  the century 1900. So 25 is 2025 while 50 is 1950.
  10893.  
  10894.  The following formats are acceptable for datetime data:
  10895.  
  10896.    Apr[il] 15[,] [19]87
  10897.     [15] Apr[il][,] [19]87
  10898.     1987 APR[IL]
  10899.     5/15/1987
  10900.     5-15-87
  10901.     [19]87[0415]
  10902.  
  10903.  A datetime value can be entered either as time followed by date or as date
  10904.  followed by time, or the year can be separated from the rest of the date,
  10905.  like this:
  10906.  
  10907.    10:23PM Apr 15 1987
  10908.     Apr 15 1987 10:23PM
  10909.     Apr 15 10:23PM 1987
  10910.  
  10911.  If time is missing, it defaults to midnight. For example, if you insert Apr
  10912.  15 1987, SQL Server stores this as Apr 15 1987 12:00AM.
  10913.  
  10914.  If the day of the month is missing, it defaults to the first day of the
  10915.  month. If the month is missing, it defaults to January. If the entire date
  10916.  is missing, it defaults to the base date, January 1, 1900. For example, if
  10917.  you insert 4:33, SQL Server stores it as Jan 1 1900 4:33AM.
  10918.  
  10919.  You can use the LIKE keyword and wildcard characters with datetime data as
  10920.  well as with char, varchar, and text. When you use LIKE with datetime
  10921.  values, SQL Server converts the dates to the standard datetime format and
  10922.  then to varchar. Since the standard storage format doesn't include seconds
  10923.  or milliseconds, you cannot search for seconds or milliseconds with LIKE and
  10924.  a match pattern.
  10925.  
  10926.  It is a good idea to use LIKE when you search for datetime values since
  10927.  datetime entries can contain a variety of date parts. For example, if you
  10928.  insert the value 9:20 into a column named arrival_time, the clause where
  10929.  arrival_time = 9:20 would not find it because SQL Server converts the entry
  10930.  into Jan 1, 1900 9:20AM. However, the clause where arrival_time like
  10931.  `%9:20%' would find it.
  10932.  
  10933.  Use the STYLE parameter of the CONVERT statement to get several additional
  10934.  date display formats by converting datetime data to char or varchar.
  10935.  
  10936.  
  10937.  Binary, Varbinary, and Image
  10938.  
  10939.  When binary, varbinary, or image data is entered or searched for, it must be
  10940.  preceded with "0x". For example, to enter FF, type 0xFF.
  10941.  
  10942.  If you enter strings that are longer than the specified length of a binary
  10943.  or varbinary column, the entry is truncated without warning.
  10944.  
  10945.  A length of 10 for a binary or varbinary column means 20 characters.
  10946.  
  10947.  When you create a default on a binary or varbinary column, precede it with
  10948.  "0x".
  10949.  
  10950.  
  10951.  Money
  10952.  
  10953.  Money data should be preceded with a dollar sign ($) when you enter or
  10954.  search for it. If there is no $, SQL Server treats the value as a float.
  10955.  Depending on the exact input value, SQL Server may not accept it or may lose
  10956.  some of the value's precision. The minus sign, representing negative money
  10957.  values, must be placed after the dollar sign. You cannot enter money values
  10958.  with commas, although the default print format for money data places a comma
  10959.  after every three digits. When money values are displayed, they are rounded
  10960.  off to the nearest cent. All the arithmetic operations except modulo are
  10961.  available with money.
  10962.  
  10963.  
  10964.  Float
  10965.  
  10966.  The exact format for float data depends on the precision and number of
  10967.  significant digits that your machine supports. See your System Administrator
  10968.  for details.
  10969.  
  10970.  On all machines, you can enter float data with or without a decimal point
  10971.  and a positive or negative sign. An exponential component of float data is
  10972.  also optional. For float data with an exponential component, enter a number,
  10973.  followed by e or E, followed by a number that can include a sign but not a
  10974.  decimal point.
  10975.  
  10976.  Here are some examples of float data as you would enter it:
  10977.  
  10978.    10E2
  10979.     15.3e1
  10980.     2.e5
  10981.     2.2e-1
  10982.     +56E+2
  10983.  
  10984.  The value represented by a float is the product of the first number and the
  10985.  power of 10 of the second number. This value is computed and displayed by
  10986.  SQL Server.
  10987.  
  10988.  
  10989.  Int, Smallint, and Tinyint
  10990.  
  10991.  You can insert numeric values into int, smallint, and tinyint columns with
  10992.  the E-notation described in the preceding section.
  10993.  
  10994.  
  10995.  Adding New Rows: INSERT
  10996.  
  10997.  Use the INSERT statement to add rows to the database in two ways: with the
  10998.  VALUES keyword or with a SELECT statement.
  10999.  
  11000.  The VALUES keyword is used to specify values for some or all of the columns
  11001.  in a new row. A simplified syntax for the INSERT statement using the VALUES
  11002.  keyword is
  11003.  
  11004.    INSERT table_name
  11005.     VALUES (constant1, constant2, ...)
  11006.  
  11007.  Use a SELECT statement in an INSERT statement to pull values from one or
  11008.  more other tables. A simplified syntax for the INSERT statement using a
  11009.  SELECT statement is
  11010.  
  11011.    INSERT table_name
  11012.     SELECT column_list
  11013.     FROM table_list
  11014.     WHERE search_conditions
  11015.  
  11016.  The full syntax for the INSERT statement is
  11017.  
  11018.    INSERT [INTO]
  11019.     [[database.]owner.]{table_name | view_name} [(column_list)]
  11020.     {VALUES (constant_expression [, constant_expression...]) |
  11021.     SELECT_statement}
  11022.  
  11023.  ────────────────────────────────────────────────────────────────────────────
  11024.  NOTE
  11025.  
  11026.  When text and image values are added with the INSERT statement, all of the
  11027.  data is written to the transaction log. The WRITETEXT statement allows you
  11028.  to add these values without logging the large amounts of data that may
  11029.  consist of text or image values. See "Inserting Data into Some Columns" and
  11030.  "Adding or Changing Data with WRITETEXT" later in this chapter.
  11031.  
  11032.  ────────────────────────────────────────────────────────────────────────────
  11033.  
  11034.  
  11035.  Adding New Rows with VALUES
  11036.  
  11037.  This INSERT statement adds a new row to the publishers table, giving a value
  11038.  for every column in the row:
  11039.  
  11040.    insert into publishers
  11041.     values ('1622', 'Jardin, Inc.', 'Camden', 'NJ')
  11042.  
  11043.  Notice that the data values are typed in the same order as the column names
  11044.  in the original CREATE TABLE statement (that is, first the ID number, then
  11045.  the name, the city, and finally the state). The VALUES data is surrounded by
  11046.  parentheses and all character data is enclosed in single or double quotation
  11047.  marks.
  11048.  
  11049.  ────────────────────────────────────────────────────────────────────────────
  11050.  NOTE
  11051.  
  11052.  Use a separate INSERT statement for each row you add.
  11053.  
  11054.  ────────────────────────────────────────────────────────────────────────────
  11055.  
  11056.  
  11057.  Inserting Data into Some Columns
  11058.  
  11059.  You can add data to some, but not all, of the columns in a row by specifying
  11060.  those columns. For example, adding data in only two columns (say pub_id and
  11061.  pub_name) requires a statement like this:
  11062.  
  11063.    insert into publishers (pub_id, pub_name)
  11064.     values ('1756', 'The Health Center')
  11065.  
  11066.  The order in which you list the column names must match the order in which
  11067.  you list the values. The following example produces the same results as the
  11068.  previous one:
  11069.  
  11070.    insert publishers (pub_name, pub_id)
  11071.     values('The Health Center', '1756')
  11072.  
  11073.  Either of the INSERT statements puts "1756" in the identification number
  11074.  column and "The Health Center" in the publisher name column. Since the
  11075.  pub_id column in publishers has a unique index, you can't execute both of
  11076.  these INSERT statements; the second attempt to insert a pub_id value of
  11077.  "1756" produces an error message.
  11078.  
  11079.  
  11080.  Null Values, Defaults, and Errors
  11081.  
  11082.  The following SELECT statement shows the row that was added to publishers:
  11083.  
  11084.    select *
  11085.     from publishers
  11086.     where pub_name = 'The Health Center'
  11087.  
  11088.     pub_id   pub_name    city   state
  11089.     ------   ----------------  ----   -----
  11090.     1756   The Health Center   NULL   NULL
  11091.  
  11092.  SQL Server enters null values in the city and state columns because no value
  11093.  was given for these columns in the INSERT statement, and the publisher table
  11094.  allows null values in these columns.
  11095.  
  11096.  When you specify values for only some of the columns in a row, one of three
  11097.  things can happen to the columns with no values:
  11098.  
  11099.  
  11100.    ■   A default value is entered if one exists for the column or
  11101.        user-defined datatype. (See Chapter 8, "Creating Defaults and Rules,"
  11102.        or the CREATE DEFAULT entry in the SQL Server Language Reference for
  11103.        details.)
  11104.  
  11105.    ■   NULL is entered if NULL was specified for the column when the table
  11106.        was created and no default value exists for the column or datatype.
  11107.        (See the CREATE TABLE entry in the SQL Server Language Reference.)
  11108.  
  11109.    ■   An error message is displayed and the row is not added if NULL was not
  11110.        specified and no default exists.
  11111.  
  11112.  
  11113.  The following table shows you what you would see under these circumstances:
  11114.  
  11115.  
  11116. ╓┌───────────┌──────────────┌────────────────────────────────────────────────╖
  11117.              No NULL        NULL
  11118.  ────────────────────────────────────────────────────────────────────────────
  11119.  Default     the default    the default
  11120.  
  11121.  No Default  error message  NULL
  11122.  
  11123.  ────────────────────────────────────────────────────────────────────────────
  11124.  
  11125.  
  11126.  
  11127.  You can use the sp_help system procedure to get a report on a specified
  11128.  table or default (or on any other object listed in the system table
  11129.  sysobjects). To see the definition of a default, use the sp_helptext system
  11130.  procedure.
  11131.  
  11132.  
  11133.  Rules
  11134.  
  11135.  As explained in Chapter 8, "Creating Defaults and Rules," you can create a
  11136.  rule and bind it to a column or user-defined datatype. Rules govern the kind
  11137.  of data that may be added.
  11138.  
  11139.  The pub_id column in the pubs database is an example: a rule called
  11140.  pub_idrule, which specifies acceptable publisher identification numbers, is
  11141.  bound to the column. The acceptable IDs are 1389, 0736, 0877, 1622, and
  11142.  1756, or any 4-digit number the first two digits of which are 99. If you try
  11143.  to enter any other number, you get an error message.
  11144.  
  11145.  When you get this kind of error message, you may want to look at the
  11146.  definition of the rule. Use the sp_helptext system procedure:
  11147.  
  11148.    sp_helptext pub_idrule
  11149.  
  11150.     ----------
  11151.     1
  11152.  
  11153.     (1 row affected)
  11154.  
  11155.     text
  11156.     ------------------------------------------------------
  11157.     create rule pub_idrule
  11158.     as @pub_id in ("1389", "0736", "0877", "1622", "1756")
  11159.     or @pub_id like "99[0-9][0-9]"
  11160.  
  11161.     (1 row affected)
  11162.  
  11163.  For more general information on a rule, use sp_help. Or use sp_help with a
  11164.  table and column name as parameters to find out whether the specified column
  11165.  has a rule.
  11166.  
  11167.  
  11168.  Adding New Rows with SELECT
  11169.  
  11170.  To pull values into a table from one or more other tables, use a SELECT
  11171.  clause in the INSERT statement. The SELECT clause can insert values into
  11172.  some or all of the columns in a row.
  11173.  
  11174.  Inserting values for only some columns can come in handy when you want to
  11175.  take some values from an existing table. Then you can use UPDATE to add the
  11176.  values for the other columns.
  11177.  
  11178.  Before inserting values for some (but not all) of the columns in a table,
  11179.  make sure that a default exists or NULL has been specified for the columns
  11180.  for which you are not inserting values. Otherwise, you'll get an error
  11181.  message.
  11182.  
  11183.  When you insert rows from one table into another, the two tables must have
  11184.  compatible structures─that is, the matching columns must be of the same
  11185.  datatypes or datatypes between which SQL Server automatically converts.
  11186.  
  11187.  ────────────────────────────────────────────────────────────────────────────
  11188.  NOTE
  11189.  
  11190.  You cannot insert data from a table that allows null values into a table
  11191.  that does not, even though none of the data being inserted is null.
  11192.  ────────────────────────────────────────────────────────────────────────────
  11193.  
  11194.  If the columns are in the same order in their CREATE TABLE statements, you
  11195.  don't need to specify column names in either table. Suppose newauthors
  11196.  contains some rows of author information in the same format as authors. To
  11197.  add to authors all the rows in newauthors, type
  11198.  
  11199.    insert authors
  11200.     select *
  11201.     from newauthors
  11202.  
  11203.  To insert rows into a table based on data in another table, the columns in
  11204.  the two tables do not have to be listed in the same sequence in their
  11205.  respective CREATE TABLE statements. You can use either the INSERT or the
  11206.  SELECT statement to order the columns so that they match.
  11207.  
  11208.  For example, say the CREATE TABLE statement for the authors table contained
  11209.  the columns au_id, au_fname, au_lname, and address in that order, while
  11210.  newauthor contained au_id, address, au_lname, and au_fname. You'd have to
  11211.  make the column sequence match in the INSERT statement. You could do this in
  11212.  either of these two ways:
  11213.  
  11214.    insert authors (au_id, address, au_lname, au_fname)
  11215.     select * from newauthors
  11216.  
  11217.     insert authors
  11218.     select au_id, au_fname, au_lname, address
  11219.     from newauthors
  11220.  
  11221.  If the column sequence in the two tables fails to match, SQL Server cannot
  11222.  complete the INSERT operation or completes it incorrectly, putting data in
  11223.  the wrong column. For example, you might get address data in the au_lname
  11224.  column.
  11225.  
  11226.  
  11227.  Computed Columns
  11228.  
  11229.  You can use computed columns in a SELECT statement inside an INSERT
  11230.  statement. For example, imagine that a table named tmp contains some new
  11231.  rows for the titles table with some out-of-date data; the price figures need
  11232.  to be doubled. A statement to increase the prices and insert the tmp rows
  11233.  into titles looks like this:
  11234.  
  11235.    insert titles
  11236.     select title_id, title, type, pub_id, price*2,
  11237.     advance, royalty, ytd_sales, notes, pubdate
  11238.     from tmp
  11239.  
  11240.  When you perform computations on a column, you cannot use the SELECT *
  11241.  syntax. Each column must be named individually in the select list.
  11242.  
  11243.  
  11244.  Inserting Data into Some Columns
  11245.  
  11246.  You can use the SELECT statement to add data to some, but not all, of the
  11247.  columns in a row just as you do with the VALUES clause. Simply specify the
  11248.  columns to which you want to add data in the INSERT clause.
  11249.  
  11250.  For example, there are some authors in the authors table who do not have
  11251.  contracts and hence do not have entries in the titleauthor table. To pull
  11252.  their au_id numbers out of the authors table and insert them into the
  11253.  titleauthor table as placeholders, you might try to use this statement:
  11254.  
  11255.    insert titleauthor (au_id)
  11256.     select au_id
  11257.     from authors
  11258.     where contract = 0
  11259.  
  11260.  However, this statement is not legal because a value is required for the
  11261.  title_id column (null values are not permitted and no default is specified).
  11262.  You can put in xxxxxx as a dummy value for title_id like this, using it as a
  11263.  constant:
  11264.  
  11265.    insert titleauthor (au_id, title_id)
  11266.     select au_id, "xxxxxx"
  11267.     from authors
  11268.     where contract = 0
  11269.  
  11270.  The titleauthor table now contains four new rows with entries for the au_id
  11271.  column, dummy entries for the title_id column, and null values for the other
  11272.  two columns.
  11273.  
  11274.  
  11275.  Inserting Data from the Same Table
  11276.  
  11277.  You can insert data into a table based on other data in the same table.
  11278.  Essentially, this means copying all or part of a row.
  11279.  
  11280.  For example, you can insert a new row in the publishers table that is based
  11281.  on the values in an already existing row in the same table. (Make sure you
  11282.  follow the rule on the pub_id column.) Here's how:
  11283.  
  11284.    insert publishers
  11285.     select "9999", "test", city, state
  11286.     from publishers
  11287.     where pub_name = "New Age Books"
  11288.  
  11289.     (1 row affected)
  11290.  
  11291.     select * from publishers
  11292.  
  11293.     pub_id  pub_name     city   state
  11294.     ------  --------------------  ----------  -----
  11295.     0736  New Age Books    Boston   MA
  11296.     0877  Binnet & Hardley   Washington  DC
  11297.     1389  Algodata Infosystems  Berkeley  CA
  11298.     9999  test      Boston   MA
  11299.  
  11300.     (4 rows affected)
  11301.  
  11302.  
  11303.  Changing Existing Data: UPDATE
  11304.  
  11305.  Use the UPDATE statement to change single rows, groups of rows, or all the
  11306.  rows in a table.
  11307.  
  11308.  The UPDATE statement specifies the row or rows you want changed and the new
  11309.  data. The new data can be a constant or expression that you specify, or data
  11310.  pulled from other tables.
  11311.  
  11312.  ────────────────────────────────────────────────────────────────────────────
  11313.  NOTE
  11314.  
  11315.  The UPDATE statement is logged; if you are changing large blocks of text or
  11316.  image data, you may wish to use the WRITETEXT statement, which is not
  11317.  logged. See "Adding or Changing Data with WRITETEXT" later in this chapter.
  11318.  ────────────────────────────────────────────────────────────────────────────
  11319.  
  11320.  Here's a simplified version of the UPDATE syntax for updating specified rows
  11321.  with an expression:
  11322.  
  11323.    UPDATE table_name
  11324.     SET column_name = expression
  11325.     WHERE search_conditions
  11326.  
  11327.  For example, if Reginald Blotchet-Halls decides to change his name to
  11328.  Goodbody Health, here's how to change his row in the authors table:
  11329.  
  11330.    update authors
  11331.     set au_lname = "Health", au_fname = "Goodbody"
  11332.     where au_lname = "Blotchet-Halls"
  11333.  
  11334.  This simplified syntax statement updates a table based on data from another
  11335.  table:
  11336.  
  11337.    UPDATE table_name
  11338.     SET column_name = expression
  11339.     FROM table_name
  11340.     WHERE search_conditions
  11341.  
  11342.  Here's an example that updates the ytd_sales column of the titles table to
  11343.  reflect the most recent sales recorded in the sales table:
  11344.  
  11345.    update titles
  11346.     set ytd_sales = ytd_sales + qty
  11347.     from titles, sales
  11348.     where titles.title_id = sales.title_id
  11349.     and sales.date in (select max(sales.date) from sales)
  11350.  
  11351.  The preceding example assumes that only one set of sales is recorded for a
  11352.  given title on a given date and that updates are up to date.
  11353.  
  11354.  The full syntax for the UPDATE statement is
  11355.  
  11356.    UPDATE [[database.]owner.]{table_name | view_name}
  11357.     SET [[[database.]owner.]{table_name. | view_name.}]
  11358.     column_name1 = {expression1 | NULL}
  11359.     [, column_name2 = {expression2 | NULL}...]
  11360.     [FROM [[database.]owner.]{table_name | view_name}
  11361.     [, [[database.]owner.]{table_name | view_name}]...]
  11362.     [WHERE search_conditions]
  11363.  
  11364.  
  11365.  The UPDATE Clause
  11366.  
  11367.  The UPDATE statement is followed by the name of a table or view. As in all
  11368.  the data modification statements, you can change the data in only one table
  11369.  at a time.
  11370.  
  11371.  If an UPDATE statement violates an integrity constraint (if one of the
  11372.  values being added is the wrong datatype, or violates a rule that has been
  11373.  defined for one of the columns or datatypes involved), the update does not
  11374.  take place and an error message is displayed.
  11375.  
  11376.  (See Chapter 10, "Creating Views," for restrictions on updating views.)
  11377.  
  11378.  
  11379.  The SET Clause
  11380.  
  11381.  The SET clause specifies the column(s) and the changed value(s). The WHERE
  11382.  clause determines which row or rows will be updated. Note that if you don't
  11383.  have a WHERE clause, the specified columns of all rows will be updated with
  11384.  the values given in the SET clause.
  11385.  
  11386.  For example, if all the publishing houses in the publishers table move their
  11387.  head offices to Atlanta, Georgia, this is how you update the table:
  11388.  
  11389.    update publishers
  11390.     set city = "Atlanta", state = "GA"
  11391.  
  11392.  In the same way, you can change the names of all the publishers to NULL with
  11393.  this statement:
  11394.  
  11395.    update publishers
  11396.     set pub_name = null
  11397.  
  11398.  You can also use computed column values in an update. To double all the
  11399.  prices in the titles table, use this statement:
  11400.  
  11401.    update titles
  11402.     set price = price * 2
  11403.  
  11404.  Since there is no WHERE clause, the change in prices is applied to every row
  11405.  in the table.
  11406.  
  11407.  
  11408.  The WHERE Clause
  11409.  
  11410.  The WHERE clause specifies which rows are to be updated. For example, in the
  11411.  unlikely event that northern California is renamed Pacifica (abbreviated PC)
  11412.  and the people of Oakland vote to change the name of their city to something
  11413.  exciting (like Big Bad Bay City), here is how you can update the authors
  11414.  table for all former Oakland residents whose addresses are now out of date:
  11415.  
  11416.  
  11417.    update authors
  11418.     set state = "PC", city = "Big Bad Bay City"
  11419.     where state = "CA" and city = "Oakland"
  11420.  
  11421.  You need to write another statement to change the name of the state for
  11422.  residents of other northern California cities.
  11423.  
  11424.  
  11425.  The FROM Clause
  11426.  
  11427.  Use the FROM clause to pull data from one or more tables into the table
  11428.  you're updating.
  11429.  
  11430.  For example, earlier in this chapter, an example was given for inserting
  11431.  some new rows into the titleauthor table for authors without contracts,
  11432.  filling in the au_id column and giving dummy or null values for the other
  11433.  columns. When one of these authors, Dirk Stringer, gets a contract, a title
  11434.  identification number is assigned to his book, The Psychology of Computer
  11435.  Cooking, in the titles table. You can modify his row in the titleauthor
  11436.  table by adding a title identification number for him:
  11437.  
  11438.    update titleauthor
  11439.     set title_id = titles.title_id
  11440.     from titleauthor, titles, authors
  11441.     where titles.title = "The Psychology of Computer Cooking"
  11442.      and authors.au_id = titleauthor.au_id
  11443.      and au_lname = "Stringer"
  11444.  
  11445.  Note that an UPDATE without the au_id join changes all the title_ids in the
  11446.  titleauthor table so that they are the same as The Psychology of Computer
  11447.  Cooking's identification number.
  11448.  
  11449.  
  11450.  Adding or Changing Data with WRITETEXT
  11451.  
  11452.  The WRITETEXT statement is used to change text or image values. This
  11453.  statement completely overwrites any existing data in the column it affects.
  11454.  As a default, WRITETEXT statements are not logged. This prevents you from
  11455.  filling up the transaction log with the large amounts of data that often
  11456.  comprise these datatypes.
  11457.  
  11458.  ────────────────────────────────────────────────────────────────────────────
  11459.  NOTE
  11460.  
  11461.  The System Administrator must use the sp_dboption system procedure to set
  11462.  select into/bulk copy to true for the WRITETEXT statement to be used without
  11463.  logging changes.
  11464.  ────────────────────────────────────────────────────────────────────────────
  11465.  
  11466.  The following example adds text to an existing row in the blurbs table:
  11467.  
  11468.    declare @val varbinary(30)
  11469.     select @val = texptr(blurb) from blurbs
  11470.     where title_id = "TC4203"
  11471.     writetext blurbs.blurb @val
  11472.     "This book is a must for Anglophile food freaks"
  11473.  
  11474.  For this statement to work, the column must already contain a valid text
  11475.  pointer. This means that some value, even an explicit NULL, must already
  11476.  have been inserted. You might create the row with the following INSERT
  11477.  statement that inserts only the title_id and NULL for the text column:
  11478.  
  11479.    insert blurbs
  11480.     values ("TC4203", NULL)
  11481.  
  11482.  ────────────────────────────────────────────────────────────────────────────
  11483.  NOTE
  11484.  
  11485.  You cannot use WRITETEXT on text and image columns in views.
  11486.  ────────────────────────────────────────────────────────────────────────────
  11487.  
  11488.  
  11489.  Removing Data: DELETE
  11490.  
  11491.  Like INSERT and UPDATE, DELETE works for single-row as well as multiple-row
  11492.  operations but is more suitable for the latter. As for the other data
  11493.  modification statements, you can delete rows based on data in other tables.
  11494.  
  11495.  
  11496.  If you decide to remove one row from publishers, the row added for Jardin,
  11497.  Inc., type
  11498.  
  11499.    delete publishers
  11500.     where pub_name = "Jardin, Inc."
  11501.  
  11502.  A simplified syntax for the DELETE statement is
  11503.  
  11504.    DELETE table_name
  11505.     WHERE column_name = expression
  11506.  
  11507.  Here is the complete syntax statement, which shows that you can remove rows
  11508.  either on the basis of specified expressions or based on data from other
  11509.  tables:
  11510.  
  11511.    DELETE [FROM] [[database.]owner.]{table_name | view_name}
  11512.     [FROM [[database.]owner.]{table_name | view_name}
  11513.     [, [[database.]owner.]{table_name | view_name}]...]
  11514.     [WHERE search_conditions]
  11515.  
  11516.  
  11517.  The DELETE Clause
  11518.  
  11519.  The optional FROM directly after DELETE is included for compatibility with
  11520.  other versions of SQL. (The FROM on the second line is a TRANSACT-SQL
  11521.  enhancement that allows you to make deletions based on data in other
  11522.  tables.)
  11523.  
  11524.  
  11525.  The WHERE Clause
  11526.  
  11527.  The WHERE clause specifies which rows are to be removed. When no WHERE
  11528.  clause is given in the DELETE statement, all rows in the table are removed.
  11529.  
  11530.  
  11531.  
  11532.  The FROM Clause
  11533.  
  11534.  The FROM clause in the second position of a DELETE statement is a special
  11535.  TRANSACT-SQL feature that allows you to select data from a table or tables
  11536.  and delete corresponding data from the first-named table. The rows you
  11537.  select in the FROM clause specify the conditions for the DELETE.
  11538.  
  11539.  Suppose that a complex corporate deal results in the acquisition of all the
  11540.  Big Bad Bay City (formerly Oakland) authors and their books by another
  11541.  publisher. You need to remove all these books from the titles table right
  11542.  away, but you don't know their titles or identification numbers. The only
  11543.  information you have is the authors' names and addresses.
  11544.  
  11545.  You can delete the rows in titles by finding the author identification
  11546.  numbers for the rows that have Big Bad Bay City as the town in the authors
  11547.  table and using these numbers to find the title identification numbers of
  11548.  the books in the titleauthor table. In other words, a three-way join is
  11549.  required to find the rows you want to delete in the titles table.
  11550.  
  11551.  The three tables are all included in the FROM clause of the DELETE
  11552.  statement. However, only the rows in the titles table that fulfill the
  11553.  conditions of the WHERE clause are deleted. You would have to do separate
  11554.  deletes to remove relevant rows in tables other than titles.
  11555.  
  11556.  Here's the statement you need:
  11557.  
  11558.    delete titles
  11559.     from authors, titles, titleauthor
  11560.     where titles.title_id = titleauthor.title_id
  11561.      and authors.au_id = titleauthor.au_id
  11562.      and city = "Big Bad Bay City"
  11563.  
  11564.  The deltitle trigger in the pubs database prevents you from actually
  11565.  performing this deletion since it won't allow you to delete any titles that
  11566.  have sales recorded in the sales table.
  11567.  
  11568.  
  11569.  Deleting All Rows: TRUNCATE TABLE
  11570.  
  11571.  Use TRUNCATE TABLE as a fast, nonlogged method of deleting all the rows in a
  11572.  table. TRUNCATE TABLE immediately frees all the space that the table's data
  11573.  and indexes had occupied. The freed space can then be used by any object.
  11574.  The distribution pages for all indexes are also freed. Remember to run
  11575.  UPDATE STATISTICS after adding new rows to the table.
  11576.  
  11577.  As with DELETE, a table emptied with the TRUNCATE TABLE statement remains in
  11578.  the database (along with its indexes and other associated objects) unless
  11579.  you enter a DROP TABLE statement.
  11580.  
  11581.  The TRUNCATE TABLE statement has the following syntax:
  11582.  
  11583.    TRUNCATE TABLE [[database.]owner.]table_name
  11584.  
  11585.  For example, to remove all the data in sales, type
  11586.  
  11587.    truncate table sales
  11588.  
  11589.  Permission to use the TRUNCATE TABLE statement, like DROP TABLE, defaults to
  11590.  the table owner and cannot be transferred.
  11591.  
  11592.  A TRUNCATE TABLE statement is not caught by a DELETE trigger. (See Chapter
  11593.  13, "Creating Triggers," for details.)
  11594.  
  11595.  
  11596.  
  11597.  
  11598.  
  11599.  
  11600.  Chapter 10  Creating Views
  11601.  ────────────────────────────────────────────────────────────────────────────
  11602.  
  11603.  
  11604.  Introduction
  11605.  
  11606.  A view is an alternative way of looking at data in one or more tables. You
  11607.  can think of a view as a shifting frame through which you can see the
  11608.  particular data in which you're interested. That's why one speaks of looking
  11609.  at data or changing data through a view.
  11610.  
  11611.  A view is derived from one or more tables whose data is physically stored in
  11612.  the database. The tables or tables from which a view is derived are called
  11613.  base tables. A view can also be derived from another view.
  11614.  
  11615.  The definition of a view (in terms of the base tables from which it is
  11616.  derived) is stored in the database. No separate copies of data are
  11617.  associated with this stored definition. The data that you view is stored in
  11618.  the base tables.
  11619.  
  11620.  A view looks exactly like any other database table. You can display it and
  11621.  operate on it almost exactly as you can any other table. TRANSACT-SQL has
  11622.  been enhanced so that there are no restrictions on querying through views
  11623.  and fewer than usual on modifying them. (The exceptions are explained later
  11624.  in this chapter.)
  11625.  
  11626.  When you modify the data you see through a view, you are actually changing
  11627.  the data in the underlying base tables. Conversely, changes to data in the
  11628.  underlying base tables are automatically reflected in the views derived from
  11629.  them.
  11630.  
  11631.  Views can be used to focus, simplify, and customize each user's perception
  11632.  of the database. They also provide a security mechanism. These advantages
  11633.  are discussed later in this chapter.
  11634.  
  11635.  This chapter discusses:
  11636.  
  11637.  
  11638.    ■   The advantages of views
  11639.  
  11640.    ■   Creating views
  11641.  
  11642.    ■   Retrieving data through views
  11643.  
  11644.    ■   Updating data through views
  11645.  
  11646.  
  11647.  
  11648.  Advantages of Views
  11649.  
  11650.  The examples in this chapter demonstrate that views can be used to focus,
  11651.  simplify, and customize each user's perception of the database. Views also
  11652.  provide an easy-to-use security measure. In addition, they can be helpful
  11653.  when changes are made to the structure of the database and users prefer to
  11654.  work with the database in the style to which they have become accustomed.
  11655.  
  11656.  
  11657.  Focus
  11658.  
  11659.  Views allow users to focus in on the particular data that interests them and
  11660.  on the particular tasks for which they're responsible. Data that is not of
  11661.  interest to a particular user or for a particular task can be left out of
  11662.  the view.
  11663.  
  11664.  
  11665.  Simpler Data Manipulation
  11666.  
  11667.  Not only the users' perception of the data but also their manipulation of it
  11668.  can be simplified with views. Frequently used joins, projections, and/or
  11669.  selections can be defined as views so that users don't have to specify all
  11670.  the conditions and qualifications each time a further operation on that data
  11671.  is performed.
  11672.  
  11673.  For example, consider how the view hiprice would simplify a query to find
  11674.  information about high-priced, recently published books of specified types.
  11675.  
  11676.  
  11677.  
  11678.  Customizing
  11679.  
  11680.  Views allow different users to see the same data in different ways, even
  11681.  when they're using the same data at the same time. This advantage is
  11682.  particularly important when users of many different interests and skill
  11683.  levels share the same database.
  11684.  
  11685.  
  11686.  Security
  11687.  
  11688.  Through a view, users can query and modify only the data they can see. The
  11689.  rest of the database is neither visible nor accessible.
  11690.  
  11691.  With the GRANT and REVOKE statements, each user's access to the database can
  11692.  be restricted to specified database objects─including views. If the view and
  11693.  all the tables and views from which it was derived are owned by the same
  11694.  user, that owner can grant permission to others to use the view while
  11695.  denying permission to use its underlying tables and views. This is a simple
  11696.  but effective security mechanism. (See Chapter 14, "Advanced Topics for
  11697.  Database Owners," or the SQL Server System Administrator's Guide for details
  11698.  on the GRANT and REVOKE statements.)
  11699.  
  11700.  By defining different views and selectively granting permissions on them, a
  11701.  user (or any combination of users) can be restricted to different subsets of
  11702.  data. The following examples show how to use views for security:
  11703.  
  11704.  
  11705.    ■   Access can be restricted to a subset of the rows of a base table (a
  11706.        value-dependent subset). For example, you might define a view that
  11707.        contains only the rows for business and psychology books to keep
  11708.        information about other types of books hidden from some users.
  11709.  
  11710.    ■   Access can be restricted to a subset of the columns of a base table (a
  11711.        value-independent subset). For example, you might define a view that
  11712.        contains all the rows of the titles table but omits the royalty and
  11713.        advance columns since this information is sensitive.
  11714.  
  11715.    ■   Access can be restricted to a row-and-column subset of a base table.
  11716.  
  11717.    ■   Access can be restricted to the rows that qualify for a join of more
  11718.        than one base table. For example, you might define a view that joins
  11719.        the titles, authors, and titleauthor table to display the names of the
  11720.        authors and the books they have written. This view would hide personal
  11721.        data about authors and financial information about the books.
  11722.  
  11723.    ■   Access can be restricted to a statistical summary of data in a base
  11724.        table. For example, through the view category_price, defined later in
  11725.        this chapter, users can access only the average price of each type of
  11726.        book.
  11727.  
  11728.    ■   Access can be restricted to a subset of another view or of some
  11729.        combination of views and base tables. For example, through the view
  11730.        hiprice_computer, defined later in this chapter, users can access the
  11731.        title and price of computer books that meet the qualifications in the
  11732.        view definition of hiprice.
  11733.  
  11734.  
  11735.  To create a view, a user must be granted CREATE VIEW permission by the
  11736.  Database Owner and must have appropriate permissions on any tables or views
  11737.  referenced in the view definition.
  11738.  
  11739.  As the owner of an object on which other users have created views, you must
  11740.  be aware of who can see what data through what views. Consider this
  11741.  situation: the Database Owner has granted Harold CREATE VIEW permission, and
  11742.  a user named Margaret has granted Harold permission to SELECT from a table
  11743.  she owns. Given these permissions, Harold can create a view that selects all
  11744.  columns and rows from Margaret's table. If Margaret subsequently revokes
  11745.  permission for Harold to SELECT from her table, he can still look at her
  11746.  data through the view he has created.
  11747.  
  11748.  
  11749.  Logical Data Independence
  11750.  
  11751.  Views help to shield users from changes in the structure of the real tables
  11752.  if such changes become necessary.
  11753.  
  11754.  For example, say the database is restructured by using SELECT INTO to split
  11755.  the titles table into these two new (base) tables (and dropping titles):
  11756.  
  11757.    titletext (title_id, title, type, notes)
  11758.  
  11759.     titlenumbers (title_id, pub_id, price, advance, royalty,
  11760.     ytd_sales, pub_date)
  11761.  
  11762.  Notice that the old titles table can be "regenerated" by joining on the
  11763.  title_id columns of the two new tables. To shield the changed structure of
  11764.  the database from users, you can create a view that is the join of the two
  11765.  new tables. You can even name it titles.
  11766.  
  11767.  Any query or stored procedure that previously referred to the base table
  11768.  titles now refers to the view titles. As far as the users are concerned,
  11769.  SELECT statements continue to work exactly as before. Users who only
  11770.  retrieve from the new view need not even know that the restructuring has
  11771.  occurred.
  11772.  
  11773.  Unfortunately, views provide only partial logical independence. Some data
  11774.  modification statements on the new titles will not be allowed because of
  11775.  certain restrictions, which are explained later in this chapter.
  11776.  
  11777.  
  11778.  View Examples
  11779.  
  11780.  The first example is a view derived from the titles table. Suppose you are
  11781.  interested only in books priced higher than $15.00 and for which an advance
  11782.  of more than $5000 was paid. This SELECT statement would find the rows that
  11783.  qualify:
  11784.  
  11785.    select *
  11786.     from titles
  11787.     where price > $15
  11788.      and advance > $5000
  11789.  
  11790.  Now suppose you have numerous retrieval and update operations to do on this
  11791.  collection of data. You could, of course, combine the conditions shown in
  11792.  the previous query with any statement that you execute. However, for
  11793.  convenience, you can create a view in which just the records of interest are
  11794.  visible:
  11795.  
  11796.    create view hiprice
  11797.     as select *
  11798.     from titles
  11799.     where price > $15
  11800.      and advance > $5000
  11801.  
  11802.  When SQL Server receives this statement, it does not actually execute the
  11803.  SELECT statement that follows the keyword AS. Instead, it stores the SELECT
  11804.  statement (which is in fact the definition of the view hiprice) in the
  11805.  system table syscomments. Entries are also made in sysobjects and in
  11806.  syscolumns for each column included in the view.
  11807.  
  11808.  Now, when you display or operate on hiprice, SQL Server combines your SQL
  11809.  statement with the stored definition of hiprice. For example, you can change
  11810.  all the prices in hiprice just as you can change any other table:
  11811.  
  11812.    update hiprice
  11813.     set price = price * 2
  11814.  
  11815.  SQL Server actually finds the view definition in the system tables and
  11816.  converts this update statement into the statement
  11817.  
  11818.    update titles
  11819.     set price = price * 2
  11820.     where price > $15
  11821.      and advance > $5000
  11822.  
  11823.  In other words, SQL Server knows from the view definition that the data to
  11824.  be updated is in titles. It also knows that it should increase the prices
  11825.  only in those rows that meet the conditions on the price and advance columns
  11826.  given in the view definition and those in the update statement.
  11827.  
  11828.  Having executed the first update statement─the update to hiprice─you can see
  11829.  its effect either in the view or in the titles table. Conversely, if you had
  11830.  created the view and then executed the second update statement, which
  11831.  operates directly on the base table, the changed prices would also be
  11832.  visible through the view.
  11833.  
  11834.  Updating a view's underlying table in such a way that different rows qualify
  11835.  for the view affects the view. For example, say you increase the price of
  11836.  the book You Can Combat Computer Stress to $25.95. Since this book now meets
  11837.  the qualifying conditions in the view definition statement, it is considered
  11838.  part of the view.
  11839.  
  11840.  However, if you alter the structure of a view's underlying table by adding
  11841.  columns, the new columns will not appear in a view defined with a SELECT *
  11842.  clause unless the view is dropped and redefined. This is because the
  11843.  asterisk is interpreted and expanded when the view is first created.
  11844.  
  11845.  
  11846.  Help on Views
  11847.  
  11848.  Several system procedures provide information from the system tables about
  11849.  views.
  11850.  
  11851.  You can get a report on a view with the sp_help system procedure. For
  11852.  example:
  11853.  
  11854.    sp_help hiprice
  11855.  
  11856.     Name    Owner   Type
  11857.     --------   -----   ----
  11858.     hiprice    dbo    view
  11859.  
  11860.     Data_located_on_segment   When_created
  11861.     -----------------------   -----------------------
  11862.     default       Feb 12 1987 11:57AM
  11863.  
  11864.     (0 rows affected)
  11865.  
  11866. ╓┌───────┌───────────────┌───────────────┌────────┌───────┌───────────────┌──
  11867.  ────────────────────────────────────────────────────────────────────────────
  11868.          Column_name     Type            Length   Null    Default_name    Rule
  11869.  
  11870.          -----------     --------------  -------  ----    ------------    ----
  11871.  
  11872.          title_id        tid nocase      6        0       NULL            NULL
  11873.  
  11874.          title           varchar nocase  80       0       NULL            NULL
  11875.  
  11876.          type            char nocase     12       0       NULL            NULL
  11877.  
  11878.          pub_id          char nocase     4        1       NULL            NULL
  11879.  
  11880.          price           moneyn nocase   8        1       NULL            NULL
  11881.  
  11882.          advance         moneyn nocase   8        1       NULL            NULL
  11883.  
  11884.          royalty         intn nocase     4        1       NULL            NULL
  11885.  
  11886.          ytd_sales       intn nocase     4        1       NULL            NULL
  11887.  
  11888.  ────────────────────────────────────────────────────────────────────────────
  11889. 
  11890.          notes           varchar nocase  200      1       NULL            NULL
  11891.  
  11892.          pubdate         datetime        8        0       NULL            NULL
  11893.                          nocase
  11894.  
  11895.  
  11896.  
  11897.          (0 rows
  11898.          affected)
  11899.  
  11900.  
  11901.  
  11902.          No defined
  11903.          keys for this
  11904.          object.
  11905.  
  11906.  
  11907.  
  11908.  ────────────────────────────────────────────────────────────────────────────
  11909.  NOTE
  11910.  
  11911.  This example shows output for a non-case-sensitive database.
  11912.  ────────────────────────────────────────────────────────────────────────────
  11913.  
  11914.  To display the text of the CREATE VIEW statement, execute the sp_helptext
  11915.  system procedure:
  11916.  
  11917.    sp_helptext hiprice
  11918.  
  11919.     -----------
  11920.     1
  11921.  
  11922.     (1 row affected)
  11923.  
  11924.  
  11925.     text
  11926.     -----------------------
  11927.     create view hiprice
  11928.  
  11929.     as select *
  11930.     from titles
  11931.     where price > $15
  11932.     and advance > $5000
  11933.  
  11934.     (1 row affected)
  11935.  
  11936.  The sp_depends system procedure lists all the objects that the view or table
  11937.  references in the current database, and it lists all the objects that
  11938.  reference that view or table. Here's an example:
  11939.  
  11940.    sp_depends titles
  11941.     Things inside the current database that reference the object.
  11942.     object    type
  11943.     ------------  --------------------
  11944.     dbo.hiprice   view
  11945.     dbo.titleview  view
  11946.     dbo.reptq1   stored procedure
  11947.     dbo.reptq2   stored procedure
  11948.     dbo.reptq3   stored procedure
  11949.  
  11950.     (0 rows affected)
  11951.  
  11952.  (For complete information about the system procedures, see the SQL Server
  11953.  Language Reference.)
  11954.  
  11955.  
  11956.  Creating and Dropping Views
  11957.  
  11958.  The CREATE VIEW statement has the following syntax:
  11959.  
  11960.    CREATE VIEW [[database.]owner.]view_name
  11961.     [(column_name [, column_name...])]
  11962.     AS SELECT_statement
  11963.  
  11964.  The remainder of this section discusses the CREATE VIEW clause, the SELECT
  11965.  statement, and the DROP VIEW statement.
  11966.  
  11967.  
  11968.  The CREATE VIEW Clause
  11969.  
  11970.  View names must follow the rules for identifiers and must be unique for each
  11971.  user among the already existing tables and views.
  11972.  
  11973.  You can build indexes on views, views on other views, and procedures that
  11974.  reference views. You can define primary, foreign, and common keys on views.
  11975.  You cannot associate rules, defaults, or triggers with a view. Temporary
  11976.  views cannot be created, nor can views be created on temporary tables.
  11977.  
  11978.  As illustrated in the example given in the previous section, you need not
  11979.  specify any column names in the CREATE VIEW clause of a view definition
  11980.  statement. SQL Server gives the columns of the view the same names and the
  11981.  same datatypes as the columns referred to in the select list of the SELECT
  11982.  statement. The select list can be an "*", as in the example, or a full or
  11983.  partial list of the column names in the base table(s).
  11984.  
  11985.  It's always legal to specify column names. However, column names must be
  11986.  specified in the CREATE VIEW clause for every column in the view if
  11987.  
  11988.  
  11989.    ■   Any of the view's columns are derived from an arithmetic expression, a
  11990.        built-in function, or a constant.
  11991.  
  11992.    ■   Two or more of the view's columns would otherwise have the same name
  11993.        (usually because the view definition includes a join, and the columns
  11994.        being joined have the same name).
  11995.  
  11996.    ■   You wish to give any column in the view a different name than the
  11997.        column from which it is derived. (You can also rename columns in the
  11998.        SELECT statement.)  Whether or not you rename a view column, it
  11999.        inherits the datatype of the column from which it is derived.
  12000.  
  12001.  
  12002.  Here's a view definition statement that makes the name of a column in the
  12003.  view different from its name in the underlying table:
  12004.  
  12005.    create view pub_view (Publisher, city, state)
  12006.     as select pub_name, city, state
  12007.     from publishers
  12008.  
  12009.  An alternate method of creating the same view but renaming the columns in
  12010.  the SELECT statement would be:
  12011.  
  12012.    create view pub_view2
  12013.     as select Publisher = pub_name, city, state
  12014.     from publishers
  12015.  
  12016.  The examples of view definition statements given in a later section
  12017.  illustrate the rest of the rules for including column names in the CREATE
  12018.  VIEW clause.
  12019.  
  12020.  
  12021.  The SELECT Statement
  12022.  
  12023.  The SELECT statement in the CREATE VIEW statement defines the view. You must
  12024.  have permission to SELECT from any objects referenced in the SELECT
  12025.  statement of a view you are creating.
  12026.  
  12027.  A view need not be a simple subset of the rows and columns of one particular
  12028.  table, as in our example. You can create a view using more than one table
  12029.  and/or other views with a SELECT statement of any complexity.
  12030.  
  12031.  There are a few restrictions on the SELECT statements in a view definition:
  12032.  
  12033.  
  12034.  
  12035.    ■   You cannot include ORDER BY or COMPUTE clauses.
  12036.  
  12037.    ■   You cannot include the DISTINCT or INTO keywords.
  12038.  
  12039.    ■   You cannot reference a temporary table.
  12040.  
  12041.  
  12042.  
  12043.  View Definition with Projection
  12044.  
  12045.  The following statement creates a view with all the rows of the titles table
  12046.  but with only a subset of its columns:
  12047.  
  12048.    create view titles_view
  12049.     as select title, type, price, pubdate
  12050.     from titles
  12051.  
  12052.  Note that no column names are included in the CREATE VIEW clause. The view
  12053.  titles_view inherits the column names given in the select list.
  12054.  
  12055.  
  12056.  View Definition with a Computed Column
  12057.  
  12058.  Here is a view definition statement that creates a view with a computed
  12059.  column generated from the columns price, royalty, and ytd_sales:
  12060.  
  12061.    create view accounts (title, advance, amt_due)
  12062.     as select title, advance, (price * royalty / 100) * ytd_sales
  12063.     from titles
  12064.     where price > $15
  12065.     and advance > $5000
  12066.  
  12067.  In this example, a list of columns must be included in the CREATE VIEW
  12068.  clause since there is no name that can be inherited by the column computed
  12069.  by multiplying together price, royalty, and ytd_sales. The computed column
  12070.  is given the name amt_due. It must be listed in the same position in the
  12071.  CREATE VIEW clause as the expression from which it is computed is listed in
  12072.  the SELECT clause.
  12073.  
  12074.  
  12075.  View Definition with a Built-In Function
  12076.  
  12077.  Similarly, a view definition that includes a built-in function must include
  12078.  column names in the CREATE VIEW clause:
  12079.  
  12080.    create view categories (category, average_price)
  12081.     as select type, avg(price)
  12082.     from titles
  12083.     group by type
  12084.  
  12085.  
  12086.  View Definition with a Join
  12087.  
  12088.  You can create a view derived from more than one base table. Here's an
  12089.  example of a view derived from both the authors and the publishers tables.
  12090.  The view contains the names and cities of the authors that live in the same
  12091.  city as a publisher, along with each publisher's name and city.
  12092.  
  12093.    create view cities (authorname, acity, publishername, pcity)
  12094.     as select au_lname, authors.city, pub_name, publishers.city
  12095.     from authors, publishers
  12096.     where authors.city = publishers.city
  12097.  
  12098.  
  12099.  Views Derived from Other Views
  12100.  
  12101.  You can define a view in terms of another view:
  12102.  
  12103.    create view hiprice_computer
  12104.     as select title, price
  12105.     from hiprice
  12106.     where type = 'popular_comp'
  12107.  
  12108.  
  12109.  Dropping Views
  12110.  
  12111.  To delete a view from the database, use the DROP VIEW statement. The DROP
  12112.  VIEW statement has the following syntax:
  12113.  
  12114.    DROP VIEW [[database.]owner.]view_name
  12115.     [, [[database.]owner.]view_name...]
  12116.  
  12117.  As indicated, you can drop more than one view at a time.
  12118.  
  12119.  Here's how to drop the view hiprice:
  12120.  
  12121.    drop view hiprice
  12122.  
  12123.  When you execute the DROP VIEW statement, information about the named
  12124.  view(s) is deleted from the system tables sysprocedures, sysobjects,
  12125.  syscolumns, syscomments, sysprotects, and sysdepends. All permissions on
  12126.  that view are deleted too.
  12127.  
  12128.  If a view depends on a table (or on another view) that has been dropped, SQL
  12129.  Server displays an error message if anyone tries to use the view. If a new
  12130.  table or view with the same name is created to replace the one that has been
  12131.  dropped, the view again becomes usable (as long as the columns referenced in
  12132.  the view definition exist).
  12133.  
  12134.  
  12135.  Retrieving Data through Views
  12136.  
  12137.  When you retrieve data through a view, SQL Server checks to make sure that
  12138.  all the database objects referenced anywhere in the statement exist and that
  12139.  they are valid in the context of the statement. If the checks are
  12140.  successful, SQL Server combines the statement with the stored definition of
  12141.  the view and translates it into a query on the view's underlying table(s),
  12142.  as explained in an earlier section. This process is called view resolution.
  12143.  
  12144.  
  12145.  Consider the view definition statement given earlier in this chapter and a
  12146.  query against it:
  12147.  
  12148.    create view hiprice
  12149.     as select *
  12150.     from titles
  12151.     where price > $15
  12152.     and advance > $5000
  12153.  
  12154.     select title, type
  12155.     from hiprice
  12156.     where type = 'popular_comp'
  12157.  
  12158.  Internally, SQL Server combines the query of hiprice with its definition,
  12159.  converting the query to
  12160.  
  12161.    select title, type
  12162.     from titles
  12163.     where price > $15
  12164.     and advance > $5000
  12165.     and type = 'popular_comp'
  12166.  
  12167.  You can query any view in any way just as if it were a real table. You can
  12168.  use joins, GROUP BY clauses, subqueries, and other query techniques on
  12169.  views, in any combination.
  12170.  
  12171.  ────────────────────────────────────────────────────────────────────────────
  12172.  NOTE
  12173.  
  12174.  You can use the SELECT statement on text and image columns in views, but the
  12175.  READTEXT statement is not allowed.
  12176.  
  12177.  ────────────────────────────────────────────────────────────────────────────
  12178.  
  12179.  
  12180.  View Resolution
  12181.  
  12182.  When you define a view, SQL Server checks to make sure that all the tables
  12183.  or views listed in the FROM clause exist and gives you an error message if
  12184.  there's a problem. Similar checks are performed when you query through the
  12185.  view.
  12186.  
  12187.  Between the time a view is defined and the time it is used in an SQL
  12188.  statement, things can change. For example, one or more of the tables or
  12189.  views listed in the FROM clause of the view definition may have been
  12190.  dropped. Or one or more of the columns listed in the SELECT statement of the
  12191.  view definition may have been renamed.
  12192.  
  12193.  To fully resolve a view, SQL Server checks to make sure that
  12194.  
  12195.  
  12196.    ■   All the tables, views, and/or columns from which the view was derived
  12197.        still exist.
  12198.  
  12199.    ■   The datatype of each column on which a view column depends has not
  12200.        been changed to an incompatible type.
  12201.  
  12202.    ■   If the statement is an UPDATE, INSERT, or DELETE, it does not violate
  12203.        the restrictions on modifying views. (Restrictions are discussed in a
  12204.        later section of this chapter.)
  12205.  
  12206.  
  12207.  If any of these checks fail, SQL Server displays an error message.
  12208.  
  12209.  
  12210.  Redefining Views
  12211.  
  12212.  SQL Server allows you to redefine a view without forcing you to redefine
  12213.  other views that depend on it (unless the redefinition makes it impossible
  12214.  for SQL Server to translate the dependent view).
  12215.  
  12216.  As an example, the authors table and three possible views are shown here.
  12217.  Each succeeding view is defined using the view that preceded it: view2 is
  12218.  created from view1, and view3 is created from view2. In this way, view2
  12219.  depends on view1, and view3 depends on both of the preceding views.
  12220.  
  12221.  The columns in the views and their selection criteria for the CREATE VIEW
  12222.  statements are listed in parentheses following the name of the view.
  12223.  
  12224. ╓┌───────┌────────┌──────────────────────────────────────────────────────────╖
  12225.  ────────────────────────────────────────────────────────────────────────────
  12226.          view3    (select au_lname, phone
  12227.                   from view2
  12228.                   where au_lname = "MacFeather")
  12229.  
  12230.          view2    (select au_lname, phone
  12231.                   from view1
  12232.                   where au_lname like "[M-Z]%")
  12233.  
  12234.          view1    (select au_lname, phone
  12235.                   from authors
  12236.                   where zip like "94___")
  12237.  
  12238.          authors  (au_id, au_lname, au_fname, phone,
  12239.                   address, city, state, zip, contract)
  12240.  
  12241.  
  12242.  
  12243.  You can replace view2 with another view (also named view2) that contains
  12244.  slightly different selection criteria, such as (au_lname, phone from view_1
  12245.  where au_lname like "[M-P]"). View3 (which depends on view2) is still valid
  12246.  and need not be redefined. When you use a query that references either view2
  12247.  or view3, view resolution takes place as usual.
  12248.  
  12249.  If you redefine view2 so that view3 cannot be derived from it, view3 becomes
  12250.  invalid. For example, if a new version of view2 contains a single column,
  12251.  au_lname, rather than the two columns that view3 expects, view3 can no
  12252.  longer be used since it cannot derive the phone column from the object on
  12253.  which it depends.
  12254.  
  12255.  However, view3 still exists and can be used again by dropping the offending
  12256.  view2 and re-creating view2 with both the au_lname and the phone columns.
  12257.  
  12258.  In short, you can change the definition of an intermediate view without
  12259.  affecting dependent views so long as the select list of the dependent views
  12260.  remains valid. If this rule is violated, a query that references the invalid
  12261.  view displays an error message.
  12262.  
  12263.  
  12264.  Renaming Views
  12265.  
  12266.  You can rename a view with the sp_rename system procedure. The sp_rename
  12267.  system procedure has the following syntax:
  12268.  
  12269.    sp_rename objname, newname
  12270.  
  12271.  For example, to rename titleview to bookview:
  12272.  
  12273.    sp_rename titleview, bookview
  12274.  
  12275.  Of course, the new name must follow the rules for identifiers. You can only
  12276.  change the name of views that you own. The Database Owner can change the
  12277.  name of any user's view. The view must be in the current database.
  12278.  
  12279.  
  12280.  Altering or Dropping Underlying Objects
  12281.  
  12282.  Problems can arise if you change the name of a view's underlying object.
  12283.  Views that depend on a table or view whose name has been changed may work
  12284.  fine for a while. In fact, they work until SQL Server recompiles them. Since
  12285.  recompilation takes place for many reasons and without notification to the
  12286.  user, attempts to query or modify the view may suddenly cause SQL Server to
  12287.  return error messages.
  12288.  
  12289.  At that point, you must drop the view and re-create it so that its text
  12290.  reflects the new name of the object on which it depends. To avoid such
  12291.  problems, the safest course is not to rename any tables or views that are
  12292.  referenced by a view. If you do rename tables or views, be sure to change
  12293.  the definitions of their dependent views when you rename them.
  12294.  
  12295.  A similar situation arises if a view depends on a table or view that has
  12296.  been dropped. When someone tries to use the view, SQL Server produces an
  12297.  error message. However, if a new table or view is created to replace the one
  12298.  that was dropped, the view will again become usable.
  12299.  
  12300.  If you define a view with a SELECT * clause and then alter the structure of
  12301.  its underlying table(s) by adding columns, the new columns will not appear.
  12302.  This is because the asterisk shorthand is interpreted and expanded when the
  12303.  view is first created. To see the new columns through the view, drop the
  12304.  view and re-create it.
  12305.  
  12306.  
  12307.  Restrictions for Modifying Data through Views
  12308.  
  12309.  There are several kinds of data modification operations not allowed through
  12310.  views:
  12311.  
  12312.  
  12313.    ■   UPDATE, INSERT, or DELETE statements that refer to any column in the
  12314.        view that is a computation (a computed column or a built-in function)
  12315.        are not allowed.
  12316.  
  12317.    ■   UPDATE, INSERT, or DELETE statements that refer to a view that
  12318.        includes aggregates or row aggregates (built-in functions and a GROUP
  12319.        BY clause or a COMPUTE BY clause) are not allowed.
  12320.  
  12321.    ■   INSERT statements are not allowed unless all NOT NULL columns in the
  12322.        underlying table(s) or view(s) are included in the view through which
  12323.        you are inserting new rows. (SQL Server has no way to supply values
  12324.        for NOT NULL columns in the underlying objects.)
  12325.  
  12326.    ■   UPDATE and INSERT statements are not allowed unless the columns being
  12327.        modified all belong to the same base table. (It's illegal in SQL to
  12328.        use data modification statements on more than one table in a single
  12329.        statement.) However, if a view contains columns from more than one
  12330.        object, but the data modification statement references columns from
  12331.        only one of them, the statement is legal. This is a TRANSACT-SQL
  12332.        enhancement.
  12333.  
  12334.    ■   The WRITETEXT statement is not allowed in the text and image columns
  12335.        in a view.
  12336.  
  12337.  
  12338.  When you write a data modification statement for a view, SQL Server checks
  12339.  to make sure that none of the restrictions is violated and no data integrity
  12340.  rules are violated.
  12341.  
  12342.  Why can some views be updated and some not? You can best understand the
  12343.  restrictions by examining an example of each kind of view that cannot be
  12344.  updated.
  12345.  
  12346.  
  12347.  Computed Columns in View Definition
  12348.  
  12349.  The first restriction applies to columns of views that are derived from
  12350.  computed columns or built-in functions. For example, the amt_due column in
  12351.  the accounts view is a computed column.
  12352.  
  12353.    create view accounts (title, advance, amt_due)
  12354.     as select title_id, advance, (price * royalty/100) * ytd_sales
  12355.     from titles
  12356.     where price > $15
  12357.     and advance > $5000
  12358.  
  12359.  The rows visible through accounts are
  12360.  
  12361. ╓┌───────┌──────────────────────────────────────────────────────┌─────────┌──
  12362.  ────────────────────────────────────────────────────────────────────────────
  12363.          select * from accounts
  12364.  
  12365.  
  12366.  
  12367.          title_id                                               advance   amt_
  12368.  
  12369.          --------                                               --------  ----
  12370.  
  12371.  ────────────────────────────────────────────────────────────────────────────
  12372. 
  12373.          PC1035                                                 7,000.00  32,2
  12374.  
  12375.          PC8888                                                 8,000.00  8,19
  12376.  
  12377.          PS1372                                                 7,000.00  809.
  12378.  
  12379.          TC3218                                                 7,000.00  785.
  12380.  
  12381.  
  12382.  
  12383.          (4 rows affected)
  12384.  
  12385.  
  12386.  
  12387.  Updates and inserts to the amt_due column are not allowed because there is
  12388.  no way to deduce the underlying values for price, royalty, or year-to-date
  12389.  sales from any value you might enter in amt_due column. DELETE statements
  12390.  make no sense because there is no underlying value to delete.
  12391.  
  12392.  
  12393.  GROUP BY or COMPUTE BY in View Definition
  12394.  
  12395.  The second restriction applies to all columns in views that contain
  12396.  aggregate values─that is, views whose definition includes a GROUP BY or
  12397.  COMPUTE BY clause. Here is a view defined with a GROUP BY clause and the
  12398.  rows seen through it:
  12399.  
  12400. ╓┌───────┌────────────────────────────────────────────────────────────┌──────
  12401.  ────────────────────────────────────────────────────────────────────────────
  12402.          create view categories (category, average_price)
  12403.  
  12404.          as select type, avg(price)
  12405.  
  12406.          from titles
  12407.  
  12408.          select * from categories
  12409.  
  12410.          category                                                     average_
  12411.  
  12412.          --------                                                     --------
  12413.  ────────────────────────────────────────────────────────────────────────────
  12414.         --------                                                     --------
  12415.  
  12416.          UNDECIDED                                                    NULL
  12417.  
  12418.          business                                                     13.73
  12419.  
  12420.          mod_cook                                                     11.49
  12421.  
  12422.          popular_comp                                                 21.48
  12423.  
  12424.          psychology                                                   13.50
  12425.  
  12426.          trad_cook                                                    15.96
  12427.  
  12428.          (6 rows affected)
  12429.  
  12430.  
  12431.  
  12432.  It would not make sense to insert rows into the categories view. To what
  12433.  group of underlying rows would an inserted row belong? Updates on the
  12434.  average_price column cannot be allowed because there is no way to know from
  12435.  any value you might enter there how the underlying prices should be changed.
  12436.  
  12437.  
  12438.  
  12439.  Null Values in Underlying Objects
  12440.  
  12441.  The third restriction applies to INSERT statements if there are some NOT
  12442.  NULL columns in the table(s) or view(s) from which the view is derived.
  12443.  
  12444.  For example, suppose null values are not allowed in a column of a table that
  12445.  underlies a view. Normally, when you insert new rows through a view, any
  12446.  columns in underlying tables that aren't included in the view are given null
  12447.  values. If null values are not allowed in one or more of these columns, no
  12448.  inserts can be allowed through the view.
  12449.  
  12450.  Consider this view:
  12451.  
  12452.    create view titleview
  12453.     as select title_id, price, ytd_sales
  12454.     from titles
  12455.     where type = 'business'
  12456.  
  12457.  Null values are not allowed in the title column of the underlying table
  12458.  titles, so no INSERT statements can be allowed through titleview. Although
  12459.  the title column doesn't even exist in the view, its prohibition of null
  12460.  values makes any inserts into the view illegal.
  12461.  
  12462.  Similarly, if the title_id column has a unique index, updates or inserts
  12463.  that would duplicate any values in the underlying table are rejected, even
  12464.  if the entry doesn't duplicate any value in the view.
  12465.  
  12466.  
  12467.  Changing More Than One Underlying Object
  12468.  
  12469.  The fourth restriction is self-explanatory. It disallows updates and inserts
  12470.  through views if the statement would modify columns that are derived from
  12471.  more than one object. This is because updates and inserts on more than one
  12472.  object at a time are never allowed.
  12473.  
  12474.  However, SQL Server allows view modification statements that would not be
  12475.  allowed in other systems. For example, you can modify one underlying object
  12476.  of a view that contains columns from more than one underlying object.
  12477.  
  12478.  In other words, if a view contains three columns from titles and two columns
  12479.  from publishers, you can do an update operation on the view that changes
  12480.  only the columns from titles. You can't do an update on the view that
  12481.  changes one column from titles and one column from publishers.
  12482.  
  12483.  
  12484.  
  12485.  
  12486.  
  12487.  
  12488.  Chapter 11  Using Control-of-Flow Language
  12489.  ────────────────────────────────────────────────────────────────────────────
  12490.  
  12491.  
  12492.  Introduction
  12493.  
  12494.  This chapter discusses how to define and use multi-statement, or batch,
  12495.  files and control-of-flow language.
  12496.  
  12497.  Stored procedures and system procedures (procedures supplied by SQL Server
  12498.  for querying and updating the system tables) are discussed in Chapter 12,
  12499.  "Using Stored and System Procedures." A special kind of stored procedure
  12500.  called a trigger is used to enforce referential integrity. Triggers are
  12501.  discussed in Chapter 13, "Creating Triggers."
  12502.  
  12503.  
  12504.  Batches
  12505.  
  12506.  Up to this point, each example in this guide has consisted of an individual
  12507.  SQL statement. You submit individual SQL statements to SQL Server one at a
  12508.  time, entering statements and receiving results interactively. SQL Server
  12509.  can also process multiple SQL statements submitted as a batch, either
  12510.  interactively or from a file.
  12511.  
  12512.  A batch of SQL statements is terminated by an end-of-batch signal that
  12513.  instructs SQL Server to go ahead and execute the statements. The
  12514.  end-of-batch signal for the stand-alone SQL utility, isql, is the go command
  12515.  on a line by itself. (For details, see the SQL Server Language Reference.)
  12516.  
  12517.  Technically speaking, a single SQL statement can constitute a batch, but it
  12518.  is more common to think of a batch as containing multiple SQL statements.
  12519.  Frequently, a batch of statements is written to an operating system file
  12520.  before being submitted to isql.
  12521.  
  12522.  
  12523.  Batches and Batch Rules
  12524.  
  12525.  Batch rules govern which SQL statements can be combined into a single batch.
  12526.  The rules include the following:
  12527.  
  12528.  
  12529.    ■   CREATE PROCEDURE, CREATE RULE, CREATE DEFAULT, CREATE TRIGGER, and
  12530.        CREATE VIEW statements must be submitted to SQL Server in isolation;
  12531.        they cannot be combined with other SQL statements in a batch. CREATE
  12532.        DATABASE, CREATE TABLE, and CREATE INDEX can be combined with other
  12533.        statements in a single batch.
  12534.  
  12535.    ■   USE must be submitted in a prior batch before statements that
  12536.        reference objects in that database.
  12537.  
  12538.    ■   You cannot drop an object and then reference or re-create it in the
  12539.        same batch.
  12540.  
  12541.    ■   Any options set with a SET statement take effect at the end of the
  12542.        batch. You can combine SET statements and queries in the same batch,
  12543.        but the SET options won't apply to the queries in that batch.
  12544.  
  12545.  
  12546.  
  12547.  Batch Examples
  12548.  
  12549.  The examples in this section illustrate batches using the format of the isql
  12550.  utility, which has a clear end-of-batch signal (the go command on a line by
  12551.  itself). Here's a batch that contains two SELECT statements:
  12552.  
  12553. ╓┌─────────────────────────────────┌─────────────────────────────────────────
  12554.  ────────────────────────────────────────────────────────────────────────────
  12555.                                    select count(*) from titles
  12556.  
  12557.                                    select count(*) from authors
  12558.  
  12559.  
  12560.  ────────────────────────────────────────────────────────────────────────────
  12561. 
  12562.  
  12563.                                    /*Two SELECT statements in a single
  12564.                                    batch.*/
  12565.  
  12566.                                    ------------
  12567.  
  12568.                                    18
  12569.  
  12570.                                    (1 row affected)
  12571.  
  12572.                                    ------------
  12573.  
  12574.                                    23
  12575.  
  12576.                                    (1 row affected)
  12577.  
  12578.  
  12579.  
  12580.  This batch creates a table, inserts a row into it, and then selects
  12581.  everything from it:
  12582.  
  12583. ╓┌───────┌────────────────────────────────────────────────────────────────┌──
  12584.  ────────────────────────────────────────────────────────────────────────────
  12585.          create table test
  12586.  
  12587.          column1 char(10), column2 int
  12588.  
  12589.          insert test
  12590.  
  12591.          values ("hello", 598)
  12592.  
  12593.          select * from test
  12594.  
  12595.          go
  12596.  
  12597.  
  12598.  
  12599.          /*You can CREATE a table and reference it in the same batch.*/
  12600.  
  12601.          (1 row affected)
  12602.  ────────────────────────────────────────────────────────────────────────────
  12603.         (1 row affected)
  12604.  
  12605.          column1                                                          colu
  12606.  
  12607.          -------                                                          ----
  12608.  
  12609.          hello                                                            598
  12610.  
  12611.          (1 row affected)
  12612.  
  12613.  
  12614.  
  12615.  This batch contains a single statement which creates a view:
  12616.  
  12617.    create view testview as
  12618.     select column1 from test
  12619.     go
  12620.  
  12621.     /*A CREATE VIEW statement must be the only statement
  12622.     in a batch.*/
  12623.  
  12624.  The next batch selects from a table in the master database and then opens
  12625.  the pubs database. (It assumes that you are in the master database.)
  12626.  
  12627. ╓┌─────────────────────────────────┌─────────────────────────────────────────
  12628.  ────────────────────────────────────────────────────────────────────────────
  12629.                                    select count(*) from sysdatabases
  12630.  
  12631.                                    use pubs
  12632.  
  12633.                                    go
  12634.  
  12635.  
  12636.  
  12637.                                    /*You can combine a USE statement with
  12638.                                    other statements so
  12639.  
  12640.                                    long as objects you reference in
  12641.                                    subsequent statements are
  12642.  
  12643.                                    in the database in which you started. This
  12644.  ────────────────────────────────────────────────────────────────────────────
  12645.                                   in the database in which you started. This
  12646.                                    example assumes
  12647.  
  12648.                                    you started in the Master Database. After
  12649.                                    the batch is
  12650.  
  12651.                                    executed, pubs is the current database.*/
  12652.  
  12653.  
  12654.  
  12655.                                    ------------
  12656.  
  12657.                                    9
  12658.  
  12659.  
  12660.  
  12661.                                    (1 row affected)
  12662.  
  12663.  
  12664.  
  12665.  The final batch example combines a DROP statement with a SELECT statement.
  12666.  
  12667. ╓┌─────────────────────────────────┌─────────────────────────────────────────
  12668.  ────────────────────────────────────────────────────────────────────────────
  12669.                                    drop table test
  12670.  
  12671.                                    select count(*) from titles
  12672.  
  12673.                                    go
  12674.  
  12675.  
  12676.  
  12677.                                    /*You can combine a DROP statement with
  12678.                                    other statements as
  12679.  
  12680.                                    long as you don't reference or re-create
  12681.                                    the dropped object
  12682.  
  12683.                                    in the same batch.*/
  12684.  
  12685.  
  12686.  ────────────────────────────────────────────────────────────────────────────
  12687. 
  12688.  
  12689.                                    ------------
  12690.  
  12691.                                    18
  12692.  
  12693.  
  12694.  
  12695.                                    (1 row affected)
  12696.  
  12697.  
  12698.  
  12699.  If there is a syntax error anywhere in the batch, none of the statements is
  12700.  executed. For example, here is a batch with a typing error in the last
  12701.  statement and the results:
  12702.  
  12703.    select count(*) from titles
  12704.     select count(*) from authors
  12705.     slect count(*) from publishers
  12706.     go
  12707.  
  12708.     Msg 101, Level 15, State 1:
  12709.     Line 3: SQL syntax error.
  12710.     Msg 156, Level 15, State 1:
  12711.     Incorrect syntax near the keyword 'count'.
  12712.  
  12713.  Batches that violate a batch rule also generate error messages. Here are
  12714.  some examples of illegal batches:
  12715.  
  12716.    A. create table test
  12717.     (column1 char(10), column2 int)
  12718.     insert test
  12719.     values ("hello", 598)
  12720.     select * from test
  12721.     create view testview as select column1 from test
  12722.     go
  12723.     /* ILLEGAL BATCH - CREATE VIEW must be the only statement in a batch.*/
  12724.  
  12725.    B.  create view testview as select column1 from test
  12726.     insert testview values ("goodbye")
  12727.     go
  12728.     /* ILLEGAL BATCH - CREATE VIEW must be the only statement in a batch.*
  12729.  
  12730.    C. use pubs
  12731.     select * from titles
  12732.     go
  12733.     /* ILLEGAL BATCH - You cannot switch databases and
  12734.     reference the new one in the same batch.*/
  12735.  
  12736.    D. drop table test
  12737.     create table test
  12738.     (column1 char(10), column2 int)
  12739.     go
  12740.     /* ILLEGAL BATCH - You cannot drop an object and
  12741.     re-create it in the same batch.*/
  12742.  
  12743.  
  12744.  Batches Submitted as Files
  12745.  
  12746.  You can submit one or more batches of SQL statements to isql from an
  12747.  operating system file. A file can include more than one batch─more than one
  12748.  collection of SQL statements, each terminated by the go command.
  12749.  
  12750.  For example, an operating system file might contain the following three
  12751.  batches:
  12752.  
  12753.    use pubs
  12754.     go
  12755.     select count(*) from titles
  12756.     select count(*) from authors
  12757.     go
  12758.     create table test
  12759.     (column1 char(10), column2 int)
  12760.     insert test
  12761.     values ("hello", 598)
  12762.     select * from test
  12763.     go
  12764.  
  12765.  Here are the results of submitting this file to the isql program:
  12766.  
  12767. ╓┌─────────────────────────────────┌─────────────────────────────────────────╖
  12768.  ────────────────────────────────────────────────────────────────────────────
  12769.                                    -----------
  12770.  ────────────────────────────────────────────────────────────────────────────
  12771.                                    -----------
  12772.  
  12773.                                    18
  12774.  
  12775.                                    (1 row affected)
  12776.  
  12777.                                    -----------
  12778.  
  12779.                                    23
  12780.  
  12781.                                    (1 row affected)
  12782.  
  12783.                                    (1 row affected)
  12784.  
  12785.  
  12786.  
  12787. ╓┌───────┌─────────────────┌─────────────────────────────────────────────────╖
  12788.  ────────────────────────────────────────────────────────────────────────────
  12789.          column1           column2
  12790.  
  12791.  ────────────────────────────────────────────────────────────────────────────
  12792. 
  12793.          -------           ----------
  12794.  
  12795.          hello             598
  12796.  
  12797.  
  12798.  
  12799.          (1 row affected)
  12800.  
  12801.  
  12802.  
  12803.  
  12804.  Control-of-Flow Language
  12805.  
  12806.  TRANSACT-SQL provides special keywords called control-of-flow language that
  12807.  allow the user to control the flow of execution of SQL statements.
  12808.  Control-of-flow language can be used in single SQL statements, in batches,
  12809.  in stored procedures, and in triggers.
  12810.  
  12811.  Without control-of-flow language, separate SQL statements are performed
  12812.  sequentially, as they occur. (Correlated subqueries, discussed in Chapter 6,
  12813.  "Building Subqueries," are a partial exception.) Control-of-flow language
  12814.  permits statements to be connected, related to each other, and made
  12815.  interdependent using programming-like constructs.
  12816.  
  12817.  Control-of-flow language─such as IF-ELSE for conditional performance of
  12818.  statements and WHILE for repetitive execution─lets you refine and control
  12819.  the operation of SQL statements. TRANSACT-SQL's control-of-flow language
  12820.  transforms standard SQL into a high-level programming language. The
  12821.  control-of-flow keywords and their functions are as follows:
  12822.  
  12823. ╓┌─────────────────────────────────┌─────────────────────────────────────────
  12824.  Keyword                           Function
  12825.  ────────────────────────────────────────────────────────────────────────────
  12826.  IF                                Defines conditional execution
  12827.  
  12828.  ...ELSE                           Defines alternate execution when condition
  12829.                                    is false
  12830.  
  12831.  BEGIN                             Begins a statement block
  12832.  
  12833.  Keyword                           Function
  12834.  ────────────────────────────────────────────────────────────────────────────
  12835. 
  12836.  ...END                            Ends a statement block
  12837.  
  12838.  WHILE                             Repeats performance of statements while
  12839.                                    condition is true
  12840.  
  12841.  BREAK                             Exits from the end of the next outermost
  12842.                                    WHILE loop
  12843.  
  12844.  ...CONTINUE                       Restarts WHILE loop
  12845.  
  12846.  DECLARE                           Declares local variables
  12847.  
  12848.  GOTO label:                       Goes to label:, a position in a statement
  12849.                                    block
  12850.  
  12851.  RETURN                            Exits unconditionally
  12852.  
  12853.  WAITFOR                           Sets delay for statement execution
  12854.  Keyword                           Function
  12855.  ────────────────────────────────────────────────────────────────────────────
  12856. WAITFOR                           Sets delay for statement execution
  12857.  
  12858.  PRINT                             Prints a user-defined message or local
  12859.                                    variable on user's screen
  12860.  
  12861.  RAISERROR                         Prints a user-defined message or local
  12862.                                    variable on user's screen and sets a
  12863.                                    system flag in the global variable @ERROR
  12864.  
  12865.  /* comment */                     Inserts a comment anywhere in an SQL
  12866.                                    statement
  12867.  
  12868.  ────────────────────────────────────────────────────────────────────────────
  12869.  
  12870.  
  12871.  
  12872.  
  12873.  IF...ELSE
  12874.  
  12875.  The IF keyword (used with or without its companion ELSE) is used to
  12876.  introduce a condition that determines whether the following SQL statement is
  12877.  executed. The SQL statement is executed if the condition is satisfied (that
  12878.  is, if it returns true).
  12879.  
  12880.  The ELSE keyword introduces an alternate SQL statement that is executed when
  12881.  the IF condition is not satisfied (when it returns false).
  12882.  
  12883.  The IF and ELSE keywords have the following syntax:
  12884.  
  12885.    IF
  12886.     boolean_expression
  12887.     statement
  12888.     [ELSE
  12889.     [boolean_expression]
  12890.     statement ]
  12891.  
  12892.  A boolean expression is an expression that returns true or false. It can
  12893.  include a column name, a constant, any combination of column names and
  12894.  constants connected by arithmetic or bitwise operators, or a subquery (as
  12895.  long as it returns a single value). If the boolean expression contains a
  12896.  SELECT statement, the SELECT statement must be enclosed in parentheses, and
  12897.  it must return a single value.
  12898.  
  12899.  Here's an example of using IF alone:
  12900.  
  12901.    if exists (select zip from authors
  12902.     where zip = '94705')
  12903.     print "Berkeley author"
  12904.  
  12905.  If one or more of the zip codes in the authors table has the value 94705,
  12906.  the message "Berkeley author" is printed. The SELECT statement in this
  12907.  example returns a single value (either true or false) because it is
  12908.  introduced with the keyword EXISTS. The EXISTS keyword functions here just
  12909.  as it does in subqueries. (See Chapter 6, "Building Subqueries.")
  12910.  
  12911.  The following example uses both IF and ELSE to test for the presence of
  12912.  user-created objects (all of which have ID numbers that are larger than 50).
  12913.  If user objects exist, the ELSE clause selects their names, types, and ID
  12914.  numbers.
  12915.  
  12916.    if (select max(id) from sysobjects) < 50
  12917.     print "There are no user-created objects in this database."
  12918.     else
  12919.     select name, type, id from sysobjects
  12920.     where id > 50 and type = "U"
  12921.  
  12922.     (0 rows affected)
  12923.  
  12924.     name    type  id
  12925.     ----------   ----  ----------
  12926.     authors    U   1088006907
  12927.     publishers   U   1120007021
  12928.     roysched   U   1152007135
  12929.     sales    U   1184007249
  12930.     titleauthor   U   1216007363
  12931.     titles    U   1248007477
  12932.     stores    U   1280007591
  12933.     discounts   U   1312007705
  12934.     test    U   1648008902
  12935.  
  12936.     (9 rows affected)
  12937.  
  12938.  IF and ELSE control the execution of a single SQL statement unless you use
  12939.  the BEGIN and END keywords (discussed later) to group multiple statements
  12940.  into a statement block. The expression in the IF test must return a single
  12941.  value, whether it is a single statement or a statement block.
  12942.  
  12943.  IF...ELSE constructs are frequently used in stored procedures where they
  12944.  test for the existence of some parameter.
  12945.  
  12946.  IF tests can nest within other IF tests, either within another IF or
  12947.  following an ELSE. There is no limit on the number of levels of nesting.
  12948.  
  12949.  
  12950.  BEGIN...END
  12951.  
  12952.  The BEGIN and END keywords are used to enclose a series of SQL statements so
  12953.  that they are treated as a unit by control-of-flow constructs like
  12954.  IF...ELSE. A series of statements enclosed by BEGIN and END is called a
  12955.  statement block.
  12956.  
  12957.  BEGIN and END have the following syntax:
  12958.  
  12959.    BEGIN
  12960.      statement block
  12961.     END
  12962.  
  12963.  Here's an example:
  12964.  
  12965.    if (select avg(price) from titles) < $15
  12966.     begin
  12967.      update titles
  12968.      set price = price * 2
  12969.  
  12970.      select title, price
  12971.      from titles
  12972.      where price > $28
  12973.     end
  12974.  
  12975.     (0 rows affected)
  12976.  
  12977.  Without BEGIN and END, the IF condition would cause only one SQL statement
  12978.  to be executed.
  12979.  
  12980.  BEGIN...END blocks can be nested within other BEGIN...END blocks.
  12981.  
  12982.  
  12983.  WHILE and BREAK...CONTINUE
  12984.  
  12985.  The WHILE keyword is used to set a condition for the repeated execution of a
  12986.  statement or statement block. The statement is executed repeatedly as long
  12987.  as the specified condition is true.
  12988.  
  12989.  The WHILE keyword has the following syntax:
  12990.  
  12991.    WHILE
  12992.     boolean_expression
  12993.     statement
  12994.  
  12995.  In this example, the SELECT and UPDATE statements are repeated as long as
  12996.  the average price remains less than $30:
  12997.  
  12998. ╓┌───────┌───────────────────────────────────────────────────────────────┌───
  12999.  ────────────────────────────────────────────────────────────────────────────
  13000.          while (select avg(price) from titles) < $30
  13001.  ────────────────────────────────────────────────────────────────────────────
  13002.          while (select avg(price) from titles) < $30
  13003.  
  13004.          begin
  13005.  
  13006.          select title_id, price
  13007.  
  13008.          from titles
  13009.  
  13010.          where price > $20
  13011.  
  13012.  
  13013.  
  13014.          update titles
  13015.  
  13016.          set price = price * 2
  13017.  
  13018.          end
  13019.  
  13020.  
  13021.  
  13022.  ────────────────────────────────────────────────────────────────────────────
  13023. 
  13024.          (0 rows affected)
  13025.  
  13026.  
  13027.  
  13028.          title_id                                                        price
  13029.  
  13030.          --------                                                        -----
  13031.  
  13032.          PC1035                                                          22.95
  13033.  
  13034.          PS1372                                                          21.59
  13035.  
  13036.          TC3218                                                          20.95
  13037.  
  13038.  
  13039.  
  13040.          (3 rows affected)
  13041.  
  13042.          (18 rows affected)
  13043.  ────────────────────────────────────────────────────────────────────────────
  13044.         (18 rows affected)
  13045.  
  13046.          (0 rows affected)
  13047.  
  13048.  
  13049.  
  13050.          title_id                                                        price
  13051.  
  13052.          --------                                                        -----
  13053.  
  13054.          BU1032                                                          39.98
  13055.  
  13056.          BU1111                                                          23.90
  13057.  
  13058.          BU7832                                                          39.98
  13059.  
  13060.          MC2222                                                          39.98
  13061.  
  13062.          PC1035                                                          45.90
  13063.  
  13064.  ────────────────────────────────────────────────────────────────────────────
  13065. 
  13066.          PC8888                                                          40.00
  13067.  
  13068.          PS1372                                                          43.18
  13069.  
  13070.          PS2091                                                          21.90
  13071.  
  13072.          PS3333                                                          39.98
  13073.  
  13074.          TC3218                                                          41.90
  13075.  
  13076.          TC4203                                                          23.90
  13077.  
  13078.          TC7777                                                          29.98
  13079.  
  13080.  
  13081.  
  13082.          (12 rows affected)
  13083.  
  13084.          (18 rows affected)
  13085.  ────────────────────────────────────────────────────────────────────────────
  13086.         (18 rows affected)
  13087.  
  13088.          (0 rows affected)
  13089.  
  13090.  
  13091.  
  13092.  The BREAK and CONTINUE keywords control the operation of the statements
  13093.  inside a WHILE loop. BREAK causes an exit from the WHILE loop. Any
  13094.  statements that appear after the END keyword that marks the end of the loop
  13095.  are executed. CONTINUE causes the WHILE loop to restart, skipping any
  13096.  statements after CONTINUE but inside the loop. BREAK and CONTINUE are often
  13097.  activated by an IF test.
  13098.  
  13099.  BREAK and CONTINUE have the following syntax:
  13100.  
  13101.    WHILE
  13102.     boolean expression
  13103.     statement
  13104.     BREAK
  13105.     statement
  13106.     CONTINUE
  13107.  
  13108.  Here's an example using WHILE, BREAK, CONTINUE, and IF that reverses the
  13109.  inflation caused in the previous examples. As long as the average price
  13110.  remains more than $20, the prices are all cut in half. The maximum price is
  13111.  then selected. If it is greater than or equal to $40, the WHILE loop is
  13112.  restarted. If the maximum price is less than $40, the WHILE loop is exited,
  13113.  and a message (along with the highest prices) is printed.
  13114.  
  13115. ╓┌───────┌───────────────────────────────────────────────────────────────┌───
  13116.  ────────────────────────────────────────────────────────────────────────────
  13117.          while (select avg(price) from titles) > $20
  13118.  
  13119.          begin
  13120.  
  13121.          update titles
  13122.  
  13123.          set price = price / 2
  13124.  
  13125.          select max(price) from titles
  13126.  
  13127.  ────────────────────────────────────────────────────────────────────────────
  13128. 
  13129.          if (select max(price) from titles) < $40
  13130.  
  13131.          break
  13132.  
  13133.          else
  13134.  
  13135.          continue
  13136.  
  13137.          end
  13138.  
  13139.          begin
  13140.  
  13141.          select title_id, price
  13142.  
  13143.          from titles
  13144.  
  13145.          where price > $20
  13146.  
  13147.          print "Not Too Expensive"
  13148.  ────────────────────────────────────────────────────────────────────────────
  13149.         print "Not Too Expensive"
  13150.  
  13151.          end
  13152.  
  13153.  
  13154.  
  13155.          (18 rows affected)
  13156.  
  13157.          -----------
  13158.  
  13159.          45.90
  13160.  
  13161.  
  13162.  
  13163.          (1 row affected)
  13164.  
  13165.          (0 rows affected)
  13166.  
  13167.          (0 rows affected)
  13168.  
  13169.  ────────────────────────────────────────────────────────────────────────────
  13170. 
  13171.          (18 rows affected)
  13172.  
  13173.          ------------
  13174.  
  13175.          22.95
  13176.  
  13177.  
  13178.  
  13179.          (1 row affected)
  13180.  
  13181.          (0 rows affected)
  13182.  
  13183.  
  13184.  
  13185.  
  13186.  
  13187.  
  13188.  
  13189.  
  13190.  ────────────────────────────────────────────────────────────────────────────
  13191. 
  13192.  
  13193.          title_id                                                        price
  13194.  
  13195.          --------                                                        -----
  13196.  
  13197.          PC1035                                                          22.95
  13198.  
  13199.          PS1372                                                          21.59
  13200.  
  13201.          TC3218                                                          20.95
  13202.  
  13203.          (3 rows affected)
  13204.  
  13205.  
  13206.  
  13207.          Not Too Expensive
  13208.  
  13209.  
  13210.  
  13211.  If two or more WHILE loops are nested, BREAK exits to the next outermost
  13212.  loop. First all the statements after the END of the inner loop run. Then the
  13213.  outer loop restarts.
  13214.  
  13215.  
  13216.  DECLARE and Local Variables
  13217.  
  13218.  Variables are defined entities that are assigned values. Local variables are
  13219.  declared (and named and typed) using the DECLARE keyword and assigned an
  13220.  initial value with a SELECT statement. They must be declared, assigned a
  13221.  value, and used all within the same batch or procedure.
  13222.  
  13223.  Local variables are often used in a batch or stored procedure as counters
  13224.  for WHILE loops or IF...ELSE blocks. When they are used in stored
  13225.  procedures, they are declared for automatic, noninteractive use by the
  13226.  procedure when it is executed.
  13227.  
  13228.  The name of a local variable must begin with the "@" sign and follow the
  13229.  rules for identifiers except that it can contain from 1 to 29 characters.
  13230.  Each local variable is given either a system datatype or a user-defined
  13231.  datatype.
  13232.  
  13233.  Local variables have the following syntax:
  13234.  
  13235.    DECLARE @variable_name datatype
  13236.     [, @variable_name datatype...]
  13237.  
  13238.  Values are assigned to local variables with a SELECT statement. The syntax
  13239.  is
  13240.  
  13241.    SELECT @variable_name = expression
  13242.     [, @variable_name = expression...]
  13243.     [FROM clause] [WHERE clause]
  13244.     [GROUP BY clause] [HAVING clause]
  13245.     [ORDER BY clause] [COMPUTE clause]
  13246.  
  13247.  Local variables must be declared and used in the same batch or procedure.
  13248.  
  13249.  The SELECT statement that assigns a value to the local variable usually
  13250.  returns a single value. Here are some examples:
  13251.  
  13252.    declare @veryhigh money
  13253.     select @veryhigh = max(price)
  13254.     from titles
  13255.     if @veryhigh > $20
  13256.     print "Ouch!"
  13257.  
  13258.     declare @one varchar(18), @two varchar(18)
  13259.     select @one = "this is one", @two = "this is two"
  13260.     if @one = "this is one"
  13261.     print "you got one"
  13262.     if @two = "this is two"
  13263.     print "you got two"
  13264.     else print "nope"
  13265.  
  13266.  If the SELECT statement returns more than one value, the variable is
  13267.  assigned the last value returned.
  13268.  
  13269.  It is more efficient in terms of both memory usage and performance to write
  13270.  
  13271.  
  13272.    select @a = 1, @b = 2, @c = 3
  13273.  
  13274.  than to write
  13275.  
  13276.    select @a = 1
  13277.     select @b = 2
  13278.     select @c = 3
  13279.  
  13280.  A similar thing applies to DECLARE statements. It is more efficient to write
  13281.  
  13282.  
  13283.    declare @a int, @b char(20), @c float
  13284.  
  13285.  than to write
  13286.  
  13287.    declare @a int
  13288.     declare @b char(20)
  13289.     declare @c float
  13290.  
  13291.  The SELECT statement that assigns values to variables is used only for that
  13292.  purpose; it cannot also be used to return data to the user. The first SELECT
  13293.  statement in the following example assigns the maximum price to the local
  13294.  variable @veryhigh; the second SELECT statement displays the value:
  13295.  
  13296.    declare @veryhigh money
  13297.     select @veryhigh = max(price)
  13298.     from titles
  13299.     select @veryhigh
  13300.  
  13301.  Local variables can be used as parameters to PRINT or RAISERROR.
  13302.  
  13303.  
  13304.  DECLARE and Global Variables
  13305.  
  13306.  Global variables are system-supplied, predeclared variables. They are
  13307.  distinguished from local variables by having two "@" signs preceding their
  13308.  names─for example, @ERROR.
  13309.  
  13310.  The global variables and their contents are as follows:
  13311.  
  13312.  @@CONNECTIONS
  13313.    The number of logins or attempted logins.
  13314.  
  13315.  @@CPU_BUSY
  13316.    The amount of time, in ticks, that the CPU has spent doing SQL Server work
  13317.    since the last time SQL Server was started.
  13318.  
  13319.  @@ERROR
  13320.    The last error number generated by the system. The @ERROR global variable
  13321.    is commonly used to check the error status (succeeded or failed) of the
  13322.    most recently executed statement. A statement such as IF @ERROR != 0
  13323.    return causes an exit on error.
  13324.  
  13325.  @@IDLE
  13326.    The amount of time, in ticks, that SQL Server has been idle.
  13327.  
  13328.  @@IO_BUSY
  13329.    The amount of time, in ticks, that SQL Server has spent doing input and
  13330.    output operations.
  13331.  
  13332.  @@MAX_CONNECTIONS
  13333.    The maximum number of simultaneous connections that can be made with SQL
  13334.    Server in this computer environment. The user can configure SQL Server for
  13335.    fewer connections with sp_configure.
  13336.  
  13337.  @@NESTLEVEL
  13338.    The level of current execution (initially zero). Each time a stored
  13339.    procedure calls another stored procedure, the nesting level is
  13340.    incremented. If the maximum of 32 is exceeded, the transaction aborts.
  13341.  
  13342.  @@PACK_RECEIVED
  13343.    The number of input packets read by SQL Server.
  13344.  
  13345.  @@PACK_SENT
  13346.    The number of output packets written by SQL Server.
  13347.  
  13348.  @@PACKET_ERRORS
  13349.    The number of errors that have occurred while SQL Server was sending and
  13350.    receiving packets.
  13351.  
  13352.  @@PROCID
  13353.    The stored procedure ID of the currently executing procedure.
  13354.  
  13355.  @@ROWCOUNT
  13356.    The number of rows affected by the last query.
  13357.  
  13358.  @@TEXTSIZE
  13359.    The number of bytes of text data a SELECT returns.
  13360.  
  13361.  @@TIMETICKS
  13362.    The number of microseconds per tick. Each tick on the Microsoft(R)
  13363.    Operating System/2 (MS(R) OS/2) is 312.5 milliseconds (1/32 seconds).
  13364.  
  13365.  @@VERSION
  13366.    The date of the current version of SQL Server.
  13367.  
  13368.  @@TOTAL_ERROR
  13369.    The number of errors that have occurred while SQL Server was reading or
  13370.    writing.
  13371.  
  13372.  @@TOTAL_READ
  13373.    The number of disk reads by SQL Server.
  13374.  
  13375.  @@TOTAL_WRITE
  13376.    The number of writes by SQL Server.
  13377.  
  13378.  @@TRANCOUNT
  13379.    The number of currently active transactions for the current user.
  13380.  
  13381.  @@TOTAL_ERROR
  13382.    The number of errors that have occurred while SQL Server was reading or
  13383.    writing.
  13384.  
  13385.  For information on the contents of many of these global variables, execute
  13386.  the sp_monitor system procedure. (For complete information on the system
  13387.  procedures, see the SQL Server Language Reference.)
  13388.  
  13389.  
  13390.  GOTO
  13391.  
  13392.  The GOTO statement causes unconditional branching to a user-defined label.
  13393.  GOTO and labels can be used in stored procedures and batches. A label's name
  13394.  must follow the rules for identifiers and must be followed by a colon (:)
  13395.  when it is first given. It is not followed by a colon when it is used with
  13396.  GOTO.
  13397.  
  13398.  The GOTO statement has the following syntax:
  13399.  
  13400.    label:
  13401.  
  13402.     GOTO label
  13403.  
  13404.  Here's an example that uses GOTO and a label, a WHILE loop, and a local
  13405.  variable as a counter:
  13406.  
  13407.    declare @count smallint
  13408.     select @count = 1
  13409.     restart:
  13410.     print "yes"
  13411.     select @count = @count + 1
  13412.     while @count <=4
  13413.     goto restart
  13414.  
  13415.  As in this example, GOTO is usually made dependent on a WHILE or IF test or
  13416.  some other condition to avoid an endless loop between GOTO and the label.
  13417.  
  13418.  
  13419.  RETURN
  13420.  
  13421.  The RETURN statement exits from a query or procedure unconditionally. It can
  13422.  be used at any point in a query or a procedure. Statements after RETURN are
  13423.  not executed.
  13424.  
  13425.  The RETURN statement has the following syntax:
  13426.  
  13427.    RETURN
  13428.  
  13429.  Here's an example of a stored procedure that uses RETURN (as well as
  13430.  IF...ELSE and BEGIN...END):
  13431.  
  13432.    create procedure findrules @nm varchar(30) = null as
  13433.     if @nm is null
  13434.     begin
  13435.      print "You must give a username"
  13436.      return
  13437.     end
  13438.     else
  13439.     begin
  13440.      select sysobjects.name, sysobjects.id, sysobjects.uid
  13441.      from sysobjects, master..syslogins
  13442.      where master..syslogins.name = @nm
  13443.      and sysobjects.uid = master..syslogins.suid
  13444.      and sysobjects.type = "R"
  13445.     end
  13446.  
  13447.  If no username is given as a parameter, the RETURN statement causes the
  13448.  procedure to exit after a message has been sent to the user's screen. If a
  13449.  username is given, the names of the rules owned by the user are retrieved
  13450.  from the appropriate system tables.
  13451.  
  13452.  RETURN is similar to BREAK used with WHILE procedures.
  13453.  
  13454.  
  13455.  WAITFOR
  13456.  
  13457.  The WAITFOR statement specifies a specific time of day, a time interval, or
  13458.  an event at which the execution of a statement block, stored procedure, or
  13459.  transaction is to occur.
  13460.  
  13461.  The WAITFOR statement has the following syntax:
  13462.  
  13463.    WAITFOR {DELAY "time" | TIME "time" | ERROREXIT | PROCESSEXIT}
  13464.  
  13465.  The DELAY option instructs SQL Server to wait until the specified amount of
  13466.  time has passed. TIME instructs SQL Server to wait until the specified time,
  13467.  given in one of the acceptable formats for datetime data.
  13468.  
  13469.  However, you cannot specify dates─the date portion of the datetime value is
  13470.  not allowed. The time you specify with WAITFOR TIME or WAITFOR DELAY can
  13471.  include hours, minutes, and seconds─up to a maximum of 24 hours. Use the
  13472.  format hh:mm:ss. For example, WAITFOR time "16:23" instructs SQL Server to
  13473.  wait for 4:23 pm. The statement WAITFOR DELAY "01:30" instructs SQL Server
  13474.  to wait one hour and 30 minutes. For a review of the acceptable formats for
  13475.  TIME values, see Chapter 9, "Adding, Changing, and Removing Data."
  13476.  
  13477.  ERROREXIT instructs SQL Server to wait until a process terminates
  13478.  abnormally; PROCESSEXIT instructs SQL Server to wait until a process
  13479.  terminates for any reason. You can use WAITFOR ERROREXIT with a procedure
  13480.  that kills the abnormally terminated process to free system resources that
  13481.  would otherwise be taken up by an infected process. To find out which
  13482.  process is infected, check the sysprocesses table with the sp_who system
  13483.  procedure.
  13484.  
  13485.  This example instructs SQL Server to wait until 2:20 p.m., then to update
  13486.  the chess table with the next move and execute a stored procedure called
  13487.  sendmessage (which inserts a message into one of Judy's tables notifying her
  13488.  that a new move now exists in the chess table):
  13489.  
  13490.    begin
  13491.      waitfor time "14:20"
  13492.      insert chess(next_move)
  13493.      values('Q-KR5')
  13494.      execute sendmessage 'judy'
  13495.     end
  13496.  
  13497.  To send the message to judy after 10 seconds instead of waiting until 2:20,
  13498.  substitute this WAITFOR statement in the preceding example:
  13499.  
  13500.    waitfor delay "0:00:10"
  13501.  
  13502.  After you give the WAITFOR statement, you cannot use your connection to SQL
  13503.  Server until the time or event that you specified occurs.
  13504.  
  13505.  
  13506.  PRINT and RAISERROR
  13507.  
  13508.  The PRINT statement, used in the previous example, displays a user-defined
  13509.  message or the contents of a local variable (or global variable of type char
  13510.  or varchar) on the user's screen. The local variable must be declared within
  13511.  the same batch or procedure in which it is used. The message can be up to
  13512.  255 characters long.
  13513.  
  13514.  The PRINT statement has the following syntax:
  13515.  
  13516.    PRINT {"any ASCII text" | local variable |
  13517.     @version global variable}
  13518.  
  13519.  Here's an example:
  13520.  
  13521.    if exists (select zip from authors
  13522.      where zip = '94705')
  13523.     print "Berkeley author"
  13524.  
  13525.  Here's how you'd use PRINT to display the contents of a local variable:
  13526.  
  13527.    declare @msg char(50)
  13528.     select @msg = "What's up doc?"
  13529.     print @msg
  13530.  
  13531.  The RAISERROR statement both displays a user-defined error or local variable
  13532.  message on the user's screen, and sets a system flag to record the fact that
  13533.  an error has occurred. As with PRINT, the local variable must be declared
  13534.  within the same batch or procedure in which it is used. The message can be
  13535.  up to 255 characters long.
  13536.  
  13537.  The RAISERROR statement has the following syntax:
  13538.  
  13539.    RAISERROR number {"text of message" | local variable}
  13540.  
  13541.  The number is placed in the global variable @ERROR, which stores the error
  13542.  number most recently generated by SQL Server (whether it is associated with
  13543.  a system-supplied error message or a user-defined one.) Error numbers for
  13544.  user-defined error messages must be greater than 20,000. The message can be
  13545.  up to 255 characters long.
  13546.  
  13547.  Use RAISERROR instead of PRINT when you want an error number stored in
  13548.  @ERROR. For example, here's how you'd use RAISERROR in the indrules system
  13549.  procedure:
  13550.  
  13551.    raiserror 99999 "You must give a user name"
  13552.  
  13553.  
  13554.  Comments
  13555.  
  13556.  The comment notation is used to attach comments to SQL statements, batches,
  13557.  and stored procedures. Comments have the following syntax:
  13558.  
  13559.    /* text of comment */
  13560.  
  13561.  There is no maximum length for comments, and they can be inserted anywhere,
  13562.  on a line by themselves or at the end of a line. Multiple-line comments are
  13563.  fine, too, so long as each comment starts with a slash and an asterisk, and
  13564.  ends with an asterisk and a slash. Everything between "/*" and "*/" is
  13565.  treated as part of the comment. Comments can be nested.
  13566.  
  13567.  A stylistic convention that's often used for multiple-line comments is to
  13568.  begin the first line with "/*" and subsequent lines with "**". The comment
  13569.  is ended with "*/" as usual. Here's what it looks like:
  13570.  
  13571.    select * from titles
  13572.      /* A comment here might explain the rules
  13573.      ** associated with using an asterisk as
  13574.      ** shorthand in the select list.*/
  13575.     where price > $5
  13576.  
  13577.  Here's a procedure that includes a couple of comments:
  13578.  
  13579.    /* this procedure finds rules by username*/
  13580.  
  13581.     create procedure findrules2 @nm varchar(30) = null
  13582.     as if @nm is null/*if no parameter is given*/
  13583.     print "You must give a username"
  13584.     else
  13585.     begin
  13586.      select sysobjects.name, sysobjects.id, sysobjects.uid
  13587.      from sysobjects, master..syslogins
  13588.      where master..syslogins.name = @nm
  13589.      and sysobjects.uid = master..syslogins.suid
  13590.      and sysobjects.type = "R"
  13591.     end
  13592.  
  13593.  
  13594.  
  13595.  
  13596.  
  13597.  
  13598.  Chapter 12  Using Stored and System Procedures
  13599.  ────────────────────────────────────────────────────────────────────────────
  13600.  
  13601.  
  13602.  Introduction
  13603.  
  13604.  Stored procedures are collections of SQL statements and control-of-flow
  13605.  language. They are compiled the first time they are executed and their
  13606.  execution plans are stored so that subsequent execution is very fast. Stored
  13607.  procedures take parameters and can call other procedures.
  13608.  
  13609.  Stored procedures greatly enhance the power, efficiency, and flexibility of
  13610.  SQL. Compiled procedures dramatically improve the performance of SQL
  13611.  statements and batches.
  13612.  
  13613.  Stored procedures differ from ordinary SQL statements and from batches of
  13614.  SQL statements in that they are precompiled. The first time you run a
  13615.  procedure, SQL Server's query processor analyzes it and prepares an
  13616.  execution plan that is stored in a system table. Subsequently, the
  13617.  precompiled procedure is executed according to the stored plan. Since most
  13618.  of the query-processing work has already been performed, stored procedures
  13619.  are executed almost instantaneously.
  13620.  
  13621.  SQL Server supplies a variety of stored procedures as convenient tools for
  13622.  the user. These stored procedures are called system procedures.
  13623.  
  13624.  This chapter includes
  13625.  
  13626.  
  13627.    ■   Explanations of creating and executing your own stored procedures.
  13628.  
  13629.    ■   A brief discussion of the system procedures. (For complete
  13630.        information, see the SQL Server Language Reference.)
  13631.  
  13632.  
  13633.  You create stored procedures with the CREATE PROCEDURE statement. To execute
  13634.  a stored procedure (either a system procedure or a user-defined procedure),
  13635.  use the EXECUTE statement. (Or you can use the name of the stored procedure
  13636.  alone as long as it is the first word of a statement or batch.)
  13637.  
  13638.  A simple stored procedure (without special features such as parameters) has
  13639.  the following syntax:
  13640.  
  13641.    CREATE PROCedure procedure_name
  13642.     AS SQL_statements
  13643.  
  13644.  Stored procedures are database objects, and their names must follow the
  13645.  rules for identifiers.
  13646.  
  13647.  Any number and kind of SQL statements can be included with the exception of
  13648.  CREATE statements. (See "Stored Procedure Rules" later in this chapter.) A
  13649.  procedure can be as simple as a single statement that lists the names of all
  13650.  the users in a database:
  13651.  
  13652.    create procedure namelist
  13653.     as select name from sysusers
  13654.  
  13655.  To execute a stored procedure, use the keyword EXECUTE and the name of the
  13656.  stored procedure, or just give the procedure's name (as long as it is
  13657.  submitted to SQL Server by itself or is the first statement in a batch). You
  13658.  can execute namelist in any of these ways:
  13659.  
  13660.    namelist
  13661.     execute namelist
  13662.     exec namelist
  13663.  
  13664.  A procedure can include more than one statement:
  13665.  
  13666.    create procedure showall as
  13667.     select count(*) from sysusers
  13668.     select count(*) from sysobjects
  13669.     select count(*) from syscolumns
  13670.  
  13671.  When the procedure is executed, the results of each statement are displayed
  13672.  in the order that the statement appears in the procedure:
  13673.  
  13674. ╓┌─────────────────────────────────┌─────────────────────────────────────────╖
  13675.  ────────────────────────────────────────────────────────────────────────────
  13676.                                    showall
  13677.  
  13678.                                    ------------
  13679.  
  13680.                                    5
  13681.  
  13682.                                    (1 row affected)
  13683.  
  13684.                                    ------------
  13685.  
  13686.                                    88
  13687.  
  13688.                                    (1 row affected)
  13689.  
  13690.                                    ------------
  13691.  
  13692.                                    349
  13693.  
  13694.  ────────────────────────────────────────────────────────────────────────────
  13695. 
  13696.                                    (1 row affected)
  13697.  
  13698.  
  13699.  
  13700.  When a CREATE PROCEDURE statement is successfully executed, the procedure's
  13701.  name is stored in sysobjects, its execution plan in sysprocedures, and its
  13702.  text in syscomments. Display the text of a procedure with the sp_helptext
  13703.  system procedure:
  13704.  
  13705.    sp_helptext showall
  13706.  
  13707.     text
  13708.     ----------------------------------------
  13709.     create procedure showall as
  13710.     select count(*) from sysusers
  13711.     select count(*) from sysobjects
  13712.     select count(*) from syscolumns
  13713.  
  13714.     (1 row affected)
  13715.  
  13716.  
  13717.  Creating and Executing Stored Procedures
  13718.  
  13719.  The CREATE PROCEDURE has the following syntax:
  13720.  
  13721.    CREATE PROCedure [owner.]procedure_name [;number]
  13722.     [[(]@parameter_name datatype [= default]
  13723.     [, @parameter_name datatype [= default]...][)]]
  13724.     [WITH RECOMPILE]
  13725.     AS SQL_statements
  13726.  
  13727.  You can create a procedure in the current database only.
  13728.  
  13729.  Permission to execute CREATE PROCEDURE defaults to the Database Owner, who
  13730.  can transfer it to other users.
  13731.  
  13732.  There are two formats for specifying parameters when you execute a stored
  13733.  procedure. Here are the two complete syntax statements:
  13734.  
  13735.    [EXECute] procedure_name[;number] [value [, value...]]
  13736.      [WITH RECOMPILE]
  13737.  
  13738.     [EXECute] procedure_name[;number]
  13739.      [@parameter = ] value [, [@parameter =] value]...]
  13740.      [WITH RECOMPILE]
  13741.  
  13742.  
  13743.  Parameters
  13744.  
  13745.  A parameter is a value supplied to the stored procedure. One or more
  13746.  parameters can optionally be declared in a CREATE PROCEDURE statement. The
  13747.  value of each declared parameter must be supplied by the user when the
  13748.  procedure is executed.
  13749.  
  13750.  A parameter name must be preceded by the "@" symbol and must conform to the
  13751.  rules for identifiers except that it can contain from 1 to 29 characters.
  13752.  Parameters must be given a system datatype or a user-defined datatype, and a
  13753.  length if required for the datatype. Parameter names are local to the
  13754.  procedure that creates them; the same parameter names can be used in other
  13755.  procedures.
  13756.  
  13757.  In a CREATE PROCEDURE statement, parameters can only take the place of
  13758.  constants. The name of a database object cannot be used to define a
  13759.  parameter; however, the stored procedure can look up an object name in the
  13760.  appropriate system table based on the value of a parameter given at
  13761.  execution time.
  13762.  
  13763.  Here's a stored procedure that is useful in the pubs database. Given an
  13764.  author's last and first name, it displays the names of any books he or she
  13765.  has written and each book's publisher.
  13766.  
  13767.    create proc au_info @lastname varchar(40),
  13768.      @firstname varchar(20) as
  13769.     select au_lname, au_fname, title, pub_name
  13770.     from authors, titles, publishers, titleauthor
  13771.     where au_fname = @firstname
  13772.      and au_lname = @lastname
  13773.      and authors.au_id = titleauthor.au_id
  13774.      and titles.title_id = titleauthor.title_id
  13775.      and titles.pub_id = publishers.pub_id
  13776.  
  13777.  Now we execute au_info:
  13778.  
  13779.    au_info Ringer, Anne
  13780.  
  13781.     au_lname au_fname  title      pub_name
  13782.     --------- ---------  ---------------------  ----------------
  13783.     Ringer  Anne   The Gourmet Microwave  Binnet & Hardley
  13784.     Ringer  Anne   Is Anger the Enemy?   New Age Books
  13785.  
  13786.     (2 rows affected)
  13787.  
  13788.  The following stored procedure queries the system tables. Given a table name
  13789.  as the parameter, the procedure shows the table name, index name, and index
  13790.  ID.
  13791.  
  13792.    create proc showind @table varchar(30) as
  13793.     select TABLE_NAME = sysobjects.name,
  13794.     INDEX_NAME = sysindexes.name, INDEX_ID = indid
  13795.     from sysindexes, sysobjects
  13796.     where sysobjects.name = @table
  13797.      and sysobjects.id = sysindexes.id
  13798.  
  13799.  The column headings (for example, TABLE_NAME) were added to improve the
  13800.  readability of the results.
  13801.  
  13802.  Here are the acceptable syntax forms for executing this (or any) stored
  13803.  procedure:
  13804.  
  13805.    execute showind titles
  13806.  
  13807.     execute showind @table = titles
  13808.  
  13809.     showind titles
  13810.  
  13811.  The last syntax form is acceptable so long as the statement is the only one
  13812.  or first one in a batch.
  13813.  
  13814.  Here are the results of executing showind in the pubs database when titles
  13815.  is given as the parameter:
  13816.  
  13817. ╓┌───────┌─────────────────────────────────────────────────┌─────────────┌───
  13818.  ────────────────────────────────────────────────────────────────────────────
  13819.          TABLE_NAME                                        INDEX_NAME    INDEX
  13820.  ────────────────────────────────────────────────────────────────────────────
  13821.          TABLE_NAME                                        INDEX_NAME    INDEX
  13822.  
  13823.          ------------                                      ------------  -----
  13824.  
  13825.          titles                                            titleidind    1
  13826.  
  13827.          titles                                            titleind      2
  13828.  
  13829.  
  13830.  
  13831.          (2 rows affected)
  13832.  
  13833.  
  13834.  
  13835.  ────────────────────────────────────────────────────────────────────────────
  13836.  NOTE
  13837.  
  13838.  If you supply the parameters in the form "@parameter = value", you can
  13839.  supply the parameters in any order. Otherwise, you must supply parameters in
  13840.  the order of their CREATE PROCEDURE statement.
  13841.  ────────────────────────────────────────────────────────────────────────────
  13842.  
  13843.  
  13844.  Default Parameters
  13845.  
  13846.  You can assign a default value for the parameter in the CREATE PROCEDURE
  13847.  statement. This value, which can be any constant, is taken as the parameter
  13848.  to the procedure if the user does not supply one.
  13849.  
  13850.  Here's a procedure that displays the names of all the authors that have
  13851.  written a book published by the publisher given as a parameter. If no
  13852.  publisher name is supplied, the procedure shows the authors published by
  13853.  Algodata Infosystems.
  13854.  
  13855.    create proc pub_info
  13856.      @pubname varchar(40) = "Algodata Infosystems" as
  13857.     select au_lname, au_fname, pub_name
  13858.     from authors a, publishers p, titles t, titleauthor ta
  13859.     where @pubname = p.pub_name
  13860.      and a.au_id = ta.au_id
  13861.      and t.title_id = ta.title_id
  13862.      and t.pub_id = p.pub_id
  13863.  
  13864.  Note that if the default value is a character string that contains embedded
  13865.  blanks or punctuation, it must be enclosed in single or double quotation
  13866.  marks.
  13867.  
  13868.  When you execute pub_info, you can give any publisher's name as the
  13869.  parameter value. If you don't supply any parameter, SQL Server uses the
  13870.  default, Algodata Infosystems.
  13871.  
  13872.    exec pub_info
  13873.  
  13874.     au_lname   au_fname   pub_name
  13875.     ---------------- ---------------- --------------------
  13876.     Green    Marjorie   Algodata Infosystems
  13877.     Bennet    Abraham    Algodata Infosystems
  13878.     O'Leary    Michael    Algodata Infosystems
  13879.     MacFeather   Stearns    Algodata Infosystems
  13880.     Straight   Dick    Algodata Infosystems
  13881.     Carson    Cheryl    Algodata Infosystems
  13882.     Dull    Ann     Algodata Infosystems
  13883.     Hunter    Sheryl    Algodata Infosystems
  13884.     Locksley   Chastity   Algodata Infosystems
  13885.  
  13886.     (9 rows affected)
  13887.  
  13888.  You assign titles as the default value for the @table parameter in this
  13889.  procedure, showind2:
  13890.  
  13891.    create proc showind2 @table varchar(30) = titles as
  13892.     select TABLE_NAME = sysobjects.name,
  13893.     INDEX_NAME = sysindexes.name, INDEX_ID = indid
  13894.     from sysindexes, sysobjects
  13895.     where sysobjects.name = @table
  13896.      and sysobjects.id = sysindexes.id
  13897.  
  13898.  The column headings (for example, TABLE_NAME) clarify the results display.
  13899.  Here's what the procedure shows for the authors table:
  13900.  
  13901. ╓┌───────┌───────────────────────────────────────────────────┌───────────┌───
  13902.  ────────────────────────────────────────────────────────────────────────────
  13903.          showind2 authors
  13904.  ────────────────────────────────────────────────────────────────────────────
  13905.          showind2 authors
  13906.  
  13907.  
  13908.  
  13909.          TABLE_NAME                                          INDEX_NAME  INDEX
  13910.  
  13911.          ----------                                          ----------  -----
  13912.  
  13913.          authors                                             auidind     1
  13914.  
  13915.          authors                                             aunmind     2
  13916.  
  13917.  
  13918.  
  13919.          (2 rows affected)
  13920.  
  13921.  
  13922.  
  13923.  If the user does not supply a value, SQL Server uses the default, titles.
  13924.  
  13925. ╓┌───────┌───────────────────────────────────────────────────┌───────────┌───
  13926.  ────────────────────────────────────────────────────────────────────────────
  13927.          showind2
  13928.  
  13929.  
  13930.  
  13931.          TABLE_NAME                                          INDEX_NAME  INDEX
  13932.  
  13933.          ----------                                          ----------  -----
  13934.  
  13935.          titles                                              titleidind  1
  13936.  
  13937.          titles                                              titleind    2
  13938.  
  13939.  
  13940.  
  13941.          (2 rows affected)
  13942.  
  13943.  
  13944.  
  13945.  If a parameter is expected but none is supplied, and a default value is not
  13946.  supplied in the CREATE PROCEDURE statement, SQL Server displays an error
  13947.  message.
  13948.  
  13949.  ────────────────────────────────────────────────────────────────────────────
  13950.  NOTE
  13951.  
  13952.  The error message lists names of expected parameters in reverse order to
  13953.  their order in the CREATE PROCEDURE statement.
  13954.  
  13955.  ────────────────────────────────────────────────────────────────────────────
  13956.  
  13957.  
  13958.  NULL as Default Parameter
  13959.  
  13960.  The default can be the value NULL. In this case, if the user does not supply
  13961.  a parameter, SQL Server executes the stored procedure according to its other
  13962.  statements. No error message is displayed.
  13963.  
  13964.  The procedure definition can also specify that some other action be taken if
  13965.  the user does not give a parameter. Here's an example:
  13966.  
  13967.    create procedure showind3 @table varchar(30) = null as
  13968.     if @table is null
  13969.      print "Please give a table name"
  13970.     else
  13971.      select TABLE_NAME = sysobjects.name,
  13972.      INDEX_NAME = sysindexes.name, INDEX_ID = indid
  13973.      from sysindexes, sysobjects
  13974.      where sysobjects.name = @table
  13975.      and sysobjects.id = sysindexes.id
  13976.  
  13977.  If the user fails to give a parameter, SQL Server prints the user-supplied
  13978.  message on the screen.
  13979.  
  13980.  (For other examples of setting the default to NULL, examine the text of
  13981.  system procedures, using sp_helptext.)
  13982.  
  13983.  
  13984.  Wildcard Characters in the Default Parameter
  13985.  
  13986.  The default can include the wildcard characters (%, _, [] and [^]) if the
  13987.  procedure uses the parameter with the LIKE keyword.
  13988.  
  13989.  For example, showind can be modified to display information about the system
  13990.  tables if the user does not supply a parameter, like this:
  13991.  
  13992.    create procedure showind4 @table varchar(30) = "sys%" as
  13993.     select TABLE_NAME = sysobjects.name,
  13994.     INDEX_NAME = sysindexes.name, INDEX_ID = indid
  13995.     from sysindexes, sysobjects
  13996.     where sysobjects.name like @table
  13997.     and sysobjects.id = sysindexes.id
  13998.  
  13999.  
  14000.  Using More Than One Parameter
  14001.  
  14002.  The following variant of the stored procedure au_info has defaults with
  14003.  wildcard characters for both parameters:
  14004.  
  14005.    create proc au_info2 @lastname varchar(30) = "D%",
  14006.     @firstname varchar(18) = "%" as
  14007.     select au_lname, au_fname, title, pub_name
  14008.     from authors, titles, publishers, titleauthor
  14009.     where au_fname like @firstname
  14010.      and au_lname like @lastname
  14011.      and authors.au_id = titleauthor.au_id
  14012.      and titles.title_id = titleauthor.title_id
  14013.      and titles.pub_id = publishers.pub_id
  14014.  
  14015.  If au_info2 is executed with no parameters, all the authors with last names
  14016.  beginning with "D" are displayed:
  14017.  
  14018.    au_info2
  14019.  
  14020.     au_lname au_fname title      pub_name
  14021.     -------- -------- ------------------------- --------------------
  14022.     Dull  Ann   Secrets of Silicon Valley Algodata Infosystems
  14023.     DeFrance Michel  The Gourmet Microwave  Binnet & Hardley
  14024.  
  14025.     (2 rows affected)
  14026.  
  14027.  If defaults are available for parameters, parameters can be omitted at
  14028.  execution, beginning with the last parameter. You cannot skip a parameter
  14029.  unless NULL is its supplied default.
  14030.  
  14031.  ────────────────────────────────────────────────────────────────────────────
  14032.  NOTE
  14033.  
  14034.  If you supply parameters in the form "@parameter = value", you can supply
  14035.  parameters in any order. You can also omit a parameter for which a default
  14036.  has been supplied.
  14037.  ────────────────────────────────────────────────────────────────────────────
  14038.  
  14039.  As an example of omitting the second parameter when defaults for two
  14040.  parameters have been defined, you can find the books and publishers for all
  14041.  authors with the last name "Ringer" like this:
  14042.  
  14043.    au_info2 Ringer
  14044.  
  14045.     au_lname au_fname  title      pub_name
  14046.     --------- ---------  ------------------------ ----------------
  14047.     Ringer  Anne   The Gourmet Microwave  Binnet & Hardley
  14048.     Ringer  Anne   Is Anger the Enemy?   New Age Books
  14049.     Ringer  Albert   Is Anger the Enemy?   New Age Books
  14050.     Ringer  Albert   Life Without Fear   New Age Books
  14051.  
  14052.     (4 rows affected)
  14053.  
  14054.  
  14055.  Procedure Groups
  14056.  
  14057.  The optional semicolon and (integer) number after the name of the procedure
  14058.  in the CREATE PROCEDURE and EXECUTE statements allow you to group procedures
  14059.  of the same name so that they can be dropped together with a single DROP
  14060.  PROCEDURE statement.
  14061.  
  14062.  Procedures used in the same application are often grouped this way. For
  14063.  example, you might create a series of procedures called orders;1, orders;2,
  14064.  and so on. The command drop proc orders would drop the entire group.
  14065.  
  14066.  Once procedures have been grouped by appending a semicolon and number to
  14067.  their names, they cannot be dropped individually. For example, the command
  14068.  drop proc orders;2 is not allowed.
  14069.  
  14070.  
  14071.  WITH RECOMPILE in CREATE PROCEDURE
  14072.  
  14073.  In the CREATE PROCEDURE statement, the optional clause WITH RECOMPILE comes
  14074.  just before the SQL statements. It instructs SQL Server not to save a plan
  14075.  for this procedure. The procedure is recompiled each time it is executed.
  14076.  
  14077.  In the absence of WITH RECOMPILE, SQL Server stores the execution plan that
  14078.  it created, which is based on the parameter given to the procedure on its
  14079.  first execution. Usually, this execution plan is the best one for most of
  14080.  the values that are passed to the procedure as parameters.
  14081.  
  14082.  However, it's possible that parameter values supplied for subsequent
  14083.  executions would have caused SQL Server to come up with an execution plan
  14084.  different from the one it created when the parameter was first executed.
  14085.  
  14086.  Use WITH RECOMPILE in a CREATE PROCEDURE statement when you expect that the
  14087.  parameters you supply to the procedure won't be typical─that is, they would
  14088.  not result in the same optimal plan.
  14089.  
  14090.  
  14091.  WITH RECOMPILE in EXECUTE
  14092.  
  14093.  In the EXECUTE statement, the optional clause WITH RECOMPILE comes after any
  14094.  parameters. It instructs SQL Server to compile a new plan for this execution
  14095.  of the procedure only. The original plan is used for subsequent executions.
  14096.  
  14097.  
  14098.  Use WITH RECOMPILE when you execute a procedure if the parameter you're
  14099.  supplying is atypical─that is, if the plan stored with the procedure might
  14100.  not be optimal for this parameter.
  14101.  
  14102.  ────────────────────────────────────────────────────────────────────────────
  14103.  NOTE
  14104.  
  14105.  If you use SELECT * in your CREATE PROCEDURE statement, the procedure (even
  14106.  if you use the WITH RECOMPILE option to EXECUTE) will not pick up any new
  14107.  columns you may have added to the table. You must drop the procedure and
  14108.  recreate it.
  14109.  ────────────────────────────────────────────────────────────────────────────
  14110.  
  14111.  
  14112.  Stored Procedure Rules
  14113.  
  14114.  Some additional rules for creating stored procedures are as follows:
  14115.  
  14116.  
  14117.    ■   CREATE PROCEDURE statements cannot be combined with other SQL
  14118.        statements in a single batch.
  14119.  
  14120.    ■   The CREATE PROCEDURE definition itself can include any number and kind
  14121.        of SQL statements with the exception of CREATE statements:
  14122.  
  14123.        CREATE VIEW
  14124.  
  14125.        CREATE DEFAULT
  14126.  
  14127.        CREATE RULE
  14128.  
  14129.        CREATE TRIGGER
  14130.  
  14131.        CREATE PROCEDURE
  14132.  
  14133.    ■   Other database objects can be created within a procedure. You can
  14134.        reference an object you've created in the same procedure as long as it
  14135.        is created before it is referenced. (The CREATE statement for the
  14136.        object must come first in the actual order of the statements within
  14137.        the procedure.)
  14138.  
  14139.    ■   Within a stored procedure, you cannot create an object, drop it, and
  14140.        then create a new object with the same name.
  14141.  
  14142.    ■   If you execute a procedure that calls another procedure, the called
  14143.        procedure can access objects created by the first procedure.
  14144.  
  14145.    ■   You can reference temporary tables within a procedure.
  14146.  
  14147.    ■   If you create a temporary table inside a procedure, the temporary
  14148.        table exists only for the purposes of the procedure; it disappears
  14149.        when you exit the procedure.
  14150.  
  14151.    ■   The maximum number each for parameters, local variables, and global
  14152.        variables in a procedure is 40.
  14153.  
  14154.  
  14155.  
  14156.  Qualifying Names Inside Stored Procedures
  14157.  
  14158.  Inside a stored procedure, object names used with utility statements must be
  14159.  qualified with the object owner's name if other users are to make use of the
  14160.  stored procedure. The utility statements are ALTER TABLE, CREATE TABLE, DROP
  14161.  TABLE, TRUNCATE TABLE, CREATE INDEX, DROP INDEX, UPDATE STATISTICS, DBCC.
  14162.  For example, user mary, who owns table marytab, should qualify the name of
  14163.  her table when it is used with one of these utility statements if she wants
  14164.  other users to be able to execute the procedure in which the table is used:
  14165.  
  14166.  
  14167.    create procedure p1
  14168.     as
  14169.     create index marytab_ind
  14170.     on mary.marytab(col1)
  14171.  
  14172.  The reason for this rule is that object names are resolved when the
  14173.  procedure is run. If marytab had not been qualified and user John had tried
  14174.  to execute the procedure, SQL Server would have looked for a table called
  14175.  marytab owned by John. The preceding example shows the correct usage: it
  14176.  tells SQL Server to look for a table called marytab owned by Mary.
  14177.  
  14178.  Object names used with other statements (for example, SELECT or INSERT)
  14179.  inside a stored procedure need not be qualified because the names are
  14180.  resolved when the procedure is compiled.
  14181.  
  14182.  
  14183.  Dropping Procedures
  14184.  
  14185.  The DROP PROCEDURE statement removes procedures from the current database.
  14186.  The DROP PROCEDURE statement has the following syntax:
  14187.  
  14188.    DROP PROCedure procedure_name [, procedure_name...]
  14189.  
  14190.  If a stored procedure that has been dropped is called by another stored
  14191.  procedure, SQL Server displays an error message. However, if a new procedure
  14192.  of the same name is defined to replace the one that was dropped, other
  14193.  procedures that reference it can call it successfully.
  14194.  
  14195.  A procedure group (more than one procedure with the same name but different
  14196.  ;number suffixes) can be dropped with a single DROP PROCEDURE statement.
  14197.  Once procedures have been grouped, procedures within the group cannot be
  14198.  dropped individually.
  14199.  
  14200.  
  14201.  Renaming Procedures
  14202.  
  14203.  You can rename a stored procedure with the sp_rename system procedure. The
  14204.  sp_rename system procedure has the following syntax:
  14205.  
  14206.    sp_rename objname, newname
  14207.  
  14208.  For example, to rename showall to countall:
  14209.  
  14210.    sp_rename showall, countall
  14211.  
  14212.  Of course, the new name must follow the rules for identifiers. You can only
  14213.  change the name of stored procedures that you own. The Database Owner can
  14214.  change the name of any user's stored procedure. The stored procedure must be
  14215.  in the current database.
  14216.  
  14217.  Problems can arise with sp_rename if you change the name of an object
  14218.  referenced by a stored procedure. A stored procedure that references a table
  14219.  or view whose name has been changed may seem to work fine for a while. In
  14220.  fact, it works only until SQL Server recompiles it. Recompilation takes
  14221.  place for many reasons and without notification to the user.
  14222.  
  14223.  When a procedure stops working because one of its underlying objects has
  14224.  been renamed, you must drop the stored procedure and recreate it so that its
  14225.  text reflects the new name of the object it references. To avoid such
  14226.  problems, the safest course is not to rename any tables or views that are
  14227.  referenced by a procedure. If you do rename tables or views, be sure to
  14228.  change the definitions of dependent procedures when you rename them.
  14229.  
  14230.  
  14231.  Help on Procedures
  14232.  
  14233.  Several system procedures provide information from the system tables about
  14234.  stored procedures.
  14235.  
  14236.  
  14237.  sp_helpsql
  14238.  
  14239.  To display information on SQL statements, system procedures, and other
  14240.  topics, execute the sp_helpsql system procedure:
  14241.  
  14242.    sp_helpsql "begin transaction"
  14243.  
  14244.     BEGIN TRANSACTION
  14245.  
  14246.     Marks the starting point of a user-specified transaction.
  14247.  
  14248.     BEGIN TRANsaction [transaction_name]
  14249.  
  14250.  
  14251.  sp_help
  14252.  
  14253.  You can get a report on a stored procedure with the sp_help system
  14254.  procedure. For example, you can get information on the stored procedure
  14255.  byroyalty, which is part of the pubs database, like this:
  14256.  
  14257.    sp_help byroyalty
  14258.  
  14259.     Name    Owner   Type
  14260.     ------------  ---------  -----------------
  14261.     byroyalty   dbo    stored procedure
  14262.  
  14263.     Data_located_on_segment    When_created
  14264.     -----------------------    ---------------------
  14265.     default        Feb 9 1987 3:56PM
  14266.  
  14267.     (0 rows affected)
  14268.  
  14269. ╓┌───────┌──────────────────────────────────────┌────────────┌──────────┌────
  14270.  ────────────────────────────────────────────────────────────────────────────
  14271.          Parameter_name                         Type         Length     Param_
  14272.  
  14273.          --------------                         -----------  ---------  ------
  14274.  
  14275.          @percentage                            int          4          1
  14276.  
  14277.  
  14278.  
  14279.  You can get help on a system procedure by executing sp_help when using the
  14280.  master database.
  14281.  
  14282.  
  14283.  sp_helptext
  14284.  
  14285.  To display the text of the CREATE PROCEDURE statement, execute the
  14286.  sp_helptext system procedure:
  14287.  
  14288. ╓┌─────────────────────────────────┌─────────────────────────────────────────
  14289.  ────────────────────────────────────────────────────────────────────────────
  14290.                                    sp_helptext byroyalty
  14291.  
  14292.  
  14293.  
  14294.                                    -----------
  14295.  
  14296.                                    1
  14297.  
  14298.                                    (1 row affected)
  14299.  
  14300.  
  14301.  
  14302.                                    text
  14303.  ────────────────────────────────────────────────────────────────────────────
  14304.                                   text
  14305.  
  14306.                                    -------------------------------------------
  14307.  
  14308.                                    create procedure byroyalty @percentage int
  14309.  
  14310.                                    as
  14311.  
  14312.                                    select au_id from titleauthor
  14313.  
  14314.                                    where titleauthor.royaltyper = @percentage
  14315.  
  14316.                                    (1 row affected)
  14317.  
  14318.  
  14319.  
  14320.  You can view the text of a system procedure by executing sp_helptext when
  14321.  using the master database.
  14322.  
  14323.  
  14324.  sp_depends
  14325.  
  14326.  The sp_depends system procedure lists all the stored procedures that
  14327.  reference the object you specify or all the procedures that are depended
  14328.  upon by it. This statement lists all the objects referenced by the
  14329.  user-created stored procedure byroyalty:
  14330.  
  14331.    sp_depends byroyalty
  14332.  
  14333.     Things the object references in the current database.
  14334.  
  14335.     object    type    updated   selected
  14336.     ---------------- ----------- -  --------  --------
  14337.     dbo.titleauthor  user table   no    no
  14338.  
  14339.  The following statement uses sp_depends to list all the objects that
  14340.  reference the table titleauthor:
  14341.  
  14342.    sp_depends titleauthor
  14343.  
  14344.     Things inside the current database that reference the object.
  14345.  
  14346.     object     type
  14347.     -----------------  ---------------------------
  14348.     dbo.titleview   view
  14349.     dbo.reptq2    stored procedure
  14350.     dbo.byroyalty   stored procedure
  14351.  
  14352.  The system procedures are briefly discussed in "System Procedures" later in
  14353.  this chapter. (For complete information about the system procedures, see the
  14354.  SQL Server Language Reference.)
  14355.  
  14356.  
  14357.  Stored Procedures and Permissions
  14358.  
  14359.  Stored procedures can serve as security mechanisms, since a user can be
  14360.  granted permission to execute a stored procedure even if he or she does not
  14361.  have permissions on tables or views referenced in it. (For details, see
  14362.  Chapter 14, "Advanced Topics for Database Owners.")
  14363.  
  14364.  
  14365.  System Procedures
  14366.  
  14367.  The system procedures are provided for your convenience as
  14368.  
  14369.  
  14370.    ■   Shortcuts for retrieving information from the system tables
  14371.  
  14372.    ■   Mechanisms for accomplishing database administration and other tasks
  14373.        that involve updating system tables
  14374.  
  14375.  
  14376.  Most of the time, system tables are updated only through stored procedures.
  14377.  The System Administrator can allow direct updates of system tables by
  14378.  changing one of the configuration options and issuing the RECONFIGURE WITH
  14379.  OVERRIDE statement. (See the SQL Server System Administrator's Guide for
  14380.  details.)
  14381.  
  14382.  System procedures are created in the master database and are owned by the
  14383.  System Administrator.
  14384.  
  14385.  You can run system procedures from any database. If a system procedure is
  14386.  executed from a database other than master, any references to system tables
  14387.  are mapped to the database from which the procedure is being run. For
  14388.  example, if the Database Owner of pubs runs sp_adduser from pubs, the new
  14389.  user is added to pubs..sysusers.
  14390.  
  14391.  When the parameter for a system procedure is an object name and the object
  14392.  name is qualified by a database name or owner name, the entire name must be
  14393.  enclosed in single or double quotation marks.
  14394.  
  14395.  Since system procedures are located in the master database, their
  14396.  permissions are also set there. Some of the system procedures can be run
  14397.  only by Database Owners. These procedures make sure that the user executing
  14398.  the procedure is the owner of the database from which they are being
  14399.  executed.
  14400.  
  14401.  Other system procedures can be executed by any user who has been granted
  14402.  EXECUTE permission on them, but this permission must be granted in master.
  14403.  This situation has two consequences:
  14404.  
  14405.  
  14406.    ■   A user can have permission to execute a system procedure either in all
  14407.        databases or in none of them.
  14408.  
  14409.    ■   The owner of a user database cannot directly control permissions on
  14410.        the system procedures within his or her own database.
  14411.  
  14412.  
  14413.  (See the SQL Server System Administrator's Guide for details.)
  14414.  
  14415.  The system procedures can be divided into three categories. The following
  14416.  three sections discuss these categories.
  14417.  
  14418.  
  14419.  User Identification and Permissions
  14420.  
  14421.  This category includes procedures for
  14422.  
  14423.  
  14424.    ■   Adding, dropping, and reporting on login IDs on SQL Server
  14425.  
  14426.    ■   Adding, dropping, and reporting on users, groups, and aliases in a
  14427.        database
  14428.  
  14429.    ■   Changing passwords and default databases
  14430.  
  14431.    ■   Changing the owner of a database
  14432.  
  14433.  
  14434.  The procedures in this category are sp_addalias, sp_addgroup, sp_addlogin,
  14435.  sp_adduser, sp_changedbowner, sp_changegroup, sp_defaultdb, sp_dropalias,
  14436.  sp_dropgroup, sp_droplogin, sp_dropuser, sp_helpgroup, sp_helprotect,
  14437.  sp_helpuser, sp_password.
  14438.  
  14439.  
  14440.  Data Definition and Database Objects
  14441.  
  14442.  This category includes procedures for
  14443.  
  14444.  
  14445.    ■   Binding and unbinding rules and defaults
  14446.  
  14447.    ■   Adding, dropping, and reporting on primary keys, foreign keys, and
  14448.        common keys
  14449.  
  14450.    ■   Adding, dropping, and reporting on user-defined datatypes
  14451.  
  14452.    ■   Renaming database objects and user-defined datatypes
  14453.  
  14454.    ■   Reporting on database objects; user-defined datatypes; dependencies
  14455.        among database objects, databases, and indexes; and space used by
  14456.        tables and indexes
  14457.  
  14458.  
  14459.  The procedures in this category are sp_addtype, sp_bindefault, sp_bindrule,
  14460.  sp_commonkey, sp_depends, sp_dropkey, sp_droptype, sp_foreignkey, sp_help,
  14461.  sp_helpdb, sp_helpindex, sp_helpjoins, sp_helpkey, sp_helptext,
  14462.  sp_primarykey, sp_rename, sp_spaceused, sp_unbindefault, sp_unbindrule.
  14463.  
  14464.  
  14465.  Other System Procedures
  14466.  
  14467.  This category includes procedures for
  14468.  
  14469.  
  14470.    ■   Adding, dropping, and reporting on dump devices
  14471.  
  14472.    ■   Reporting on locks, the database options that are set, and the users
  14473.        currently running processes
  14474.  
  14475.    ■   Changing and reporting on configuration options
  14476.  
  14477.    ■   Monitoring SQL Server activity
  14478.  
  14479.  
  14480.  The procedures in this category are sp_addumpdevice, sp_configure,
  14481.  sp_dboption, sp_diskdefault, sp_dropdevice, sp_helpdevice, sp_lock,
  14482.  sp_logdevice, sp_markreport, sp_monitor, sp_who.
  14483.  
  14484.  In addition, there are system procedures that are called by other system
  14485.  procedures; users cannot call them directly. They are sp_abort_xact,
  14486.  sp_addsegment, sp_commit_xact, sp_dropsegment, sp_extendsegment,
  14487.  sp_fixindex, sp_lookup, sp_markreport, sp_placeobject, sp_remove_xact,
  14488.  sp_scan_xact, sp_start_xact, sp_stat_xact.
  14489.  
  14490.  More information about the system procedures that accomplish administrative
  14491.  tasks is given in the SQL Server System Administrator's Guide. (For complete
  14492.  information about the system procedures, see the SQL Server Language
  14493.  Reference.)
  14494.  
  14495.  
  14496.  
  14497.  
  14498.  
  14499.  
  14500.  Chapter 13  Creating Triggers
  14501.  ────────────────────────────────────────────────────────────────────────────
  14502.  
  14503.  
  14504.  Introduction
  14505.  
  14506.  A trigger is a special kind of stored procedure that goes into effect when
  14507.  you modify data in a specified table. Triggers are often created to enforce
  14508.  referential integrity or consistency among logically related data in
  14509.  different tables.
  14510.  
  14511.  The main advantage of triggers is that they are automatic─they work no
  14512.  matter what caused the data modification─a clerk's entry, an application
  14513.  action, a report calculation. Each trigger is specific to one or more of the
  14514.  data modification operations: UPDATE, INSERT, or DELETE.
  14515.  
  14516.  Triggers are useful in the following situations:
  14517.  
  14518.  
  14519.    ■   Triggers can cascade changes through related tables in the database to
  14520.        ensure referential integrity─that is, to guarantee that when a value
  14521.        in one table is changed, all other instances of that value in other
  14522.        tables are also changed.
  14523.  
  14524.        Such a trigger might go into effect when you try to change a primary
  14525.        key and you want the change to be reflected in matching foreign keys.
  14526.        For example, update triggers on the title_id column of the titles
  14527.        table─a primary key─could go into effect whenever titles.title_id is
  14528.        updated, making the same change to titleauthor.title_id,
  14529.        sales.title_id, and roysched.title_id.
  14530.  
  14531.    ■   Triggers can disallow or roll back changes that would violate
  14532.        referential integrity, canceling the attempted data modification
  14533.        transaction.
  14534.  
  14535.        Such a trigger might go into effect when you try to change a foreign
  14536.        key and the new value does not match its primary key. For example, you
  14537.        could create an insert trigger on titleauthor.title_id that rolled
  14538.        back an insert if the new value did not match some value in
  14539.        titles.title_id.
  14540.  
  14541.    ■   Triggers can keep summary data (ongoing tallies) up to date. For
  14542.        example, you can create a trigger that updates the titles.ytd_sales
  14543.        column every time a new sale is recorded in sales.
  14544.  
  14545.    ■   Triggers can enforce restrictions much more complex than those defined
  14546.        with rules. Unlike rules, triggers can reference columns or database
  14547.        objects. For example, a trigger
  14548.  
  14549.        can roll back updates that attempt to increase a book's price by more
  14550.        than 1% of its advance.
  14551.  
  14552.    ■   Triggers can also find the difference between the state of a table
  14553.        before and after a data modification, and take action(s) based on that
  14554.        difference.
  14555.  
  14556.  
  14557.  This chapter first summarizes trigger definition syntax and rules. Then it
  14558.  discusses and gives examples of triggers for the typical uses listed here.
  14559.  You may want to use these examples as templates for your own triggers.
  14560.  
  14561.  The triggers discussed in this chapter are not included in the pubs database
  14562.  shipped with your copy of SQL Server. To work with the examples shown in
  14563.  this chapter, be sure to drop all existing triggers first. Then create each
  14564.  trigger example by using the CREATE TRIGGER statement. After you are through
  14565.  using a trigger, drop it before creating another trigger.
  14566.  
  14567.  The reason for this protocol is explained more fully later in this chapter.
  14568.  Triggers on different tables can interact, disabling one other.
  14569.  
  14570.  
  14571.  Defining a Trigger: CREATE TRIGGER
  14572.  
  14573.  A trigger is a database object. You create a trigger by specifying which
  14574.  data modification statement will activate the trigger and which table will
  14575.  be the target. Then you specify the action or actions the trigger is to
  14576.  take.
  14577.  
  14578.  Here is a simple example. This trigger prints a message every time anyone
  14579.  tries to add data to or change the data in the titles table:
  14580.  
  14581.    create trigger t1
  14582.     on titles
  14583.     for insert, update
  14584.     as
  14585.     print "Make an entry in titleauthor to link this book"
  14586.     print "to its writer."
  14587.  
  14588.  The CREATE TRIGGER statement has the following syntax:
  14589.  
  14590.    CREATE TRIGGER [owner.]trigger_name
  14591.      ON [owner.]table_name
  14592.      FOR {INSERT | UPDATE | DELETE}
  14593.       [, {INSERT | UPDATE | DELETE}...]
  14594.      AS SQL_statements
  14595.      IF UPDATE (column_name)
  14596.       [{AND | OR} UPDATE (column_name...)]
  14597.  
  14598.  Here's an analysis of the trigger keywords:
  14599.  
  14600.  
  14601.    ■   The CREATE clause creates the trigger and names it. A trigger's name
  14602.        must conform to the rules for identifiers.
  14603.  
  14604.    ■   The ON clause gives the name of the table that activates the trigger.
  14605.        This table is sometimes called the trigger table.
  14606.  
  14607.        A trigger is created in the current database, although it can
  14608.        reference objects in other databases. The owner name that qualifies
  14609.        the trigger name must be the same as the owner name on the table: no
  14610.        one can create a trigger on a table except the table owner. If the
  14611.        table owner is specified in one name, it must also be included in the
  14612.        other name.
  14613.  
  14614.    ■   The FOR clause specifies which data modification statements applied
  14615.        toward the trigger table activate the trigger. In the simple earlier
  14616.        example, either an INSERT or an UPDATE to titles makes the message
  14617.        print. Triggers can also be defined for the DELETE statement.
  14618.  
  14619.    ■   The SQL statements in the AS clause cannot include SELECT statements
  14620.        that return results: a trigger does not return data to the user. With
  14621.        this exception, a trigger's SELECT statements can be any number and
  14622.        kind, and often include control-of-flow language.
  14623.  
  14624.        The SQL statements specify trigger conditions and trigger actions.
  14625.        Trigger conditions specify additional criteria that determine whether
  14626.        the attempted INSERT, DELETE, or UPDATE will cause the trigger
  14627.        action(s) to be carried out. Trigger conditions often include a
  14628.        subquery preceded by the keyword IF.
  14629.  
  14630.        The trigger actions specified in the SQL statements go into effect
  14631.        when the user action (UPDATE, INSERT, or DELETE) is attempted. If
  14632.        multiple trigger actions are specified, they are grouped with BEGIN
  14633.        and END.
  14634.  
  14635.  
  14636.  Some special syntax is used by the CREATE TRIGGER statement:
  14637.  
  14638.  
  14639.    ■   The name deleted is the name of a logical table. Rows are removed from
  14640.        the trigger table and transferred to the deleted table as soon as the
  14641.        DELETE statement is executed: deleted and the trigger table ordinarily
  14642.        have no rows in common.
  14643.  
  14644.        You can operate on rows in deleted just like you can on rows in other
  14645.        tables. In fact, the deleted table is often joined to one or more of
  14646.        the tables being changed by the trigger. The trigger can examine the
  14647.        rows in deleted to determine whether or how the trigger action(s)
  14648.        should be carried out. Use deleted with DELETE and UPDATE triggers
  14649.        only.
  14650.  
  14651.    ■   The name inserted is also the name of a logical table. This table
  14652.        holds the rows added to the trigger table by means of an INSERT or
  14653.        UPDATE statement.
  14654.  
  14655.        When an INSERT or UPDATE statement is executed, rows are added to the
  14656.        trigger table and to inserted at the same time. So the rows in
  14657.        inserted are always duplicates of one or more rows in the trigger
  14658.        table. Use inserted with INSERT and UPDATE triggers only.
  14659.  
  14660.    ■   The keywords IF UPDATE (column_name) are used to test whether the
  14661.        specified column has been modified in any way. This mechanism allows
  14662.        trigger actions to be associated with changes to the data in
  14663.        particular columns.
  14664.  
  14665.  
  14666.  
  14667.  Removing a Trigger: DROP TRIGGER
  14668.  
  14669.  You can remove a trigger by dropping it or as a side effect of dropping the
  14670.  trigger table.
  14671.  
  14672.  The DROP TRIGGER statement has the following syntax:
  14673.  
  14674.    DROP TRIGGER [owner.]trigger_name [, [owner.]trigger_name...]
  14675.  
  14676.  DROP TRIGGER permission defaults to the trigger table owner and is not
  14677.  transferable.
  14678.  
  14679.  
  14680.  Trigger Rules and Considerations
  14681.  
  14682.  This section discusses other factors to consider when using triggers.
  14683.  
  14684.  
  14685.  Triggers and Permissions
  14686.  
  14687.  A trigger is defined on a particular table. Only the owner of the table has
  14688.  CREATE TRIGGER and DROP TRIGGER permissions for the table. These permissions
  14689.  cannot be transferred to others.
  14690.  
  14691.  SQL Server will accept a trigger definition that affects tables you do not
  14692.  own, and attempts actions for which you do not have permission. The
  14693.  existence of such a trigger aborts any subsequent attempt to modify the
  14694.  trigger table. You must rectify the permissions or drop the trigger. For
  14695.  example, Joe owns sales and creates a trigger on it. The trigger is supposed
  14696.  to update titles.ytd_sales when sales.qty is updated. However, Mary is the
  14697.  owner of titles. When Joe tries to update sales, SQL Server detects the
  14698.  trigger and Joe's lack of permissions on titles and rolls back the update
  14699.  transaction. Joe must either get update permission on titles.ytd_sales from
  14700.  Mary or drop the trigger on sales.
  14701.  
  14702.  When a table is dropped, any triggers associated with it are automatically
  14703.  dropped.
  14704.  
  14705.  Using IF UPDATE (column_name) never makes sense in a DELETE trigger.
  14706.  
  14707.  
  14708.  Restrictions
  14709.  
  14710.  A table can have a maximum of three triggers: one update trigger, one insert
  14711.  trigger, and one delete trigger.
  14712.  
  14713.  Each trigger can apply to only one table. However, a single trigger may
  14714.  apply to all three user actions (UPDATE, INSERT, and DELETE).
  14715.  
  14716.  You cannot create a trigger on a view or a temporary object, though triggers
  14717.  can reference views or temporary objects.
  14718.  
  14719.  Although a TRUNCATE TABLE statement is, in effect, like a DELETE without a
  14720.  WHERE clause (it removes all rows), it cannot activate a trigger because it
  14721.  is not logged.
  14722.  
  14723.  
  14724.  Implicit and Explicit Null Values
  14725.  
  14726.  The IF UPDATE (column_name) clause is true for an INSERT statement whenever
  14727.  the column is assigned a value in the select list or in the VALUES clause.
  14728.  An explicit NULL or a default assigns a value to a column and thus activates
  14729.  the trigger. With an implicit NULL, if the value is not specified by the
  14730.  query or default, the trigger on that column is not activated. These
  14731.  examples clarify the situation:
  14732.  
  14733.    CREATE TABLE junk
  14734.     (a int null, b int not null)
  14735.     INSERT junk (a, b)  /*IF UPDATE is true for either column,*/
  14736.     VALUES (1, 2)   /*The trigger is activated.*/
  14737.     INSERT junk    /*IF UPDATE is true for either column,*/
  14738.     VALUES (1, 2)   /*The trigger is activated.*/
  14739.     INSERT junk    /*Explicit NULL: */
  14740.     VALUES (NULL, 2)  /*IF UPDATE is true for either column,*/
  14741.           /*The trigger is activated.*/
  14742.     INSERT junk (b)   /* If default on column a,*/
  14743.     VALUES (2)    /*IF UPDATE is true for either column,*/
  14744.           /*The trigger is activated.*/
  14745.     INSERT junk (b)   /* If no default on column a,*/
  14746.     VALUES (2)    /*IF UPDATE is not true for column a,*/
  14747.           /*The trigger is not activated.*/
  14748.  
  14749.  
  14750.  Nested Triggers
  14751.  
  14752.  One trigger cannot call another. If a trigger changes a table on which there
  14753.  is another trigger, the second trigger won't be executed. In other words,
  14754.  triggers cannot be nested. If you need a trigger to cause two actions, try
  14755.  to put both of the actions into a single trigger. (Or consider using a
  14756.  stored procedure instead.) For example, you might create an INSERT trigger
  14757.  on the sales table that updates titles.ytd_sales. You'd also like a trigger
  14758.  on updates to titles.ytd_sales that checks the titles.royalty column and
  14759.  changes it in turn, if necessary. The correct method is not to write a
  14760.  second trigger that changes titles.royalty when titles.ytd_sales changes.
  14761.  Such a trigger would be disabled by the existing trigger that updates
  14762.  titles.ytd_sales when sales is updated. Rather, you should write one trigger
  14763.  that takes both actions─the update of titles.ytd_sales and the (possible)
  14764.  update of titles.royalty.
  14765.  
  14766.  
  14767.  Triggers and Performance
  14768.  
  14769.  In performance terms, trigger overhead is usually low. The time involved in
  14770.  running a trigger is spent mostly in referencing other tables, which may be
  14771.  either in memory or on disk. The deleted and inserted tables, often
  14772.  referenced by triggers, are always in memory rather than on the disk because
  14773.  they are logical tables. The location of other tables referenced by the
  14774.  trigger determines the amount of time the operation takes.
  14775.  
  14776.  Once a trigger is defined, the user action (UPDATE, DELETE, or INSERT) on
  14777.  the table it affects is always implicitly part of a transaction, along with
  14778.  the trigger itself. If an error is detected, the transaction rolls back.
  14779.  
  14780.  
  14781.  SET Statements in Triggers
  14782.  
  14783.  You can use the SET statement inside a trigger. The SET option you invoke
  14784.  remains in effect during the execution of the trigger and then reverts to
  14785.  its former setting. It is often wise to SET NOCOUNT ON at the beginning of
  14786.  the trigger definition so that users won't get messages telling them how
  14787.  many rows were affected by a trigger. Some users may not even know the
  14788.  trigger exists.
  14789.  
  14790.  
  14791.  Trigger Storage
  14792.  
  14793.  Triggers, like all objects, are listed in sysobjects by name. The type
  14794.  column of sysobjects identifies triggers with the abbreviation "TR." This
  14795.  query finds the triggers that exist in a database:
  14796.  
  14797.    select *
  14798.     from sysobjects
  14799.     where type = "TR"
  14800.  
  14801.  The CREATE TRIGGER statement for each trigger is stored in syscomments. You
  14802.  can display the trigger definition with the sp_helptext system procedure, as
  14803.  explained later.
  14804.  
  14805.  Execution plans for triggers are stored in sysprocedures.
  14806.  
  14807.  
  14808.  Renaming Triggers
  14809.  
  14810.  You can rename a trigger with the sp_rename system procedure. The sp_rename
  14811.  system procedure has the following syntax:
  14812.  
  14813.    sp_rename objname, newname
  14814.  
  14815.  There is a trigger in the pubs database named deltitle. Here's how you would
  14816.  rename it to goodriddance:
  14817.  
  14818.    sp_rename deltitle, goodriddance
  14819.  
  14820.  Only the trigger owner and the Database Owner can change the name of a
  14821.  trigger. The trigger must be in the current database.
  14822.  
  14823.  Now, change this trigger's name back to the original name:
  14824.  
  14825.    sp_rename goodriddance, deltitle
  14826.  
  14827.  Problems can arise with sp_rename if you change the name of an object
  14828.  referenced by a trigger. A trigger that references a table or view whose
  14829.  name has been changed may work fine for a while. In fact, it works until SQL
  14830.  Server recompiles it. Since recompilation takes place for many reasons and
  14831.  without notification to the user, the trigger may cease working without your
  14832.  realizing it.
  14833.  
  14834.  At that point, you must drop the trigger and re-create it so that its text
  14835.  reflects the new name of the object which it references. To avoid such
  14836.  problems, do not rename any tables or views that are referenced by a trigger
  14837.  or change the definitions of their dependent triggers when you rename them.
  14838.  
  14839.  
  14840.  
  14841.  Help on Triggers
  14842.  
  14843.  Several system procedures provide information from the system tables about
  14844.  triggers.
  14845.  
  14846.  
  14847.  sp_help
  14848.  
  14849.  You can get a report on a trigger with the sp_help system procedure. For
  14850.  example, to get information on deltitle, type
  14851.  
  14852.    sp_help deltitle
  14853.  
  14854.     Name   Owner  type   Created_on
  14855.     --------  -----  -------   -----------------
  14856.     deltitle  dbo   trigger   Feb 9 1987 3:56PM
  14857.  
  14858.     (1 row affected)
  14859.  
  14860.  
  14861.  sp_helptext
  14862.  
  14863.  To display the text of the CREATE TRIGGER statement, execute the sp_helptext
  14864.  system procedure:
  14865.  
  14866.    sp_helptext deltitle
  14867.  
  14868.     ----------
  14869.     1
  14870.  
  14871.     (1 row affected)
  14872.  
  14873.     text
  14874.     -------------------------------------------
  14875.     create trigger deltitle
  14876.     on titles
  14877.     for delete
  14878.     as
  14879.     if (select count(*) from deleted, sales
  14880.     where sales.title_id = deleted.title_id) >0
  14881.     begin
  14882.     rollback transaction
  14883.     print "You can't delete a title with sales."
  14884.     end
  14885.  
  14886.     (1 row affected)
  14887.  
  14888.  
  14889.  sp_depends
  14890.  
  14891.  The sp_depends system procedure lists all the triggers that reference the
  14892.  object (for example, table or view) or all the tables or views that the
  14893.  trigger affects. This example shows how to use sp_depends to get a list of
  14894.  all the objects referenced by the trigger deltitle:
  14895.  
  14896.    sp_depends deltitle
  14897.  
  14898.     Things the object references in the current database.
  14899.  
  14900.     object    type   updated  selected
  14901.     ---------   ----------  -------  --------
  14902.     dbo.sales   user table  no   no
  14903.  
  14904.  This statement lists all the objects that reference the sales table:
  14905.  
  14906.    sp_depends sales
  14907.  
  14908.     Things inside the current database that reference the object.
  14909.  
  14910.     object    type
  14911.     ------------  ---------------
  14912.     dbo.deltitle  trigger
  14913.  
  14914.  
  14915.  Trigger Examples
  14916.  
  14917.  This section provides examples of typical triggers, which you may want to
  14918.  use as templates for your own triggers. Before looking at the examples, it's
  14919.  important to review some referential integrity concepts.
  14920.  
  14921.  Referential integrity is based on the use of primary and foreign keys:
  14922.  
  14923.  
  14924.    ■   The primary key is the column or combination of columns that uniquely
  14925.        identifies a row. It must always be NOT NULL and have a unique index.
  14926.        A table with a primary key that is used for joins with other tables is
  14927.        called a master table.
  14928.  
  14929.        In the pubs database, for example, the title_id column is the primary
  14930.        key of titles. It uniquely identifies the books in titles and is often
  14931.        joined with title_id in titleauthor, sales, and roysched. The titles
  14932.        table is the master table.
  14933.  
  14934.    ■   The foreign key is a column or combination of columns in one table
  14935.        whose values match the values in the primary key of another table. It
  14936.        doesn't have to be NOT NULL nor does it have to be unique. The foreign
  14937.        key values are copies of the primary key values, and hence no value in
  14938.        the foreign key should ever exist unless the same value exists in the
  14939.        primary key. Tables with foreign keys are often called detail or
  14940.        dependent tables to the master table.
  14941.  
  14942.        The title_id columns in titleauthor, sales, and roysched are foreign
  14943.        keys; these tables are detail tables.
  14944.  
  14945.  
  14946.  Referential integrity triggers keep the values of foreign keys in line with
  14947.  those in primary keys. Each of the following sections looks at a different
  14948.  kind of modification to a primary or foreign key value, analyzes what's
  14949.  normally required in terms of protection, and suggests a solution─often a
  14950.  trigger.
  14951.  
  14952.  
  14953.  Deleting a Primary Key
  14954.  
  14955.  When you delete a primary key row, you want to delete the entries for that
  14956.  key in dependent tables. In other words, to ensure referential integrity,
  14957.  detail rows must be removed when the master row is deleted. A trigger that
  14958.  performs a cascading delete is required.
  14959.  
  14960.  Here's an example. When a DELETE statement on titles is executed, the row is
  14961.  removed from titles and added to deleted. A trigger checks the dependent
  14962.  tables─titleauthor, sales, and roysched─to see if they have any rows with a
  14963.  title_id that matches the title_id removed from titles (now stored in the
  14964.  deleted table). If the trigger finds any such rows, it removes them.
  14965.  
  14966.    create trigger delcascadetrig
  14967.     on titles
  14968.     for delete
  14969.     as
  14970.     delete titleauthor
  14971.     from titleauthor, deleted
  14972.      where titleauthor.title_id = deleted.title_id
  14973.       /* Remove titleauthor rows
  14974.       ** that match deleted (titles) rows.*/
  14975.     delete sales
  14976.     from sales, deleted
  14977.      where sales.title_id = deleted.title_id
  14978.       /* Remove sales rows
  14979.       ** that match deleted (titles) rows.*/
  14980.     delete roysched
  14981.     from roysched, deleted
  14982.      where roysched.title_id = deleted.title_id
  14983.       /* Remove roysched rows
  14984.       ** that match deleted (titles) rows.*/
  14985.  
  14986.  In actual practice, you may find that you want to keep some of the detail
  14987.  rows, either for historical purposes (to check how many sales were made on
  14988.  discontinued titles while they were active) or because transactions on the
  14989.  detail rows are not yet complete. A trigger would have to take these factors
  14990.  into consideration.
  14991.  
  14992.  
  14993.  Inserting a Primary Key
  14994.  
  14995.  When you insert a row with a primary key into a table, you must make sure
  14996.  the entry is unique. In most cases, the unique index on the primary key will
  14997.  prevent duplicates. If, for some reason, the primary key does not have a
  14998.  unique index, a trigger can provide a check.
  14999.  
  15000.  The trigger example that follows enforces uniqueness on a primary key. The
  15001.  trigger rolls back (cancels) any insert containing an au_id that already
  15002.  exists in the authors table. To test it, first drop the unique index:
  15003.  
  15004.    drop index authors.auidind
  15005.  
  15006.  You can create a trigger that enforces uniqueness (for an attempted insert
  15007.  of a single, non-null value) by testing whether the number of rows in
  15008.  authors that join with inserted is greater than one.
  15009.  
  15010.  Recall that an INSERT statement adds rows to inserted and to the trigger
  15011.  table at the same time so that there will always be one (temporary) join
  15012.  between inserted and the trigger table, even if the INSERT subsequently
  15013.  fails.
  15014.  
  15015.  If a count of the rows that join between inserted and the trigger table is
  15016.  greater than one, this means that the key in the inserted table has joined
  15017.  with an existing key in the trigger table as well as with the newly inserted
  15018.  key.
  15019.  
  15020.  If this is the case, this trigger cancels the insert and prints a message.
  15021.  If not, it proceeds with the insert and prints no message.
  15022.  
  15023.    create trigger uniqinsertrig
  15024.     on authors
  15025.     for insert
  15026.     as if
  15027.     (select count(*)
  15028.     from authors, inserted
  15029.     where authors.au_id = inserted.au_id) >1
  15030.     begin
  15031.      rollback transaction
  15032.      print "At least one au_id is a duplicate: the transaction"
  15033.      print "cannot be completed."
  15034.     end
  15035.  
  15036.  
  15037.  Updating a Primary Key
  15038.  
  15039.  When you update (change) a primary key, you want to protect referential
  15040.  integrity either by cascading the master row change through all the detail
  15041.  rows or by rolling back the update altogether.
  15042.  
  15043.  It's best to prohibit any editing changes to a primary key. Rather than
  15044.  editing a primary key, delete the whole row and then insert a new one.
  15045.  
  15046.  The best way to prohibit updates to a primary key is to revoke all
  15047.  permissions on it. However, if you want to prohibit updates only under
  15048.  certain circumstances, use a trigger.
  15049.  
  15050.  The trigger that follows, for example, prevents updates to titles.title_id
  15051.  only on the weekend. (Such a trigger might be desirable for any type of
  15052.  column, not just for a primary key.)
  15053.  
  15054.  The IF UPDATE clause in stopupdatetrig allows you to focus on a particular
  15055.  column, titles.title_id. Modifications to the data in that column cause the
  15056.  trigger to go into action. Changes to the data in other columns do not. When
  15057.  this trigger detects an update that touches the IF UPDATE column, it cancels
  15058.  the update and prints a message.
  15059.  
  15060.    create trigger stopupdatetrig
  15061.     on titles
  15062.     for update
  15063.     as
  15064.     if update (title_id)
  15065.     and datename(dw, getdate())
  15066.     in ("Saturday", "Sunday")
  15067.     begin
  15068.      rollback transaction
  15069.      print "We don't allow monkeying with primary keys
  15070.      on the weekend!"
  15071.     end
  15072.       /* If titles.title_id changes on
  15073.       ** Saturday or Sunday, cancel the update. */
  15074.  
  15075.  
  15076.  Deleting a Foreign Key
  15077.  
  15078.  When you delete a foreign key row, you don't need a trigger to maintain
  15079.  referential integrity. The primary key row in the master table is not
  15080.  affected. Other foreign keys relate to the primary key, not to another
  15081.  foreign key.
  15082.  
  15083.  
  15084.  Inserting a Foreign Key
  15085.  
  15086.  When you insert a new foreign key row, you want to make sure the foreign key
  15087.  matches a primary key. The trigger should check for joins between the
  15088.  inserted rows and the rows in the primary key table, and then roll back any
  15089.  inserts of foreign keys that do not match a key in the primary key table. To
  15090.  accomplish this, you can use a NOT EXISTS test. This attempted insert
  15091.  differs from the previous one in that you check for joins between inserted
  15092.  and an outside table, the primary key table, rather than checking for joins
  15093.  between inserted and the trigger table.
  15094.  
  15095.  The following trigger compares the title_ids from the inserted table with
  15096.  those from the titles table. It assumes that you are making some entry for
  15097.  the foreign key and that you are not inserting a null value. If the join
  15098.  fails, the transaction is rolled back.
  15099.  
  15100.    create trigger forinsertrig1
  15101.     on sales
  15102.     for insert
  15103.     as if
  15104.     not exists
  15105.     (select * from titles, inserted
  15106.     where titles.title_id = inserted.title_id)
  15107.  
  15108.    begin
  15109.      rollback transaction
  15110.      print "No! The title_id doesn't exist in titles."
  15111.      end
  15112.       /* cancel the insert and print a message.*/
  15113.     else
  15114.      print "Added, because the title_id did exist in titles."
  15115.       /* Otherwise, allow it. */
  15116.  
  15117.  To illustrate the use of ELSE, this trigger prints one message if the INSERT
  15118.  is rolled back and another if it is accepted. Most of the time, you would
  15119.  want a message only in the first case.
  15120.  
  15121.  
  15122.  Inserting a NULL Foreign Key
  15123.  
  15124.  If the table containing the foreign key column permits null values for the
  15125.  foreign key column, you can add a line to the previous trigger that will
  15126.  handle an insert of a NULL foreign key. This version of the trigger permits
  15127.  the insert of a NULL foreign key, then rejects any invalid foreign keys that
  15128.  are not null values.
  15129.  
  15130.  ────────────────────────────────────────────────────────────────────────────
  15131.  NOTE
  15132.  
  15133.  This hypothetical trigger uses a table, salesnull, that is not part of the
  15134.  sample database. To test this trigger, you must create the salesnull table,
  15135.  which is identical in structure to sales except that its title_id column
  15136.  permits null values.
  15137.  ────────────────────────────────────────────────────────────────────────────
  15138.  
  15139.    create trigger forinsertrig1
  15140.     on salesnull
  15141.     for insert
  15142.     as if exists (select inserted.title_id from inserted
  15143.     where title_id is null)
  15144.     print "null key inserted"
  15145.     if not exists
  15146.     (select * from titles, inserted
  15147.     where titles.title_id = inserted.title_id)
  15148.     begin
  15149.      rollback transaction
  15150.      print "No! The title_id doesn't exist in titles."
  15151.     end
  15152.       /* cancel the insert and print a message.*/
  15153.     else
  15154.      print "Added, because the title_id did exist in titles."
  15155.       /* Otherwise, allow it. */
  15156.  
  15157.  
  15158.  Updating a Foreign Key
  15159.  
  15160.  A change (update) to a foreign key by itself is probably an error. A foreign
  15161.  key is just a copy of the primary key: the two should never be independent.
  15162.  
  15163.  
  15164.  If for some reason you want to allow updates of a foreign key, you might
  15165.  want to protect its integrity by
  15166.  
  15167.  
  15168.    ■   Requiring that updates to the foreign key be done through a stored
  15169.        procedure, rather than directly with an UPDATE statement.
  15170.  
  15171.    ■   Creating a trigger that checks updates against the master table and
  15172.        rolls them back if they don't match the primary key. (It is also
  15173.        possible to create a trigger that rolls back the update under any
  15174.        circumstances.)
  15175.  
  15176.  
  15177.  An example of canceling an update can be found in "Updating a Primary Key,"
  15178.  earlier in this chapter. In the following example, the trigger tests for two
  15179.  possible sources of failure: either the title_id is not in the sales table
  15180.  or it's not in the titles table.
  15181.  
  15182.  The example uses three nested IF statements. The first (IF UPDATE) checks to
  15183.  see if the title_id column in sales is being updated. If you update a column
  15184.  other than sales.title_id, the trigger has no effect.
  15185.  
  15186.  The second checks to see that the inserted table contains a row of
  15187.  information. If inserted is blank, the title_id does not exist in the sales
  15188.  table, and an error message is printed.
  15189.  
  15190.  The third checks to see if the inserted and titles tables join on the
  15191.  title_id column. If not, the transaction is rolled back, and an error
  15192.  message is printed. If the join succeeds, a different message is printed.
  15193.  
  15194.    create trigger forupdatetrig
  15195.     on sales
  15196.     for update as
  15197.     if update (title_id)
  15198.     begin
  15199.      if (select count(*) from inserted) > 0
  15200.      begin
  15201.       if not exists
  15202.        (select titles.title_id from inserted, titles
  15203.        where titles.title_id = inserted.title_id)
  15204.       begin
  15205.        rollback transaction
  15206.        print "No! the title_id doesn't exist in titles"
  15207.       end
  15208.       else
  15209.        print "sales table updated"
  15210.      end
  15211.  
  15212.    else
  15213.       print "title_id not in sales"
  15214.     end
  15215.  
  15216.  
  15217.  Summary Value Triggers
  15218.  
  15219.  Another important function of a trigger is to automatically recalculate
  15220.  ongoing tallies. Here's one that updates the ytd_sales column in the titles
  15221.  table whenever a row is added to the sales table.
  15222.  
  15223.    create trigger sumintrig
  15224.     on sales
  15225.     for insert
  15226.       /* When you add a row to sales, */
  15227.     as
  15228.     update titles
  15229.     set titles.ytd_sales = (titles.ytd_sales + inserted.qty)
  15230.     from titles, inserted
  15231.     where inserted.title_id = titles.title_id
  15232.      /* add new sales.qty to titles.ytd_sales
  15233.      ** where the title_ids join. */
  15234.  
  15235.  This trigger goes into effect whenever you record a sale by adding a row to
  15236.  the sales table. The trigger updates the ytd_sales column in titles so that
  15237.  it is equal to its previous value plus the value added to sales.qty. This
  15238.  keeps the totals up to date for inserts into sales.qty. Prevent updates on
  15239.  titles.ytd_sales and on sales.qty by revoking UPDATE permissions.
  15240.  
  15241.  You can create a trigger that checks the new value in ytd_sales against the
  15242.  roysched table to find whether the current sales total puts a new royalty
  15243.  amount into effect. If so, the trigger updates the royalty column in titles.
  15244.  
  15245.  
  15246.    create trigger sumuptrig2
  15247.     on sales
  15248.     for insert
  15249.     as
  15250.     update titles
  15251.     set titles.ytd_sales = (titles.ytd_sales + inserted.qty),
  15252.      titles.royalty = roysched.royalty
  15253.     from titles, inserted, sales, roysched
  15254.     where inserted.title_id = titles.title_id
  15255.      and titles.title_id = roysched.title_id
  15256.      and (titles.ytd_sales + inserted.qty) >= roysched.lorange
  15257.      and (titles.ytd_sales + inserted.qty) <= roysched.hirange
  15258.  
  15259.  
  15260.  Other Triggers
  15261.  
  15262.  If a table has a unique key, you can prevent updates outside of a certain
  15263.  range by comparing the (previous) value of a field in deleted to its
  15264.  (current) value in inserted to find the difference. The following example
  15265.  prevents all price increases greater than 100%:
  15266.  
  15267.    create trigger sumuptrig3
  15268.     on titles
  15269.     for update
  15270.     as
  15271.     if update (price)
  15272.     if
  15273.     (select count(*)
  15274.     from inserted, deleted
  15275.     where inserted.title_id = deleted.title_id
  15276.      and inserted.price > (deleted.price*2) ) > 0
  15277.     begin
  15278.      print "This increase is greater than 100%, hence illegal!"
  15279.      rollback transaction
  15280.     end
  15281.  
  15282.  In this trigger, you join the rows in inserted and deleted when there is an
  15283.  update to the price column in titles. Then you check to see if any of the
  15284.  prices in inserted (the new values) are more than twice as large as the
  15285.  prices in deleted (the old values). If they are, the update is rolled back.
  15286.  
  15287.  
  15288.  
  15289.  Correlated Subqueries in Triggers
  15290.  
  15291.  The triggers examined so far have looked at each data modification statement
  15292.  as a whole: if one row of a four-row insert was unacceptable, the whole
  15293.  insert was unacceptable and the transaction was rolled back.
  15294.  
  15295.  This is the way most triggers work. A trigger must reject or accept each
  15296.  data modification transaction as a whole.
  15297.  
  15298.  However, using a correlated subquery in a trigger can force the trigger to
  15299.  examine the modified rows one by one. (See Chapter 6, "Building Subqueries,"
  15300.  for more on correlated subqueries.) While the rollback must affect either
  15301.  the whole transaction or none of it, the trigger can take different actions
  15302.  on different rows.
  15303.  
  15304.  The trigger examples in this section assume the existence of a table called
  15305.  newsales. Here is its CREATE statement:
  15306.  
  15307.    create table newsales
  15308.     (stor_id char(4),
  15309.     ord_num varchar(20),
  15310.     date datetime,
  15311.     qty smallint,
  15312.     payterms varchar(12),
  15313.     title_id tid)
  15314.  
  15315.  You should insert four rows in the newsales table, to test the triggers in
  15316.  this section. Two of the newsales rows have title_ids that do not match any
  15317.  of those already in the titles table. Here is the data:
  15318.  
  15319. ╓┌───────┌──────────────┌──────────────┌────────────────────┌───────┌────────
  15320.  ────────────────────────────────────────────────────────────────────────────
  15321.          newsales
  15322.  
  15323.          stor_id        ord_num        date                 qty     payterms
  15324.  
  15325.          -------        --------       -------------------  -----   --------
  15326.  
  15327.          7066           QA7442.3       Sep 13 1985 12:00AM  75      Net 30
  15328.  
  15329.          7066           QA7442.3       Sep 13 1985 12:00AM  75      Net 60
  15330.  
  15331.          7067           D4482          Sep 14 1985 12:00AM  10      Net 30
  15332.  ────────────────────────────────────────────────────────────────────────────
  15333.         7067           D4482          Sep 14 1985 12:00AM  10      Net 30
  15334.  
  15335.          7131           N914008        Sep 14 1985 12:00AM  20      Net 30
  15336.  
  15337.  
  15338.  
  15339.  When you insert data from newsales into sales, the statement looks like
  15340.  this:
  15341.  
  15342.    insert sales
  15343.     select * from newsales
  15344.  
  15345.  All the triggers in this section are insert triggers on the sales table. The
  15346.  first trigger in this section is not a correlated one. It checks to see if a
  15347.  count of the rows in inserted is greater than the count of rows that join
  15348.  between inserted and titles on the title_id columns. If so, the trigger
  15349.  rolls back the entire transaction─no rows are inserted.
  15350.  
  15351.    create trigger anyinsert
  15352.     on sales
  15353.     for insert
  15354.     as
  15355.     if (select inserted.title_id from inserted) not in
  15356.      (select title_id from titles)
  15357.     begin
  15358.      rollback tran
  15359.      print "Can't add these records to sales─"
  15360.      print "One or more title_ids not found in titles."
  15361.     end
  15362.  
  15363.  What if you want to examine each of the records you are trying to insert?
  15364.  This calls for a trigger with a correlated subquery. Drop trigger anyinsert
  15365.  and create another trigger, which is different in two ways:
  15366.  
  15367.  
  15368.    ■   It does not name the outer query in the inner query, and hence is
  15369.        correlated.
  15370.  
  15371.    ■   It does not roll back the transaction.
  15372.  
  15373.  
  15374.  Instead, it adds all the inserted rows but examines each one and gives you a
  15375.  message if there are some nonmatching title_ids.
  15376.  
  15377.    create trigger conditionalinsert
  15378.     on sales
  15379.     for insert
  15380.     as
  15381.     if exists (select * from inserted
  15382.     where not exists
  15383.     (select *
  15384.     from titles
  15385.     where titles.title_id = inserted.title_id))
  15386.     print "All sales records added, but some title_ids not found
  15387.     in the titles table."
  15388.  
  15389.  Since trigger conditionalinsert analyzes the insert row by row, it's
  15390.  possible to modify it so that it conditionally accepts the rows with
  15391.  matching title_ids. Here's how:
  15392.  
  15393.    create trigger only_matching
  15394.     on sales
  15395.     for insert as
  15396.     if exists
  15397.     (select * from inserted
  15398.     where not exists
  15399.     (select * from titles
  15400.     where titles.title_id = inserted.title_id))
  15401.     begin
  15402.      delete sales
  15403.      where sales.title_id not in
  15404.      (select title_id
  15405.      from titles)
  15406.      print "Only sales records with matching title_ids added."
  15407.     end
  15408.  
  15409.  
  15410.  
  15411.  
  15412.  
  15413.  
  15414.  Chapter 14  Advanced Topics for Database Owners
  15415.  ────────────────────────────────────────────────────────────────────────────
  15416.  
  15417.  
  15418.  Introduction
  15419.  
  15420.  This chapter describes some of the statements used for system
  15421.  administration. A few SQL statements that can be used only by the System
  15422.  Administrator are not mentioned in this guide. They are discussed in the SQL
  15423.  Server System Administrator's Guide and the SQL Server Language Reference.
  15424.  
  15425.  The topics covered in this chapter are
  15426.  
  15427.  
  15428.    ■   Assigning permissions (the GRANT and REVOKE statements)
  15429.  
  15430.    ■   Setting query options (the SET statement)
  15431.  
  15432.    ■   Keeping SQL Server's information about indexes up to date (the UPDATE
  15433.        STATISTICS statement)
  15434.  
  15435.    ■   Locking and making system-generated locks more restrictive (the
  15436.        HOLDLOCK keyword, used in SELECT statements)
  15437.  
  15438.    ■   User-defined transactions (the BEGIN TRANSACTION, COMMIT TRANSACTION,
  15439.        SAVE TRANSACTION, and ROLLBACK TRANSACTION statements)
  15440.  
  15441.    ■   Backup and recovery (the DUMP DATABASE, LOAD DATABASE, DUMP
  15442.        TRANSACTION, LOAD TRANSACTION, and CHECKPOINT statements)
  15443.  
  15444.    ■   Checking the physical and logical consistency of the database (the
  15445.        DBCC statement)
  15446.  
  15447.  
  15448.  The discussion of permissions in this chapter provides database object
  15449.  owners with all the information they need to grant and revoke permissions on
  15450.  their objects to other users. The other topics in this list are covered
  15451.  briefly in this chapter. (For more information, see the SQL Server System
  15452.  Administrator's Guide.)
  15453.  
  15454.  
  15455.  Assigning Permissions: GRANT and REVOKE
  15456.  
  15457.  The GRANT and REVOKE statements help to enforce database security. They
  15458.  specify which users can perform which operations on which tables, views, or
  15459.  columns. In discussing the GRANT and REVOKE statements, we often speak of
  15460.  "granting permissions" or "assigning permissions."
  15461.  
  15462.  Permission for many SQL statements can be granted or revoked only by the
  15463.  System Administrator or Database Owner, as shown in the table that appears
  15464.  later in this chapter. This section focuses on the aspects of the
  15465.  permissions system that are of interest to other users, including the owners
  15466.  of database objects. (For more information, see the SQL Server System
  15467.  Administrator's Guide.)
  15468.  
  15469.  
  15470.  Object Permissions and Statement Permissions
  15471.  
  15472.  There are two kinds of permissions assigned with GRANT and REVOKE: object
  15473.  permissions and statement permissions.
  15474.  
  15475.  Object permissions regulate the use of certain statements on certain
  15476.  database objects. They are granted and revoked by the owner of the object.
  15477.  
  15478.  Object permissions apply to the following statements and objects:
  15479.  
  15480. ╓┌─────────────────────────────────┌─────────────────────────────────────────╖
  15481.  Statement                         Object
  15482.  ────────────────────────────────────────────────────────────────────────────
  15483.  SELECT                            table, view, columns
  15484.  
  15485.  UPDATE                            table, view, columns
  15486.  
  15487.  INSERT                            table, view
  15488.  
  15489.  DELETE                            table, view
  15490.  
  15491.  EXECUTE                           stored procedure
  15492.  
  15493.  ────────────────────────────────────────────────────────────────────────────
  15494.  
  15495.  
  15496.  
  15497.  Permissions for other statements are called statement permissions because
  15498.  they are not object specific. They can be granted only by the System
  15499.  Administrator or a Database Owner.
  15500.  
  15501.  The statements to which the statement permissions apply are
  15502.  
  15503.  
  15504.    ■   CREATE DATABASE (can be granted only by the System Administrator and
  15505.        only to users in the master database)
  15506.  
  15507.    ■   CREATE DEFAULT
  15508.  
  15509.    ■   CREATE PROCEDURE
  15510.  
  15511.    ■   CREATE RULE
  15512.  
  15513.    ■   CREATE TABLE
  15514.  
  15515.    ■   CREATE VIEW
  15516.  
  15517.    ■   DUMP DATABASE
  15518.  
  15519.    ■   DUMP TRANSACTION
  15520.  
  15521.  
  15522.  Each database has its own independent protection system. In other words,
  15523.  having permission to use a certain statement in one database has no effect
  15524.  in other databases.
  15525.  
  15526.  If you try to use a statement or database object for which you have not been
  15527.  assigned permission, SQL Server responds with an error message.
  15528.  
  15529.  
  15530.  The Permission Hierarchy
  15531.  
  15532.  Permissions are assigned only by users with particular roles. SQL Server's
  15533.  protection system recognizes these types of users:
  15534.  
  15535.  
  15536.    ■   The System Administrator
  15537.  
  15538.    ■   Owners of databases
  15539.  
  15540.    ■   Owners of database objects
  15541.  
  15542.    ■   Other users (also known as public)
  15543.  
  15544.  
  15545.  The different types of users exist in a kind of hierarchy, with the System
  15546.  Administrator at the top. At each level of the hierarchy, different
  15547.  permissions automatically accrue and different ones can be granted.
  15548.  
  15549.  
  15550.  System Administrator
  15551.  
  15552.  The System Administrator (login ID sa) is recognized by SQL Server as a
  15553.  superuser who has a broad range of permissions and who can assume the
  15554.  identity (and thus the permissions) of any other user. The System
  15555.  Administrator is responsible for adding and dropping users' login IDs from
  15556.  SQL Server, and for granting initial permissions.
  15557.  
  15558.  The System Administrator is a function or role rather than a person. That
  15559.  is, no user's login ID is permanently associated with the role of System
  15560.  Administrator. As far as SQL Server is concerned, if you know the password
  15561.  for the System Administrator, you can be the System Administrator. When you
  15562.  log in as System Administrator, you are working outside SQL Server's
  15563.  protection system.
  15564.  
  15565.  
  15566.  Database Owners
  15567.  
  15568.  Database Owners are next in the hierarchy. The System Administrator and
  15569.  Database Owners are the only users who can grant statement permissions to
  15570.  other users. A Database Owner is responsible for granting users access to
  15571.  his or her database with the sp_adduser and sp_dropuser system procedures,
  15572.  and for setting up user groups with sp_addgroup, sp_changegroup, and
  15573.  sp_dropgroup. (See the SQL Server Language Reference for details.)
  15574.  
  15575.  
  15576.  Database Object Owners
  15577.  
  15578.  At the next level are the owners of database objects (tables, views, and
  15579.  stored procedures), who control permission on those objects. For example, a
  15580.  user who creates (and therefore owns) a table automatically has all of the
  15581.  permissions that apply to that table─SELECT, INSERT, UPDATE, and DELETE. No
  15582.  other users have any permissions on the table until the owner specifically
  15583.  grants them with the GRANT statement.
  15584.  
  15585.  
  15586.  Other Users
  15587.  
  15588.  At the bottom of the hierarchy is the "public"─other database users.
  15589.  Permissions are granted to or revoked from them by object owners, Database
  15590.  Owners, or the System Administrator. As a later section on GRANT and REVOKE
  15591.  syntax explains, these users are specified by username, by groupname, or by
  15592.  the keyword PUBLIC.
  15593.  
  15594.  
  15595.  Permissions of Database Object Owners
  15596.  
  15597.  A user who creates a database object (a table, view, or stored procedure) is
  15598.  its owner and is automatically granted all object permissions on it. Users
  15599.  other than the object owner, including the owner of the database, are
  15600.  automatically denied all permissions on that object unless they are
  15601.  explicitly granted by the owner.
  15602.  
  15603.  As an example, say that Mary is the owner of the pubs database and has
  15604.  granted Joe permission to create tables in it. Now Joe creates the table
  15605.  authors; he is the owner of this database object. Initially, object
  15606.  permissions on authors belong to Joe and Joe alone. Joe can grant object
  15607.  permissions for this table to other users, including Mary, the Database
  15608.  Owner. (However, as the Database Owner, Mary can access the table even if
  15609.  Joe does not execute a GRANT statement by using the SETUSER statement.
  15610.  SETUSER allows a Database Owner to impersonate any user in the same
  15611.  database.)
  15612.  
  15613.  The following statements default to the owner of a table and cannot be
  15614.  transferred to other users:
  15615.  
  15616.  
  15617.    ■   ALTER TABLE
  15618.  
  15619.    ■   CREATE INDEX
  15620.  
  15621.    ■   CREATE TRIGGER
  15622.  
  15623.    ■   DROP TABLE
  15624.  
  15625.    ■   TRUNCATE TABLE
  15626.  
  15627.    ■   UPDATE STATISTICS
  15628.  
  15629.  
  15630.  And of course, permission to use the GRANT and REVOKE statements cannot be
  15631.  transferred.
  15632.  
  15633.  The owner of any object─a table, view, index, stored procedure, rule, or
  15634.  default─cannot transfer permission to use the DROP statement for that
  15635.  object.
  15636.  
  15637.  
  15638.  Permission Summary
  15639.  
  15640.  Table 14.1 summarizes the protection system. The type of user listed as the
  15641.  one to whom the statement defaults is the lowest level of user to whom the
  15642.  permission automatically accrues. This user can grant or revoke the
  15643.  permission to other users, if it is transferable. Users at higher levels are
  15644.  either automatically assigned the permission or (in the case of Database
  15645.  Owners) can get it with the SETUSER statement. (The System Administrator
  15646.  retains full permissions even if he or she executes the SETUSER statement.)
  15647.  
  15648.  
  15649.  For example, the owner of a database does not automatically receive
  15650.  permissions on objects owned by other users. But a Database Owner can always
  15651.  give himself or herself any permission by assuming the identity of the
  15652.  object owner with the SETUSER statement and then writing the appropriate
  15653.  GRANT or REVOKE statements.
  15654.  
  15655.  For permissions that default to public, no permission is required─that is,
  15656.  no GRANT or REVOKE statements need ever be written.
  15657.  
  15658.  Table 14.1  Summary of Protection System
  15659.  
  15660. ╓┌────────────┌────────────┌────────────┌────────────┌───────┌────────────┌──
  15661.                                                              Can Be
  15662.               Defaults to                                    Granted /
  15663.                                                              Revoked
  15664.               System       Db Owner     Table Owner  Public  Yes          No
  15665.               Admin
  15666.  Statement:
  15667.  ────────────────────────────────────────────────────────────────────────────
  15668.                                                              Can Be
  15669.               Defaults to                                    Granted /
  15670.                                                              Revoked
  15671.               System       Db Owner     Table Owner  Public  Yes          No
  15672.               Admin
  15673. ────────────────────────────────────────────────────────────────────────────
  15674.  ALTER        X            ─            ─            ─       (1)          ─
  15675.  DATABASE
  15676.  
  15677.  ALTER TABLE  ─            ─            X            ─       ─            X
  15678.  
  15679.  BEGIN        ─            ─            ─            X       ─            ─
  15680.  TRANSACTION
  15681.  
  15682.  CHECKPOINT   ─            X            ─            ─       ─            X
  15683.  
  15684.  COMMIT       ─            ─            ─            X       ─            ─
  15685.  TRANSACTION
  15686.  
  15687.  CREATE       X            ─            ─            ─       X            ─
  15688.  DATABASE
  15689.                                                              Can Be
  15690.               Defaults to                                    Granted /
  15691.                                                              Revoked
  15692.               System       Db Owner     Table Owner  Public  Yes          No
  15693.               Admin
  15694. DATABASE
  15695.  
  15696.  CREATE       ─            X            ─            ─       X            ─
  15697.  DEFAULT
  15698.  
  15699.  CREATE       ─            ─            X            ─       ─            X
  15700.  INDEX
  15701.  
  15702.  CREATE       ─            X            ─            ─       X            ─
  15703.  PROCEDURE
  15704.  
  15705.  CREATE RULE  ─            X            ─            ─       X            ─
  15706.  
  15707.  CREATE       ─            X            ─            (2)     X(2)         ─
  15708.  TABLE
  15709.  
  15710.                                                              Can Be
  15711.               Defaults to                                    Granted /
  15712.                                                              Revoked
  15713.               System       Db Owner     Table Owner  Public  Yes          No
  15714.               Admin
  15715. 
  15716.  CREATE TRIG  ─            ─            X            ─       ─            X
  15717.  GER
  15718.  
  15719.  CREATE VIEW  ─            X            ─            ─       X            ─
  15720.  
  15721.  DBCC         ─            X            ─            ─       ─            ─
  15722.  
  15723.  DELETE       ─            ─            X(3)         ─       X            ─
  15724.  
  15725.  DISK INIT    X            ─            ─            ─       ─            X
  15726.  
  15727.  DISK REFIT   X            ─            ─            ─       ─            X
  15728.  
  15729.  DISK REINIT  X            ─            ─            ─       ─            X
  15730.  
  15731.                                                              Can Be
  15732.               Defaults to                                    Granted /
  15733.                                                              Revoked
  15734.               System       Db Owner     Table Owner  Public  Yes          No
  15735.               Admin
  15736. 
  15737.  DROP (any    ─            ─            ─            ─       ─            X
  15738.  object)(4)
  15739.  
  15740.  DUMP         ─            X            ─            ─       X            ─
  15741.  DATABASE
  15742.  
  15743.  DUMP         ─            X            ─            ─       X            ─
  15744.  TRANSACTION
  15745.  
  15746.  EXECUTE (5)  ─            ─            ─            ─       X            ─
  15747.  
  15748.  GRANT        ─            X            ─            ─       ─            X
  15749.  
  15750.  GRANT on     ─            ─            ─            ─       ─            X
  15751.  object (4)
  15752.                                                              Can Be
  15753.               Defaults to                                    Granted /
  15754.                                                              Revoked
  15755.               System       Db Owner     Table Owner  Public  Yes          No
  15756.               Admin
  15757. object (4)
  15758.  
  15759.  INSERT       ─            ─            X(3)         ─       X            ─
  15760.  
  15761.  KILL         X            ─            ─            ─       ─            X
  15762.  
  15763.  LOAD         ─            X            ─            ─       ─            X
  15764.  DATABASE
  15765.  
  15766.  LOAD         ─            X            ─            ─       ─            X
  15767.  TRANSACTION
  15768.  
  15769.  PRINT        ─            ─            ─            X       ─            ─
  15770.  
  15771.  RAISERROR    ─            ─            ─            X       ─            ─
  15772.  
  15773.                                                              Can Be
  15774.               Defaults to                                    Granted /
  15775.                                                              Revoked
  15776.               System       Db Owner     Table Owner  Public  Yes          No
  15777.               Admin
  15778. 
  15779.  READTEXT     ─            ─            X(3)         ─       X            ─
  15780.  
  15781.  RECONFIGURE  X            ─            ─            ─       ─            X
  15782.  
  15783.  REVOKE       ─            X            ─            ─       ─            X
  15784.  
  15785.  REVOKE on    ─            ─            ─            ─       ─            X
  15786.  object (4)
  15787.  
  15788.  ROLLBACK     ─            ─            ─            X       ─            ─
  15789.  TRANSACTION
  15790.  
  15791.  SAVE         ─            ─            ─            X       ─            ─
  15792.  TRANSACTION
  15793.  
  15794.                                                              Can Be
  15795.               Defaults to                                    Granted /
  15796.                                                              Revoked
  15797.               System       Db Owner     Table Owner  Public  Yes          No
  15798.               Admin
  15799. 
  15800.  SELECT       ─            ─            X(3)         ─       X            ─
  15801.  
  15802.  SET          ─            ─            ─            X       ─            ─
  15803.  
  15804.  SETUSER      ─            X            ─            ─       ─            X
  15805.  
  15806.  TRUNCATE     ─            ─            X            ─       ─            X
  15807.  TABLE
  15808.  
  15809.  UPDATE       ─            ─            X(3)         ─       X            ─
  15810.  
  15811.  UPDATE       ─            ─            X            ─       ─            X
  15812.  STATISTICS
  15813.  
  15814.  WRITETEXT    ─            ─            X(3)         ─       X            ─
  15815.                                                              Can Be
  15816.               Defaults to                                    Granted /
  15817.                                                              Revoked
  15818.               System       Db Owner     Table Owner  Public  Yes          No
  15819.               Admin
  15820. WRITETEXT    ─            ─            X(3)         ─       X            ─
  15821.  
  15822.  ────────────────────────────────────────────────────────────────────────────
  15823.  
  15824.  
  15825.  
  15826.  (1) Transferred with CREATE DATABASE permission
  15827.  (2) Public can create temporary tables, no permission required
  15828.  (3) If a view, permission defaults to view owner
  15829.  (4) Defaults to object owner
  15830.  (5) Defaults to stored procedure owner
  15831.  
  15832.  
  15833.  
  15834.  GRANT and REVOKE Syntax
  15835.  
  15836.  The syntax statements for object and statement permissions are slightly
  15837.  different. Here are a few statements that grant object permissions. This one
  15838.  grants permission to mary and the sales group to insert and delete the
  15839.  titles table:
  15840.  
  15841.    grant insert, delete
  15842.     on titles
  15843.     to mary, sales
  15844.  
  15845.  This statement grants permission for harold to use the stored procedure
  15846.  makelist.
  15847.  
  15848.    grant execute
  15849.     on makelist
  15850.     to harold
  15851.  
  15852.  This statement revokes permission for all users to update and select from
  15853.  the price and ytd_sales columns of the titles table:
  15854.  
  15855.    revoke update, select
  15856.     on titles (price, ytd_sales)
  15857.     from public
  15858.  
  15859.  These examples show how to grant and revoke statement permissions:
  15860.  
  15861.    grant create table, create view
  15862.     to mary, jane, bob
  15863.  
  15864.     grant dump database
  15865.     to public
  15866.  
  15867.     revoke create table, create rule
  15868.     from mary
  15869.  
  15870.  The full syntax for granting and revoking object permissions (permission to
  15871.  use tables, views, columns, and stored procedures) is as follows:
  15872.  
  15873.    GRANT {ALL | permission_list}
  15874.     ON {table_name [(column_list)] |
  15875.     view_name [(column_list)] |
  15876.     stored_procedure_name}
  15877.     TO {PUBLIC | name_list}
  15878.     REVOKE {ALL | permission_list}
  15879.     ON {table_name [(column_list)] |
  15880.     view_name [(column_list)] |
  15881.     stored_procedure_name}
  15882.     FROM {PUBLIC | name_list}
  15883.  
  15884.  The full syntax for granting and revoking statement permissions follows:
  15885.  
  15886.    GRANT {ALL | statement_list}
  15887.     TO {PUBLIC | name_list}
  15888.     REVOKE {ALL | statement_list}
  15889.     FROM {PUBLIC | name_list}
  15890.  
  15891.  Only the System Administrator can use the ALL keyword when granting
  15892.  statement permissions because only the System Administrator can grant CREATE
  15893.  DATABASE permission.
  15894.  
  15895.  Whether you are granting object permissions or statement permissions, you
  15896.  can include more than one statement in the statement list. Separate the
  15897.  statements with commas.
  15898.  
  15899.  When the GRANT or REVOKE statements are being used to assign permissions on
  15900.  a table or a view, the statement list can consist of any combination of
  15901.  these statements: SELECT, INSERT, DELETE, and UPDATE.
  15902.  
  15903.  When permissions are being granted on columns, the statement list can
  15904.  include SELECT, UPDATE, or both of them. To use a SELECT * statement, you
  15905.  must have SELECT permission on all the columns in a table.
  15906.  
  15907.  When permissions are being granted on stored procedures, the statement list
  15908.  can include EXECUTE only.
  15909.  
  15910.  If more than one statement is included in the statement list, separate them
  15911.  with commas. If the keyword ALL is used in the statements for object
  15912.  permissions, every one of the statements applicable to the object is granted
  15913.  or revoked.
  15914.  
  15915.  The ON clause specifies the object for which the permission is being granted
  15916.  or revoked. Permissions on tables, views, and stored procedures can be
  15917.  granted or revoked for only one object at time. Permissions can be granted
  15918.  for more than one column at a time, but all the columns must be in the same
  15919.  table or view.
  15920.  
  15921.  The keyword PUBLIC refers to all the users of the system. If you grant or
  15922.  revoke permissions to public, you are included as well.
  15923.  
  15924.  The name list is a list of the names of user groups, the names of individual
  15925.  users, or any combination of them. Each name is separated from the following
  15926.  one by a comma.
  15927.  
  15928.  
  15929.  Combining GRANT and REVOKE Statements
  15930.  
  15931.  GRANT and REVOKE statements are order-sensitive: in case of a conflict, the
  15932.  most recently executed statement supersedes all others.
  15933.  
  15934.  There are two basic styles of setting up permissions in a database or on a
  15935.  database object. The most straightforward is to assign specific permissions
  15936.  to specific users.
  15937.  
  15938.  However, if most users are going to be granted most permissions, it's easier
  15939.  to assign all permissions to all users and then revoke specific permissions
  15940.  from specific users.
  15941.  
  15942.  For example, a Database Owner can grant all permissions on the titles table
  15943.  to all users by issuing the following statement:
  15944.  
  15945.    grant all
  15946.     on titles
  15947.     to public
  15948.  
  15949.  Then the Database Owner can execute a series of REVOKE statements, for
  15950.  example:
  15951.  
  15952.    revoke update
  15953.     on titles (royalty, advance)
  15954.     from public
  15955.  
  15956.     revoke delete
  15957.     on titles
  15958.     from mary, sales, john
  15959.  
  15960.  
  15961.  Conflicting GRANT and REVOKE Statements
  15962.  
  15963.  As mentioned in the previous section, GRANT and REVOKE statements are
  15964.  sensitive to the order in which they are executed. For example, if Joe's
  15965.  group has been granted SELECT permission on the titles table and then Joe's
  15966.  permission to select the advance column has been revoked, Joe can select all
  15967.  the columns except advance, while the other users in his group can still
  15968.  select all the columns.
  15969.  
  15970.  A GRANT or REVOKE statement that applies to a group changes any conflicting
  15971.  permissions that have been assigned to any member of that group. For
  15972.  example, if the owner of the titles table has granted different permissions
  15973.  to various members of the sales group and wants to standardize, he or she
  15974.  might execute the following statements:
  15975.  
  15976.    revoke all on titles from sales
  15977.     grant select on titles(title, title_id, type, pub_id) to sales
  15978.  
  15979.  Similarly, a GRANT or REVOKE statement executed to public will change for
  15980.  all users all previously executed permissions that conflict with the new
  15981.  statement.
  15982.  
  15983.  The same GRANT and REVOKE statements executed in different orders can create
  15984.  entirely different situations. For example, this set of statements leaves
  15985.  Joe (who belongs to the public group) without any select permission on
  15986.  titles:
  15987.  
  15988.    grant select on titles(title_id, title) to joe
  15989.     revoke select on titles from public
  15990.  
  15991.  In contrast, the same statements executed in the opposite order result in
  15992.  only Joe having SELECT permission and only on the title_id and title
  15993.  columns:
  15994.  
  15995.    revoke select on titles from public
  15996.     grant select on titles(title_id, title) to joe
  15997.  
  15998.  Remember that when you use the keyword PUBLIC, you are including yourself.
  15999.  It is possible, and sometimes desirable, to deny yourself permission to use
  16000.  your own table, while giving yourself permission to access a view built on
  16001.  it or a stored procedure that references it. (You can always change your
  16002.  mind and reinstitute the permission with a GRANT statement.) You will
  16003.  probably use PUBLIC more frequently as a quick way of revoking permissions
  16004.  and then defining some exceptions, as in the earlier example.
  16005.  
  16006.  
  16007.  Views as Security Mechanisms
  16008.  
  16009.  Permission to access the subset of data in a view must be granted or
  16010.  revoked, regardless of the set of permissions in force on the view's
  16011.  underlying table(s). Data in an underlying table that is not included in the
  16012.  view is hidden from users who are authorized to access the view but not the
  16013.  underlying table.
  16014.  
  16015.  For example, you might not want some users to be able to access the columns
  16016.  in the titles table that have to do with money and sales. You could create a
  16017.  view of the titles table that omits those columns and then give all users
  16018.  permission on the view, but give only the Sales Department permission on the
  16019.  table. Here's how:
  16020.  
  16021.    revoke all on titles to public
  16022.     grant all on bookview to public
  16023.     grant all on titles to sales
  16024.  
  16025.  An equivalent way of setting up these permissions without using a view is
  16026.  this series of statements:
  16027.  
  16028.    A. grant all on titles to public
  16029.  
  16030.    B. revoke select, update
  16031.     on titles (price, advance, royalty, ytd_sales)
  16032.     from public
  16033.  
  16034.    C. grant select on titles (price, advance, royalty, ytd_sales)
  16035.     to sales
  16036.  
  16037.  These statements still allow public to insert and delete rows from the
  16038.  titles table; you would need this additional statement to deny them these
  16039.  permissions:
  16040.  
  16041.    revoke insert, delete on titles
  16042.     to public
  16043.  
  16044.  One possible problem with the second method is that users not in the sales
  16045.  group who enter the following statement might be surprised to see a
  16046.  "permission denied" message:
  16047.  
  16048.    select * from titles
  16049.  
  16050.  SQL Server expands the asterisk into a list of all the columns in the titles
  16051.  table, and since permission on some of these columns has been revoked from
  16052.  nonsales users, refuses access to them. The error message lists the columns
  16053.  for which the user does not have access.
  16054.  
  16055.  To see all the columns for which they do have permission, the non-sales
  16056.  users would have to name them explicitly.
  16057.  
  16058.  (For more information on views, see Chapter 10, "Creating Views.")
  16059.  
  16060.  
  16061.  Stored Procedures as Security Mechanisms
  16062.  
  16063.  A user who has been granted permission to execute a stored procedure can do
  16064.  so even if he or she does not have permissions on tables or views referenced
  16065.  in it. For example, a user might be given permission to execute a stored
  16066.  procedure that updates a row-and-column
  16067.  
  16068.  subset of a specified table, even though that user does not have any other
  16069.  permissions on that table.
  16070.  
  16071.  (For information on stored procedures, see Chapter 12, "Using Stored and
  16072.  System Procedures.")
  16073.  
  16074.  
  16075.  Tuning Queries and Stored Procedures: SET
  16076.  
  16077.  The query processing options allow you to instruct SQL Server to handle
  16078.  queries and stored procedures in a variety of unusual ways. They are turned
  16079.  on or off for the duration of the user's work session with the SQL SET
  16080.  statement. No permissions are required for using the SET statement.
  16081.  
  16082.  The SET statement has the following syntax:
  16083.  
  16084.    SET
  16085.     {{ARITHABORT | ARITHIGNORE | BACKGROUND | NOCOUNT | NOEXEC|
  16086.     OFFSETS {keyword_list} | PARSE ONLY | PROCID | SHOWPLAN |
  16087.     STATISTICS IO | STATISTICS TIME |
  16088.     {ON | OFF} |
  16089.     ROWCOUNT number | TEXTSIZE number}
  16090.  
  16091.  (See the SQL Server Language Reference for details.)
  16092.  
  16093.  This statement causes SQL Server to return a description of the processing
  16094.  plan for each query but not execute it:
  16095.  
  16096.    set showplan on
  16097.     set noexec on
  16098.  
  16099.  This statement causes SQL Server to stop processing each query after it
  16100.  returns the first ten rows:
  16101.  
  16102.    set rowcount 10
  16103.  
  16104.  Although permission to run the SET statement defaults to public, most users
  16105.  have occasion to use only some of the SET options. Explanations of the
  16106.  options are as follows:
  16107.  
  16108.  ARITHABORT
  16109.    Aborts a query when an overflow or divide-by-zero error occurs during
  16110.    query execution.
  16111.  
  16112.  ARITHIGNORE
  16113.    Returns NULL when an overflow or divide-by-zero error occurs during a
  16114.    query. No warning message is displayed. If neither ARITHABORT nor
  16115.    ARITHIGNORE is set, SQL Server returns NULL and prints a warning message
  16116.    after the query is executed.
  16117.  
  16118.  BACKGROUND
  16119.    Puts processes generated by subsequent statements in background and breaks
  16120.    the connection to the workstation. Once BACKGROUND is on, you can't do
  16121.    anything else. Your session is over; you must interrupt it and log in
  16122.    again.
  16123.  
  16124.    If you execute a stored procedure that sets the background option, your
  16125.    session becomes disconnected from your workstation. The connection is not
  16126.    re-established even when the procedure finishes executing.
  16127.  
  16128.  NOCOUNT
  16129.    Turns off the message returned at the end of each statement that tells you
  16130.    how many rows were affected by the statement. The global variable
  16131.    @ROWCOUNT is updated even when NOCOUNT is on.
  16132.  
  16133.  NOEXEC
  16134.    Compiles each query but does not execute it. NOEXEC is often used with
  16135.    SHOWPLAN. Once NOEXEC is turned on, no subsequent statements will be
  16136.    executed (including other SET statements) until NOEXEC is turned off.
  16137.  
  16138.  OFFSETS
  16139.    DB-LIBRARY only. Returns the offset (position in relation to the beginning
  16140.    of the query) of specified keywords in SQL statements. The keyword list is
  16141.    a list, separated with commas, that can include any of the following SQL
  16142.    constructs: SELECT, FROM, ORDER, COMPUTE, TABLE, PROCEDURE, STATEMENT,
  16143.    PARAM, and EXECUTE.
  16144.  
  16145.    The OFFSETS option is used only in an application program using
  16146.    DB-LIBRARY.
  16147.  
  16148.  PARSEONLY
  16149.    Checks the syntax of each query and returns any error messages without
  16150.    generating a sequence tree, compiling, or executing the query. Do not use
  16151.    PARSEONLY in a stored procedure. PARSEONLY returns offsets if the OFFSETS
  16152.    option is on and there are no errors (however, OFFSETS is used only in an
  16153.    application program using DB-LIBRARY).
  16154.  
  16155.  PROCID
  16156.    Returns the ID number of the stored procedure to DB-LIBRARY (not to the
  16157.    user) before sending rows generated by that stored procedure.
  16158.  
  16159.  SHOWPLAN
  16160.    Generates a description of the processing plan for the query and
  16161.    immediately processes it unless NOEXEC is set. Do not use SHOWPLAN in a
  16162.    stored procedure.
  16163.  
  16164.  STATISTICS IO
  16165.    Displays the number of scans, the number of logical reads (pages
  16166.    accessed), and the number of physical reads (disk accesses) for each table
  16167.    referenced in the statement; STATISTICS IO displays the number of pages
  16168.    written for each statement.
  16169.  
  16170.  STATISTICS TIME
  16171.    Displays the time it took to parse and compile each command and the time
  16172.    it took to execute each step of the command. Times are given in timeticks,
  16173.    the exact value of which is machine-dependent.
  16174.  
  16175.  ROWCOUNT number
  16176.    Causes SQL Server to stop processing the query after the specified number
  16177.    of rows are returned. To turn this option off, so that all rows are
  16178.    returned, use "SET ROWCOUNT 0".
  16179.  
  16180.  TEXTSIZE n
  16181.    Specifies the size in bytes of text type data to be returned with a SELECT
  16182.    statement. If you specify a textsize of 0, 32K bytes of data are returned
  16183.    with a SELECT statement. The @TEXTSIZE global variable stores the current
  16184.    setting.
  16185.  
  16186.  If you use the SET statement inside a trigger or stored procedure, the
  16187.  option reverts to its former setting after the trigger or procedure
  16188.  executes.
  16189.  
  16190.  Any options set with a SET statement take effect at the end of the batch.
  16191.  You can combine SET statements and queries in the same batch, but the SET
  16192.  options won't apply to the queries in that batch. Since this batch contains
  16193.  a SET statement and a query, the SET option doesn't take effect:
  16194.  
  16195.    set showplan on
  16196.     select * from publishers
  16197.     go
  16198.  
  16199.     pub_id  pub_name    city   state
  16200.     ------  -------------------- ---------  -----
  16201.     0736  New Age Books   Boston   MA
  16202.     0877  Binnet & Hardley  Washington  DC
  16203.     1389  Algodata Infosystems Berkeley  CA
  16204.  
  16205.     (3 rows affected)
  16206.  
  16207.  If the two statements are put in separate batches, here's what happens:
  16208.  
  16209.    set showplan on
  16210.     go
  16211.     select * from publishers
  16212.     go
  16213.  
  16214.     STEP 1
  16215.     The type of query is SELECT
  16216.     FROM TABLE
  16217.     publishers
  16218.  
  16219.    Nested iteration
  16220.     Table Scan
  16221.     pub_id  pub_name    city   state
  16222.     ------  -------------------- ----------  -----
  16223.     0736  New Age Books   Boston   MA
  16224.     0877  Binnet & Hardley  Washington  DC
  16225.     1389  Algodata Infosystems Berkeley  CA
  16226.  
  16227.     (3 rows affected)
  16228.  
  16229.  
  16230.  UPDATE STATISTICS
  16231.  
  16232.  The UPDATE STATISTICS statement helps SQL Server make the best decisions
  16233.  about which indexes to use when it processes a query by keeping it up to
  16234.  date about the distribution of the key values in the indexes. It should be
  16235.  used when you create an index on already existing data or when a large
  16236.  amount of data in an indexed column has been added, changed, or deleted.
  16237.  
  16238.  Permission to execute the UPDATE STATISTICS statement defaults to the table
  16239.  owner and is not transferable. The UPDATE STATISTICS statement has the
  16240.  following syntax:
  16241.  
  16242.    UPDATE STATISTICS table_name [[database.]owner.] [index_name]
  16243.  
  16244.  If you do not specify an index name, the statement updates the distribution
  16245.  statistics for all the indexes in the specified table. Giving an index name
  16246.  updates statistics for that index only.
  16247.  
  16248.  You can find the name of the indexes by using the sp_helpindex system
  16249.  procedure. This procedure takes a table name as a parameter.
  16250.  
  16251.  Here's how you'd list the indexes for the authors table:
  16252.  
  16253.    sp_helpindex authors
  16254.     index_name  index_description   index_keys
  16255.     ----------  ------------------------ ----------
  16256.     auidind   clustered, unique   au_id
  16257.     aunmind   nonclustered au_lname,  au_fname
  16258.  
  16259.     (2 rows affected)
  16260.  
  16261.  To update the statistics for all of the indexes, type
  16262.  
  16263.    update statistics authors
  16264.  
  16265.  To update the statistics only for the index on the au_id column, type
  16266.  
  16267.    update statistics authors auidind
  16268.  
  16269.  Since TRANSACT-SQL does not require index names to be unique in a database,
  16270.  you must give the name of the table with which the index is associated.
  16271.  
  16272.  
  16273.  Locking and the HOLDLOCK Keyword
  16274.  
  16275.  To prevent other users from interfering with data being used for an active
  16276.  transaction, SQL Server protects the relevant tables or data pages of the
  16277.  database by locking them. Locking is a concurrency control mechanism. It is
  16278.  necessary in a multiuser environment since several users may be concurrently
  16279.  working with the same data.
  16280.  
  16281.  SQL Server handles locking decisions on its own. SQL Server always applies
  16282.  exclusive locks for update operations (UPDATE, INSERT, or DELETE). When an
  16283.  exclusive lock is set, no other transaction can acquire a lock of any kind
  16284.  until the original lock is released at the end of the transaction. The data
  16285.  modification statements are sometimes called "write" operations because they
  16286.  add, remove, or modify data. Even a single-statement update transaction can
  16287.  affect many rows.
  16288.  
  16289.  For nonupdate or "read" operations, such as SELECT, SQL Server applies
  16290.  shared locks. If a shared lock has been applied to a table or data page, a
  16291.  second transaction can also acquire a shared lock even though the first
  16292.  transaction hasn't completed.
  16293.  
  16294.  However, no transaction can acquire an exclusive lock until all shared locks
  16295.  on it have been released. Conversely, if a transaction has an exclusive
  16296.  lock, another transaction can't acquire a shared lock on it. Exclusive locks
  16297.  and shared locks can be applied either at the page level or the table level.
  16298.  
  16299.  
  16300.  
  16301.  The HOLDLOCK Keyword
  16302.  
  16303.  The HOLDLOCK keyword, used after a table name or view name in the FROM
  16304.  clause of a SELECT statement, makes a shared lock more restrictive. It
  16305.  applies only to shared locks, only to the table or view for which it is
  16306.  specified, and only for the duration of the transaction defined by the
  16307.  statement in which it is used.
  16308.  
  16309.  HOLDLOCK instructs SQL Server to hold the shared lock that it has set until
  16310.  the completion of the transaction, instead of releasing it as soon as the
  16311.  required table, view, or data page is no longer needed, whether or not the
  16312.  transaction has been completed.
  16313.  
  16314.  SQL Server's normal handling of shared locks─releasing them as soon as the
  16315.  table, view, or data page is no longer needed─facilitates continued
  16316.  interactive use of the database even while a lengthy transaction is
  16317.  proceeding. However, it also means that if the same entry is read twice
  16318.  within the same transaction, it won't necessarily be the same both times.
  16319.  
  16320.  
  16321.  Deadlocks and Livelocks
  16322.  
  16323.  A deadlock occurs when two users each have a lock on a separate object. Each
  16324.  wants to acquire a lock on the other user's object. When this happens, the
  16325.  first user is waiting for the second to let go of his or her lock, but the
  16326.  second user won't let it go until the lock on the first user's object is
  16327.  freed.
  16328.  
  16329.  SQL Server detects this situation and chooses one of the users. The user's
  16330.  process is killed, and everything starts moving.
  16331.  
  16332.  It is possible to encounter a deadlock when several long-running
  16333.  transactions are being executed at the same time in the same database.
  16334.  
  16335.  In a livelock, a request for an exclusive lock is repeatedly denied because
  16336.  a series of overlapping shared locks keeps interfering.
  16337.  
  16338.  SQL Server detects this situation, too. After four denials to the user
  16339.  requesting the exclusive lock, SQL Server refuses further requests from
  16340.  shared locks. The request for the exclusive lock is then granted.
  16341.  
  16342.  
  16343.  Data Integrity and Transaction Processing
  16344.  
  16345.  A transaction is a mechanism for ensuring that a set of one or more SQL
  16346.  statements is treated as a single unit of work. SQL Server automatically
  16347.  manages all data modification statements, including single-step change
  16348.  requests, as transactions.
  16349.  
  16350.  In addition, users can group a set of SQL statements into a user-defined
  16351.  transaction with the BEGIN TRANSACTION and COMMIT TRANSACTION statements.
  16352.  
  16353.  Transactions allow SQL Server to guarantee
  16354.  
  16355.  
  16356.    ■   Consistency: simultaneous queries and change requests cannot collide
  16357.        with each other, and users never see or operate on data that is
  16358.        partway through a change.
  16359.  
  16360.    ■   Recovery: in case of system failure, the database is recovered
  16361.        completely and automatically.
  16362.  
  16363.  
  16364.  
  16365.  Transactions and Consistency
  16366.  
  16367.  In a multiuser environment, SQL Server must prevent simultaneous queries and
  16368.  data modification requests from interfering with each other. This is
  16369.  important because if the data being processed by a query could be changed by
  16370.  another user's update while the query was running, the results of the query
  16371.  would be ambiguous.
  16372.  
  16373.  SQL Server automatically sets the appropriate level of locking for each
  16374.  transaction. As discussed earlier in this chapter, users can make shared
  16375.  locks more restrictive on a query-by-query basis by including the HOLDLOCK
  16376.  keyword in a SELECT statement.
  16377.  
  16378.  User-defined transactions allow users to instruct SQL Server to process any
  16379.  number of SQL statements as a single unit. They are discussed in a later
  16380.  section.
  16381.  
  16382.  
  16383.  Transactions and Recovery
  16384.  
  16385.  A transaction is both a unit of work and a unit of recovery. The fact that
  16386.  SQL Server handles single-step change requests as transactions means that
  16387.  the database can be recovered completely in case of failures.
  16388.  
  16389.  SQL Server's recovery time is measured in seconds and minutes, rather than
  16390.  hours or days. Users can specify the maximum acceptable recovery time.
  16391.  
  16392.  The SQL statements related to recovery and backup are discussed in a later
  16393.  section.
  16394.  
  16395.  
  16396.  User-Defined Transactions
  16397.  
  16398.  With the BEGIN TRANSACTION and COMMIT TRANSACTION statements, users can
  16399.  instruct SQL Server to process any number of simple transactions as a single
  16400.  unit. ROLLBACK TRANSACTION allows the user to undo the transaction back to
  16401.  its beginning or back to a savepoint inside the transaction that has been
  16402.  defined with the SAVE TRANSACTION statement.
  16403.  
  16404.  In addition to giving the user control over transaction management,
  16405.  user-defined transactions also improve performance since system overhead is
  16406.  incurred only once for a set of transactions, rather than once for each
  16407.  individual statement.
  16408.  
  16409.  The following subsections discuss general transaction rules and each
  16410.  transaction statement in turn. Then an example is given.
  16411.  
  16412.  Any user can define a transaction: no permission is required for any of the
  16413.  transaction statements.
  16414.  
  16415.  Statements that cannot be used inside a user-defined transaction are:
  16416.  
  16417.  
  16418.    ■   CREATE DATABASE, CREATE TABLE, CREATE INDEX, all DROP statements,
  16419.        SELECT INTO (because it creates a table), GRANT, REVOKE, ALTER
  16420.        DATABASE, ALTER TABLE, TRUNCATE TABLE, RECONFIGURE, LOAD DATABASE,
  16421.        LOAD TRANSACTION, and DISK INIT.
  16422.  
  16423.    ■   Some of the system procedures cannot be used inside user-defined
  16424.        transactions because they create temporary tables.
  16425.  
  16426.  
  16427.  
  16428.  BEGIN TRANSACTION and COMMIT TRANSACTION
  16429.  
  16430.  The BEGIN TRANSACTION and COMMIT TRANSACTION statements can enclose any
  16431.  number of SQL statements and/or stored procedures. These statements have the
  16432.  following syntax:
  16433.  
  16434.    BEGIN TRANsaction [transaction_name]
  16435.  
  16436.     COMMIT TRANsaction
  16437.  
  16438.  Here is an example:
  16439.  
  16440.    begin tran
  16441.      statement
  16442.      statement
  16443.      procedure
  16444.      statement
  16445.     commit tran
  16446.  
  16447.  The transaction name must conform to the rules for identifiers.
  16448.  
  16449.  
  16450.  ROLLBACK TRANSACTION and SAVE TRANSACTION
  16451.  
  16452.  If a transaction must be canceled before it is committed─either because of
  16453.  some failure or because of a change by the user─all of its statements or
  16454.  procedures that have been completed must be undone.
  16455.  
  16456.  A transaction can be canceled or rolled back with the ROLLBACK TRANSACTION
  16457.  statement at any time before the COMMIT TRANSACTION statement has been
  16458.  given. You can cancel either an entire transaction or part of it. However,
  16459.  you can't cancel a transaction after it has been committed.
  16460.  
  16461.  The ROLLBACK TRANSACTION statement has the following syntax:
  16462.  
  16463.    ROLLBACK TRANsaction [transaction_name | savepoint_name]
  16464.  
  16465.  A savepoint is a marker that the user puts inside a transaction to indicate
  16466.  a point to which it can be rolled back (in addition to the beginning of the
  16467.  transaction).
  16468.  
  16469.  Within a transaction, duplicate savepoint_names are allowed, but only the
  16470.  first instance of a savepoint_name is used.
  16471.  
  16472.  Savepoints are inserted by putting a SAVE TRANSACTION statement within the
  16473.  transaction. The SAVE TRANSACTION statement has the following syntax:
  16474.  
  16475.    SAVE TRANsaction savepoint_name
  16476.  
  16477.  The savepoint name must conform to the rules for identifiers.
  16478.  
  16479.  If no savepoint name or transaction name is given with the ROLLBACK
  16480.  TRANSACTION statement, the transaction is rolled back to the previous BEGIN
  16481.  TRANSACTION point.
  16482.  
  16483.  Here's how the SAVE TRANSACTION and ROLLBACK TRANSACTION statements might be
  16484.  used:
  16485.  
  16486.    begin tran transaction_name
  16487.      statement
  16488.      statement
  16489.      procedure
  16490.      save tran savepoint_name
  16491.      statement
  16492.     rollback tran savepoint_name
  16493.      statement
  16494.      statement
  16495.     rollback tran
  16496.  
  16497.  The first ROLLBACK TRANSACTION statement rolls the transaction back to the
  16498.  savepoint inside the transaction. The second ROLLBACK TRANSACTION rolls the
  16499.  transaction back to its beginning. If a transaction is rolled back to a
  16500.  savepoint, it must still proceed to completion or be canceled altogether.
  16501.  
  16502.  Until you execute a COMMIT TRANSACTION, SQL Server considers all subsequent
  16503.  statements to be part of the transaction until it encounters another BEGIN
  16504.  TRANSACTION statement. At that point, SQL Server cancels the original
  16505.  transaction and displays an error message.
  16506.  
  16507.  
  16508.  Example
  16509.  
  16510.  This example shows how a user-defined transaction might be specified:
  16511.  
  16512.    begin transaction royaltychange
  16513.      /* A user sets out to change the royalty split for the two
  16514.      authors of The Gourmet Microwave. Since the database would
  16515.      be inconsistent between the two updates, they must be grouped
  16516.      into a user-defined transaction.*/
  16517.     update titleauthor
  16518.     set royaltyper = 65
  16519.     from titleauthor, titles
  16520.     where royaltyper = 75
  16521.      and titleauthor.title_id = titles.title_id
  16522.      and title = "The Gourmet Microwave"
  16523.     update titleauthor
  16524.     set royaltyper = 35
  16525.     from titleauthor, titles
  16526.  
  16527.    where royaltyper = 25
  16528.      and titleauthor.title_id = titles.title_id
  16529.      and title = "The Gourmet Microwave"
  16530.     save transaction percentchanged
  16531.      /* After having updated the royaltyper entries for the two authors,
  16532.      the user inserts the savepoint "percentchanged,"
  16533.      and then experiments to see how a 10% increase in the book's price
  16534.      would affect the authors' royalty earnings.*/
  16535.     update titles
  16536.     set price = price * $1.1
  16537.     where title = "The Gourmet Microwave"
  16538.     select (price * royalty * ytd_sales) * royaltyper
  16539.     from titles, titleauthor
  16540.     where title = "The Gourmet Microwave"
  16541.      and titles.title_id = titleauthor.title_id
  16542.     rollback transaction percentchanged
  16543.      /* The transaction is rolled back to the savepoint with the
  16544.      ROLLBACK TRANSACTION statement.
  16545.      If no savepoint name had been given the transaction would have
  16546.      been rolled back to the BEGIN TRANSACTION.*/
  16547.     commit transaction
  16548.      /* End of royaltychange.*/
  16549.  
  16550.  
  16551.  Backup and Recovery
  16552.  
  16553.  Every change to the database, whether it is the result of a single SQL
  16554.  update statement (a system-defined transaction) or a grouped set of SQL
  16555.  statements (a user-defined transaction), is automatically recorded in the
  16556.  system table syslogs. This table is called the transaction log.
  16557.  
  16558.  Some statements that change the database are not logged─for example,
  16559.  TRUNCATE TABLE, bulk copy into a table that has no indexes, and DUMP
  16560.  TRANSACTION WITH NO_LOG.
  16561.  
  16562.  The transaction log records data modification requests (UPDATE, INSERT, or
  16563.  DELETE statements) on a moment-to-moment basis. When a transaction begins, a
  16564.  BEGIN TRANSACTION event is recorded in the log. As each data modification
  16565.  statement is received, it is recorded in the log.
  16566.  
  16567.  The change is always recorded in the log before any change is made in the
  16568.  database itself. This type of log, called a write-ahead log, ensures that
  16569.  the database can be recovered completely in case of a failure.
  16570.  
  16571.  Failures can be due to hardware or media problems, system software problems,
  16572.  application software problems, program-directed cancellations of
  16573.  transactions, or user decisions to cancel a transaction.
  16574.  
  16575.  In case of any of these failures, the transaction log can be "played back"
  16576.  (with the LOAD statements) against a copy of the database restored from a
  16577.  backup (made with the DUMP statements).
  16578.  
  16579.  To recover from a failure, transactions that were in progress but not yet
  16580.  committed at the time of the failure must be undone (since a partial
  16581.  transaction is not an accurate change). Completed transactions must be
  16582.  redone if there is no guarantee that they have been written to the disk.
  16583.  
  16584.  SQL Server's dynamic dump allows the database and transaction log to be
  16585.  backed up while use of the database continues. Making the backup process
  16586.  quick and easy encourages frequent backups─an important consideration, since
  16587.  their frequency determines the amount of work that could be lost if a system
  16588.  failure should occur.
  16589.  
  16590.  The owner of each database or the System Administrator is usually
  16591.  responsible for backing up the database and its transaction log with the
  16592.  DUMP statements, though permission to execute them can be transferred to
  16593.  other users. Permission to use the LOAD statements, however, defaults to the
  16594.  Database Owner and cannot be transferred.
  16595.  
  16596.  Once the appropriate LOAD statements are executed, SQL Server handles all
  16597.  aspects of the recovery process. SQL Server also automatically controls the
  16598.  checkpoint interval (the point at which all data pages that have been
  16599.  changed are guaranteed to have been written to the disk). Users can force a
  16600.  checkpoint if necessary with the CHECKPOINT statement.
  16601.  
  16602.  (For more information, see the SQL Server Language Reference or the SQL
  16603.  Server System Administrator's Guide.)
  16604.  
  16605.  
  16606.  Database Consistency Checker
  16607.  
  16608.  The Database Consistency Checker (DBCC) is a set of utility statements that
  16609.  checks the logical and physical consistency of a database. It is used in any
  16610.  of these three cases:
  16611.  
  16612.  
  16613.    ■   A system error with a severity level of 22 or 23 has been generated.
  16614.  
  16615.    ■   The System Administrator does a periodic check.
  16616.  
  16617.    ■   You suspect that a database is damaged. (For example, if using a
  16618.        particular table generates the message "corrupted data," you can use
  16619.        the DBCC to determine if other tables in the database are also
  16620.        damaged.)
  16621.  
  16622.  
  16623.  The Database Owner is automatically granted permission to use the DBCC
  16624.  statement and all of its options. A table owner is automatically granted
  16625.  permission to run DBCC CHECKTABLE. These permissions to run DBCC are not
  16626.  transferable.
  16627.  
  16628.  The DBCC has the following syntax:
  16629.  
  16630.    DBCC {CHECKTABLE (table_name) |
  16631.     CHECKDB [(database_name)] |
  16632.     CHECKALLOC [(database_name)] |
  16633.     CHECKCATALOG [(database_name]) |
  16634.     DBREPAIR (database_name, DROPDB) }
  16635.  
  16636.  DBCC can be run while the database is active, except for the DBREPAIR
  16637.  option.
  16638.  
  16639.  Only the CHECKTABLE option is discussed here. (For information on other DBCC
  16640.  options, see the SQL Server System Administrator's Guide and the SQL Server
  16641.  Language Reference.)
  16642.  
  16643.  The CHECKTABLE option checks the specified table to see that index and data
  16644.  pages are correctly linked, that indexes are in properly sorted order, that
  16645.  all pointers are consistent, that the data information on each page is
  16646.  reasonable, and that page offsets are reasonable.
  16647.  
  16648.  Here's an example:
  16649.  
  16650.    dbcc checktable (titles)
  16651.  
  16652.     Checking titles
  16653.     DBCC execution completed. If DBCC printed error messages,
  16654.     see your System Administrator.
  16655.  
  16656.  
  16657.  
  16658.  
  16659.  
  16660.  
  16661.  Appendix A  The pubs Sample Database
  16662.  ────────────────────────────────────────────────────────────────────────────
  16663.  
  16664.  This appendix describes the sample database, pubs. The pubs database has
  16665.  eight tables:
  16666.  
  16667.  
  16668.    ■   publishers
  16669.  
  16670.    ■   titleauthor
  16671.  
  16672.    ■   sales
  16673.  
  16674.    ■   stores
  16675.  
  16676.    ■   discounts
  16677.  
  16678.    ■   roysched
  16679.  
  16680.    ■   authors
  16681.  
  16682.    ■   titles
  16683.  
  16684.  
  16685.  Each database table is described by two figures. The first figure documents
  16686.  the structure of the table; for each table field, the figure lists its
  16687.  datatype, its NULL/NOT NULL status, and any defaults, rules, triggers, and
  16688.  indexes. The second figure lists the table contents.
  16689.  
  16690.  Table   publishers ─ Structure
  16691.  
  16692. ╓┌─────────┌────────────────────────────────┌────────────┌────────────┌──────
  16693.            pub_id                           pub_name     city         state
  16694.  ────────────────────────────────────────────────────────────────────────────
  16695.  Datatype  char(4)                          varchar(40)  varchar(20)  char(2)
  16696.  
  16697.            pub_id                           pub_name     city         state
  16698.  ────────────────────────────────────────────────────────────────────────────
  16699. 
  16700.  Null      not null                         null         null         null
  16701.  
  16702.  Rule      pub_idrule(1)                    ─            ─            ─
  16703.  
  16704.  Index     clust, uniq                      ─            ─            ─
  16705.  
  16706.  ────────────────────────────────────────────────────────────────────────────
  16707.  
  16708.  
  16709.  
  16710.  (1) The pub_idrule states that the data must be 1389, 0736, 0877, 1622, or
  16711.  1756, or must match the pattern  99[0-9][0-9].
  16712.  
  16713.  
  16714.  pub_id                            pub_name    city           state
  16715.  ────────────────────────────────────────────────────────────────────────────
  16716.  1389                              Algodata    Berkeley       CA
  16717.                                    Infosystem
  16718.                                    s
  16719.  
  16720.  0736                              New Age     Boston         MA
  16721.                                    Books
  16722.  
  16723.  0877                              Binnet &    Washington     DC
  16724.                                    Hardley
  16725.  
  16726.  Table   titleauthor ─ Structure
  16727.  
  16728. ╓┌─────────┌───────────────────┌─────────┌─────────┌─────────────────────────╖
  16729.            au_id               title_id  au_ord    royaltyper
  16730.  ────────────────────────────────────────────────────────────────────────────
  16731.  Datatype  id                  tid       smallint  int
  16732.  
  16733.  Null      not null            not null  null      null
  16734.  
  16735.  Index     nonclust            nonclust  ─         ─
  16736.  
  16737.            uniq, nonclust,
  16738.            composite
  16739.            au_id               title_id  au_ord    royaltyper
  16740.  ────────────────────────────────────────────────────────────────────────────
  16741.           composite
  16742.  
  16743.  ────────────────────────────────────────────────────────────────────────────
  16744.  
  16745.  
  16746.  
  16747.  Table   titleauthor ─ Contents
  16748.  
  16749. ╓┌────────────┌─────────┌───────┌────────────────────────────────────────────╖
  16750.  au_id        title_id  au_ord  royaltyper
  16751.  ────────────────────────────────────────────────────────────────────────────
  16752.  409-56-7008  BU1032    1       60
  16753.  
  16754.  213-46-8915  BU1032    2       40
  16755.  
  16756.  238-95-7766  PC1035    1       100
  16757.  
  16758.  213-46-8915  BU2075    1       100
  16759.  
  16760.  au_id        title_id  au_ord  royaltyper
  16761.  ────────────────────────────────────────────────────────────────────────────
  16762. 
  16763.  998-72-3567  PS2091    1       50
  16764.  
  16765.  899-46-2035  PS2091    2       50
  16766.  
  16767.  998-72-3567  PS2106    1       100
  16768.  
  16769.  722-51-5454  MC3021    1       75
  16770.  
  16771.  899-46-2035  MC3021    2       25
  16772.  
  16773.  807-91-6654  TC3218    1       100
  16774.  
  16775.  486-29-1786  PS7777    1       100
  16776.  
  16777.  486-29-1786  PC9999    1       100
  16778.  
  16779.  712-45-1867  MC2222    1       100
  16780.  
  16781.  au_id        title_id  au_ord  royaltyper
  16782.  ────────────────────────────────────────────────────────────────────────────
  16783. 
  16784.  172-32-1176  PS3333    1       100
  16785.  
  16786.  274-80-9391  BU7832    1       100
  16787.  
  16788.  427-17-2319  PC8888    1       50
  16789.  
  16790.  846-92-7186  PC8888    2       50
  16791.  
  16792.  756-30-7391  PS1372    1       75
  16793.  
  16794.  724-80-9391  PS1372    2       25
  16795.  
  16796.  724-80-9391  BU1111    1       60
  16797.  
  16798.  267-41-2394  BU1111    2       40
  16799.  
  16800.  672-71-3249  TC7777    1       40
  16801.  
  16802.  au_id        title_id  au_ord  royaltyper
  16803.  ────────────────────────────────────────────────────────────────────────────
  16804. 
  16805.  267-41-2394  TC7777    2       30
  16806.  
  16807.  472-27-2349  TC7777    3       30
  16808.  
  16809.  648-92-1872  TC4203    1       100
  16810.  
  16811.  ────────────────────────────────────────────────────────────────────────────
  16812.  
  16813.  
  16814.  
  16815.  Table   sales ─ Structure
  16816.  
  16817. ╓┌───────────┌───────────┌────────────┌───────────┌───────────┌────────────┌─
  16818.              stor_id     ord_num      date        qty         payterms     tit
  16819.  ────────────────────────────────────────────────────────────────────────────
  16820.  Datatype    char(4)     varchar(20)  datetime    smallint    varchar(12)  tid
  16821.  
  16822.  Null        not null    not null     not null    not null    not null     not
  16823.              stor_id     ord_num      date        qty         payterms     tit
  16824.  ────────────────────────────────────────────────────────────────────────────
  16825. Null        not null    not null     not null    not null    not null     not
  16826.  
  16827.  Index       ─           ─            ─           ─           ─            non
  16828.  
  16829.  ────────────────────────────────────────────────────────────────────────────
  16830.  
  16831.  
  16832.  
  16833.  Table   sales ─ Contents
  16834.  
  16835. ╓┌────────┌─────────┌─────────┌────┌─────────────────────────────────┌───────
  16836.  stor_id  ord_num   date      qty  payterms                          title_id
  16837.  ────────────────────────────────────────────────────────────────────────────
  16838.  7066     QA7442.3  09/13/85  75   On invoice                        PS2091
  16839.  
  16840.  7067     D4482     09/14/85  10   Net 60                            PS2091
  16841.  
  16842.  7131     N914008   09/14/85  20   Net 30                            PS2091
  16843.  
  16844.  stor_id  ord_num   date      qty  payterms                          title_id
  16845.  ────────────────────────────────────────────────────────────────────────────
  16846. 
  16847.  7131     N914014   09/14/85  25   Net 30                            MC3021
  16848.  
  16849.  8042     423LL922  09/14/85  15   On invoice                        MC3021
  16850.  
  16851.  8042     423LL930  09/14/85  10   On invoice                        BU1032
  16852.  
  16853.  6380     722a      09/13/85  03   Net 60                            PS2091
  16854.  
  16855.  6380     6871      09/14/85  05   Net 60                            BU1032
  16856.  
  16857.  8042     P723      03/11/88  25   Net 30                            BU1111
  16858.  
  16859.  7896     X999      02/21/88  35   On invoice                        BU2075
  16860.  
  16861.  7896     QQ2299    10/28/87  15   Net 60                            BU7832
  16862.  
  16863.  7896     TQ456     12/12/87  10   Net 60                            MC2222
  16864.  
  16865.  stor_id  ord_num   date      qty  payterms                          title_id
  16866.  ────────────────────────────────────────────────────────────────────────────
  16867. 
  16868.  8042     QA879.1   05/22/87  30   Net 30                            PC1035
  16869.  
  16870.  7066     A2976     05/24/87  50   Net 30                            PC8888
  16871.  
  16872.  7131     P3087a    05/29/87  20   Net 60                            PS1372
  16873.  
  16874.  7131     P3087a    05/29/87  25   Net 60                            PS2106
  16875.  
  16876.  7131     P3087a    05/29/87  15   Net 60                            PS3333
  16877.  
  16878.  7131     P3087a    05/29/87  25   Net 60                            PS7777
  16879.  
  16880.  7067     P2121     05/15/87  40   Net 30                            TC3218
  16881.  
  16882.  7067     P2121     05/15/87  20   Net 30                            TC4203
  16883.  
  16884.  7067     P2121     05/15/87  20   Net 30                            TC7777
  16885.  
  16886.  stor_id  ord_num   date      qty  payterms                          title_id
  16887.  ────────────────────────────────────────────────────────────────────────────
  16888. 
  16889.  ────────────────────────────────────────────────────────────────────────────
  16890.  
  16891.  
  16892.  
  16893.  Table   stores ─ Structure
  16894.  
  16895. ╓┌────────────┌────────────┌────────────┌────────────┌────────────┌────────┌─
  16896.               stor_id      stor_name    stor_addres  city         state    zip
  16897.                                         s
  16898.  ────────────────────────────────────────────────────────────────────────────
  16899.  Datatype     char(4)      varchar(40)  varchar(40)  varchar(20)  char(2)  cha
  16900.  
  16901.  Null         not null     null         null         null         null     nul
  16902.  
  16903.  ────────────────────────────────────────────────────────────────────────────
  16904.  
  16905.  
  16906.  
  16907.  Table   stores ─ Contents
  16908.  
  16909. ╓┌────────┌──────────────────────┌──────────────────────┌──────────┌──────┌──
  16910.  stor_id  stor_name              stor_address           city       state  zip
  16911.  ────────────────────────────────────────────────────────────────────────────
  16912.  7066     Barnum's               567 Pasadena Ave.      Tustin     CA     9278
  16913.  
  16914.  7067     News & Brews           577 First St.          Los Gatos  CA     9674
  16915.  
  16916.  7131     Doc-U-Mat: Quality     24-A Avrogado Way      Remulade   WA     9801
  16917.           Laundry and Books
  16918.  
  16919.  8042     Bookbeat               679 Carson St.         Portland   OR     8907
  16920.  
  16921.  6380     Eric the Read Books    788 Catamaugus Ave.    Seattle    WA     9805
  16922.  
  16923.  7896     Fricative Bookshop     89 Madison St.         Fremont    CA     9001
  16924.  
  16925.  ────────────────────────────────────────────────────────────────────────────
  16926.  
  16927.  
  16928.  
  16929.  
  16930.  discounts ─ Structure
  16931.  
  16932.  -         discounttype  stor_id  lowqty    highqty   discount
  16933.  ────────────────────────────────────────────────────────────────────────────
  16934.  Datatype  varchar(40)   char(4)  smallint  smallint  float
  16935.  
  16936.  Null      not null      null     null      null      not null
  16937.  
  16938.  
  16939.  discounts ─ Contents
  16940.  
  16941.  discounttype                      stor_id   lowqty  highqty  discount
  16942.  ────────────────────────────────────────────────────────────────────────────
  16943.  Initial Customer                  ─         ─       ─        10.5
  16944.  
  16945.  Volume Discount                   ─         100     1000     6.7
  16946.  
  16947.  Customer Discount                 8042      ─       ─        5.0
  16948.  
  16949.  
  16950.  roysched ─ Structure
  16951.  
  16952.  -                                 title_id  lorange  hirange  royalty
  16953.  ────────────────────────────────────────────────────────────────────────────
  16954.  Datatype                          tid        int      int      int
  16955.  
  16956.  Null                              not null   null     null     null
  16957.  
  16958.  Index                             nonclust   ─        ─        ─
  16959.  
  16960.  Table   roysched ─ Contents
  16961.  
  16962. ╓┌─────────┌────────┌─┌────────┌─┌───────────────────────────────────────────╖
  16963.  title_id  lorange    hirange    royalty
  16964.  ────────────────────────────────────────────────────────────────────────────
  16965.  BU1032    0          5000       10
  16966.  
  16967.  BU1032    5001       50000      12
  16968.  
  16969.  PC1035    0          2000       10
  16970.  title_id  lorange    hirange    royalty
  16971.  ────────────────────────────────────────────────────────────────────────────
  16972. PC1035    0          2000       10
  16973.  
  16974.  PC1035    2001       3000       12
  16975.  
  16976.  PC1035    3001       4000       14
  16977.  
  16978.  PC1035    4001       10000      16
  16979.  
  16980.  PC1035    10001      50000      18
  16981.  
  16982.  BU2075    0          1000       10
  16983.  
  16984.  BU2075    1001       3000       12
  16985.  
  16986.  BU2075    3001       5000       14
  16987.  
  16988.  BU2075    5001       7000       16
  16989.  
  16990.  BU2075    7001       10000      18
  16991.  title_id  lorange    hirange    royalty
  16992.  ────────────────────────────────────────────────────────────────────────────
  16993. BU2075    7001       10000      18
  16994.  
  16995.  BU2075    10001      12000      20
  16996.  
  16997.  BU2075    12001      14000      22
  16998.  
  16999.  BU2075    14001      50000      24
  17000.  
  17001.  PS2091    0          1000       10
  17002.  
  17003.  PS2091    1001       5000       12
  17004.  
  17005.  PS2091    5001       10000      14
  17006.  
  17007.  PS2091    10001      50000      16
  17008.  
  17009.  PS2106    0          2000       10
  17010.  
  17011.  PS2106    2001       5000       12
  17012.  title_id  lorange    hirange    royalty
  17013.  ────────────────────────────────────────────────────────────────────────────
  17014. PS2106    2001       5000       12
  17015.  
  17016.  PS2106    5001       10000      14
  17017.  
  17018.  PS2106    10001      50000      16
  17019.  
  17020.  MC3021    0          1000       10
  17021.  
  17022.  MC3021    1001       2000       12
  17023.  
  17024.  MC3021    2001       4000       14
  17025.  
  17026.  MC3021    4001       6000       16
  17027.  
  17028.  MC3021    6001       8000       18
  17029.  
  17030.  MC3021    8001       10000      20
  17031.  
  17032.  MC3021    10001      12000      22
  17033.  title_id  lorange    hirange    royalty
  17034.  ────────────────────────────────────────────────────────────────────────────
  17035. MC3021    10001      12000      22
  17036.  
  17037.  MC3021    12001      50000      24
  17038.  
  17039.  TC3218    0          2000       10
  17040.  
  17041.  TC3218    2001       4000       12
  17042.  
  17043.  TC3218    4001       6000       14
  17044.  
  17045.  TC3218    6001       8000       16
  17046.  
  17047.  TC3218    8001       10000      18
  17048.  
  17049.  TC3218    10001      12000      20
  17050.  
  17051.  TC3218    12001      14000      22
  17052.  
  17053.  TC3218    14001      50000      24
  17054.  title_id  lorange    hirange    royalty
  17055.  ────────────────────────────────────────────────────────────────────────────
  17056. TC3218    14001      50000      24
  17057.  
  17058.  TC3218    0          2000       10
  17059.  
  17060.  TC3218    2001       4000       12
  17061.  
  17062.  TC3218    4001       6000       14
  17063.  
  17064.  TC3218    6001       8000       16
  17065.  
  17066.  TC3218    8001       10000      18
  17067.  
  17068.  TC3218    10001      12000      20
  17069.  
  17070.  TC3218    12001      14000      22
  17071.  
  17072.  TC3218    14001      50000      24
  17073.  
  17074.  PC8888    0          5000       10
  17075.  title_id  lorange    hirange    royalty
  17076.  ────────────────────────────────────────────────────────────────────────────
  17077. PC8888    0          5000       10
  17078.  
  17079.  PC8888    5001       10000      12
  17080.  
  17081.  PC8888    10001      15000      14
  17082.  
  17083.  PC8888    15001      50000      16
  17084.  
  17085.  PS7777    0          5000       10
  17086.  
  17087.  PS7777    5001       50000      12
  17088.  
  17089.  PS3333    0          5000       10
  17090.  
  17091.  PS3333    5001       10000      12
  17092.  
  17093.  PS3333    10001      15000      14
  17094.  
  17095.  PS3333    15001      50000      16
  17096.  title_id  lorange    hirange    royalty
  17097.  ────────────────────────────────────────────────────────────────────────────
  17098. PS3333    15001      50000      16
  17099.  
  17100.  BU1111    0          4000       10
  17101.  
  17102.  BU1111    4001       8000       12
  17103.  
  17104.  BU1111    8001       10000      14
  17105.  
  17106.  BU1111    12001      16000      16
  17107.  
  17108.  BU1111    16001      20000      18
  17109.  
  17110.  BU1111    20001      24000      20
  17111.  
  17112.  BU1111    24001      28000      22
  17113.  
  17114.  BU1111    28001      50000      24
  17115.  
  17116.  MC2222    0          2000       10
  17117.  title_id  lorange    hirange    royalty
  17118.  ────────────────────────────────────────────────────────────────────────────
  17119. MC2222    0          2000       10
  17120.  
  17121.  MC2222    2001       4000       12
  17122.  
  17123.  MC2222    4001       8000       14
  17124.  
  17125.  MC2222    8001       12000      16
  17126.  
  17127.  MC2222    8001       12000      16
  17128.  
  17129.  MC2222    12001      20000      18
  17130.  
  17131.  MC2222    20001      50000      20
  17132.  
  17133.  TC7777    0          5000       10
  17134.  
  17135.  TC7777    5001       15000      02
  17136.  
  17137.  TC7777    15001      50000      14
  17138.  title_id  lorange    hirange    royalty
  17139.  ────────────────────────────────────────────────────────────────────────────
  17140. TC7777    15001      50000      14
  17141.  
  17142.  TC4203    0          2000       10
  17143.  
  17144.  TC4203    2001       8000       12
  17145.  
  17146.  TC4203    8001       16000      14
  17147.  
  17148.  TC4203    16001      24000      16
  17149.  
  17150.  TC4203    24001      32000      18
  17151.  
  17152.  TC4203    32001      40000      20
  17153.  
  17154.  TC4203    40001      50000      22
  17155.  
  17156.  BU7832    0          5000       10
  17157.  
  17158.  BU7832    5001       10000      12
  17159.  title_id  lorange    hirange    royalty
  17160.  ────────────────────────────────────────────────────────────────────────────
  17161. BU7832    5001       10000      12
  17162.  
  17163.  BU7832    10001      15000      14
  17164.  
  17165.  BU7832    15001      20000      16
  17166.  
  17167.  BU7832    20001      25000      18
  17168.  
  17169.  BU7832    25001      30000      20
  17170.  
  17171.  BU7832    30001      35000      22
  17172.  
  17173.  BU7832    35001      50000      24
  17174.  
  17175.  PS1372    0          10000      10
  17176.  
  17177.  PS1372    10001      20000      12
  17178.  
  17179.  PS1372    20001      30000      14
  17180.  title_id  lorange    hirange    royalty
  17181.  ────────────────────────────────────────────────────────────────────────────
  17182. PS1372    20001      30000      14
  17183.  
  17184.  PS1372    30001      40000      16
  17185.  
  17186.  PS1372    40001      50000      18
  17187.  
  17188.  ────────────────────────────────────────────────────────────────────────────
  17189.  
  17190.  
  17191.  
  17192.  Table   authors ─ Structure
  17193.  
  17194. ╓┌─────────┌────────┌────────────┌────────────┌─────────┌────────────┌───────
  17195.            au_id    au_lname     au_fname     phone     address      city
  17196.  
  17197.  ────────────────────────────────────────────────────────────────────────────
  17198.  Datatype  id       varchar(40)  varchar(20)  char(12)  varchar(40)  varchar(2
  17199.  
  17200.  Null      not      not null     not null     not null  null         null
  17201.            au_id    au_lname     au_fname     phone     address      city
  17202.  
  17203. Null      not      not null     not null     not null  null         null
  17204.            null
  17205.  
  17206.  Default   ─        ─            ─            UNKNOWN1  ─            ─
  17207.  
  17208.  Index     clust,   nonclust,                 ─         ─            ─
  17209.            uniq     composite
  17210.  
  17211.  ────────────────────────────────────────────────────────────────────────────
  17212.  
  17213.  
  17214.  
  17215.  (1) The default UNKNOWN is inserted if no data is entered.
  17216.  (2) The rule ziprule states that the zip code must match the pattern
  17217.  [0-9][0-9][0-9][0-9][0-9].
  17218.  
  17219.  
  17220.  Table   authors ─ Contents
  17221.  
  17222. ╓┌────────────┌───────────────┌────────────┌─────────┌─────────────┌─────────
  17223.  au_id        au_lname        au_fname     phone     address       city
  17224.  ────────────────────────────────────────────────────────────────────────────
  17225.  409-56-7008  Bennet          Abraham      415       6223 Bateman  Berkeley
  17226.                                            658-9932  St.
  17227.  
  17228.  213-46-8915  Green           Marjorie     415       309 63rd St.  Oakland
  17229.                                            986-7020  #411
  17230.  
  17231.  238-95-7766  Carson          Cheryl       415       589 Darwin    Berkeley
  17232.                                            548-7723  Ln.
  17233.  
  17234.  998-72-3567  Ringer          Albert       801       67 Seventh    Salt Lake
  17235.                                            826-0752  Av.           City
  17236.  
  17237.  899-46-2035  Ringer          Anne         801       67 Seventh    Salt Lake
  17238.                                            826-0752  Av.           City
  17239.  
  17240.  722-51-5454  DeFrance        Michel       219       3 Balding     Gary
  17241.                                            547-9982  Pl.
  17242.  
  17243.  au_id        au_lname        au_fname     phone     address       city
  17244.  ────────────────────────────────────────────────────────────────────────────
  17245. 
  17246.  807-91-6654  Panteley        Sylvia       301       1956          Rockville
  17247.                                            946-8853  Arlington
  17248.                                                      Dr.
  17249.  
  17250.  893-72-1158  McBadden        Heather      707       301 Putnam    Vacaville
  17251.                                            448-4982
  17252.  
  17253.  724-08-9931  Stringer        Dirk         415       5420          Oakland
  17254.                                            843-2991  Telegraph
  17255.                                                      Av.
  17256.  
  17257.  274-80-9391  Straight        Dick         415       5420 College  Oakland
  17258.                                            834-2919  Av.
  17259.  
  17260.  756-30-7391  Karsen          Livia        415       5720 McAuley  Oakland
  17261.                                            534-9219  St.
  17262.  
  17263.  724-80-9391  MacFeather      Stearns      415       44 Upland     Oakland
  17264.  au_id        au_lname        au_fname     phone     address       city
  17265.  ────────────────────────────────────────────────────────────────────────────
  17266. 724-80-9391  MacFeather      Stearns      415       44 Upland     Oakland
  17267.                                            354-7128  Hts.
  17268.  
  17269.  427-17-2319  Dull            Ann          415       3410 Blonde   Palo Alto
  17270.                                            836-7128  St.
  17271.  
  17272.  672-71-3249  Yokomoto        Akiko        415       3 Silver Ct.  Walnut
  17273.                                            935-4228                Creek
  17274.  
  17275.  267-41-2394  O'Leary         Michael      408       22 Cleveland  San Jose
  17276.                                            286-2428  Av. #14
  17277.  
  17278.  472-27-2349  Gringlesby      Burt         707       PO Box 792    Covelo
  17279.                                            938-6445
  17280.  
  17281.  527-72-3246  Greene          Morningstar  615       22 Graybar    Nashville
  17282.                                            297-2723  House Rd.
  17283.  
  17284.  172-32-1176  White           Johnson      408       10932 Bigge   Menlo
  17285.  au_id        au_lname        au_fname     phone     address       city
  17286.  ────────────────────────────────────────────────────────────────────────────
  17287. 172-32-1176  White           Johnson      408       10932 Bigge   Menlo
  17288.                                            496-7223  Rd.           Park
  17289.  
  17290.  712-45-1867  del Castillo    Innes        615       2286 Cram     Ann Arbor
  17291.                                            996-8275  Pl. #86
  17292.  
  17293.  846-92-7186  Hunter          Sheryl       415       3410 Blonde   Palo Alto
  17294.                                            836-7128  St.
  17295.  
  17296.  486-29-1786  Locksley        Chastity     415       18 Broadway   San
  17297.                                            585-4620  Av.           Francisco
  17298.  
  17299.  648-92-1872  Blotchet-Halls  Reginald     503       55 Hillsdale  Corvallis
  17300.                                            745-6402  Bl.
  17301.  
  17302.  341-22-1782  Smith           Meander      913       10            Lawrence
  17303.                                            843-0462  Mississippi
  17304.                                                      Dr.
  17305.  
  17306.  au_id        au_lname        au_fname     phone     address       city
  17307.  ────────────────────────────────────────────────────────────────────────────
  17308. 
  17309.  ────────────────────────────────────────────────────────────────────────────
  17310.  
  17311.  
  17312.  
  17313.  Table   titles ─ Structure
  17314.  
  17315. ╓┌─────────┌──────────┌────────────┌───────────┌────────┌───────┌───────┌────
  17316.            title_id   title        type        pub_id   price   advanc  royalt
  17317.                                                                 e       y
  17318.  ────────────────────────────────────────────────────────────────────────────
  17319.  Datatype  tid        varchar(80)  char(12)    char(4)  money   money   int
  17320.  
  17321.  Null      not null   not null     not null    null     null    null    null
  17322.  
  17323.  Default   ─          ─            UNDECIDED1  ─        ─       ─       ─
  17324.  
  17325.  Rule      ─          ─            ─           ─        ─       ─       ─
  17326.  
  17327.            title_id   title        type        pub_id   price   advanc  royalt
  17328.                                                                 e       y
  17329.  ────────────────────────────────────────────────────────────────────────────
  17330. 
  17331.  Trigger   deltitle3  ─            ─           ─        ─       ─       ─
  17332.  
  17333.  Index     clust,     nonclust     ─           ─        ─       ─       ─
  17334.            uniq
  17335.  
  17336.  ────────────────────────────────────────────────────────────────────────────
  17337.  
  17338.  
  17339.  
  17340.  (1) The default UNDECIDED is inserted if no data is entered in the column.
  17341.  (2) The getdate() function inserts the current date as the default if no
  17342.  data is entered in the column.
  17343.  (3) The deltitle trigger prohibits deleting a title if the title_id is
  17344.  listed in the sales table.
  17345.  
  17346.  
  17347.  Table   titles ─ Contents
  17348.  
  17349. ╓┌────────┌──────────────────┌─────────────┌────────┌────────┌──────────┌────
  17350.  title_i  title              type          pub_id   price    advance    royalt
  17351.  d
  17352.  ────────────────────────────────────────────────────────────────────────────
  17353.  BU1032   The Busy           business      1389     $19.99   $5000.00   10
  17354.           Executive's
  17355.           Database Guide
  17356.  
  17357.  
  17358.  
  17359.  
  17360.  PC1035   But Is It User     popular_comp  1389     $22.95   $7000.00   16
  17361.           Friendly?
  17362.  
  17363.  
  17364.  
  17365.  
  17366.  BU2075   You Can Combat     business      0736     $2.99    $10125.00  24
  17367.           Computer Stress!
  17368.  
  17369.  title_i  title              type          pub_id   price    advance    royalt
  17370.  d
  17371. 
  17372.  
  17373.  
  17374.  
  17375.  
  17376.  
  17377.  PS2091   Is Anger the       psychology    0736     10.95    $2275.00   12
  17378.           Enemy?
  17379.  
  17380.  
  17381.  
  17382.  
  17383.  PS2106   Life Without Fear  psychology    0736     $7.00    $6000.00   10
  17384.  
  17385.  
  17386.  
  17387.  
  17388.  
  17389.  
  17390.  title_i  title              type          pub_id   price    advance    royalt
  17391.  d
  17392. 
  17393.  
  17394.  
  17395.  
  17396.  
  17397.  
  17398.  MC3021   The Gourmet        mod_cook      0877     $2.99    $15000.00  24
  17399.           Microwave
  17400.  
  17401.  
  17402.  
  17403.  TC3218   Onions, Leeks,     trad_cook     0877     $20.95   $7000.00   10
  17404.           and Garlic:
  17405.           Cooking Secrets
  17406.           of the
  17407.           Mediterranean
  17408.  
  17409.  
  17410.  MC3026   The Psychology of  UNDECIDED     0877     NULL     NULL       NULL
  17411.  title_i  title              type          pub_id   price    advance    royalt
  17412.  d
  17413. MC3026   The Psychology of  UNDECIDED     0877     NULL     NULL       NULL
  17414.           Computer Cooking
  17415.  
  17416.  PC8888   Secrets of         popular_comp  1389     $20.00   $8000.00   10
  17417.           Silicon
  17418.           Valley
  17419.  
  17420.  
  17421.  
  17422.  
  17423.  PS7777   Emotional          psychology    0736     $7.99    $4000.00   10
  17424.           Security:
  17425.           A New Algorithm
  17426.  
  17427.  
  17428.  
  17429.  
  17430.  
  17431.  
  17432.  title_i  title              type          pub_id   price    advance    royalt
  17433.  d
  17434. 
  17435.  PS3333   Prolonged Data     psychology    0736     $19.99   $2000.00   10
  17436.           Deprivation:
  17437.           Four Case Studies
  17438.  
  17439.  
  17440.  
  17441.  
  17442.  
  17443.  BU1111   Cooking with       business      1389     $11.95   $5000.00   10
  17444.           Computers:
  17445.           Surreptitious
  17446.           Balance Sheets
  17447.  
  17448.  
  17449.  MC2222   Silicon Valley     mod_cook      0877     $19.99   $0.00      12
  17450.           Gastronomic
  17451.           Treats
  17452.  
  17453.  title_i  title              type          pub_id   price    advance    royalt
  17454.  d
  17455. 
  17456.  
  17457.  
  17458.  
  17459.  
  17460.  TC7777   Sushi, Anyone?     trad_cook     0877     $14.99   $8000.00   10
  17461.  
  17462.  
  17463.  
  17464.  
  17465.  
  17466.  
  17467.  
  17468.  
  17469.  
  17470.  
  17471.  TC4203   Fifty Years in     trad_cook     0877     $11.95   $4000.00   14
  17472.           Buckingham Palace
  17473.           Kitchens
  17474.  title_i  title              type          pub_id   price    advance    royalt
  17475.  d
  17476.          Kitchens
  17477.  
  17478.  
  17479.  
  17480.  
  17481.  
  17482.  BU7832   Straight Talk      business      1389     $19.99   $5000.00   10
  17483.           About Computers
  17484.  
  17485.  
  17486.  
  17487.  
  17488.  PS1372   Computer Phobic    psychology    0877     $21.59   $7000.00   10
  17489.           and Non-Phobic
  17490.           Individuals:
  17491.           Behavior
  17492.           Variations
  17493.  
  17494.  
  17495.  title_i  title              type          pub_id   price    advance    royalt
  17496.  d
  17497. 
  17498.  
  17499.  
  17500.  PC9999   Net Etiquette      popular_comp  1389     NULL     NULL       NULL
  17501.  
  17502.  
  17503.  
  17504.  ────────────────────────────────────────────────────────────────────────────
  17505.  
  17506.  
  17507.  
  17508.  The pubs database contains the following database objects:
  17509.  
  17510.  
  17511.  Rules
  17512.  
  17513.  
  17514.  pub_idrule
  17515.  
  17516.    create rule pub_idrule
  17517.     as @pub_id in ("1389", "0736", "0877", "1622", "1756")
  17518.     or @pub_id like "99[0-9][0-9]"
  17519.  
  17520.  
  17521.  ziprule
  17522.  
  17523.    create rule ziprule
  17524.     as @zip like "[0-9][0-9][0-9][0-9][0-9]"
  17525.  
  17526.  
  17527.  Trigger
  17528.  
  17529.  
  17530.  deltitle
  17531.  
  17532.    create trigger deltitle
  17533.     on titles
  17534.     for delete
  17535.     as
  17536.     if (select count(*) from deleted, sales
  17537.     where sales.title_id = deleted.title_id) > 0
  17538.      begin
  17539.      rollback transaction
  17540.      print "You can't delete a title with sales."
  17541.      end
  17542.  
  17543.  
  17544.  Stored Procedure
  17545.  
  17546.  
  17547.  byroyalty
  17548.  
  17549.    create procedure byroyalty percentage int
  17550.     as
  17551.     select au_id from titleauthor
  17552.     where titleauthor.royaltyper = percentage
  17553.  
  17554.  
  17555.  View
  17556.  
  17557.  
  17558.  titleview
  17559.  
  17560.    create view titleview
  17561.     as
  17562.     select title, au_ord, au_lname, price, ytd_sales, pub_id
  17563.     from authors, titles, titleauthor
  17564.     where authors.au_id = titleauthor.au_id
  17565.     and titles.title_id = titleauthor.title_id
  17566.  
  17567.  
  17568.  Defaults
  17569.  
  17570.  
  17571.  datedflt
  17572.  
  17573.    create default datedflt
  17574.     as getdate( )
  17575.  
  17576.  
  17577.  phonedflt
  17578.  
  17579.    create default phonedflt
  17580.     as "UNKNOWN"
  17581.  
  17582.  
  17583.  typedflt
  17584.  
  17585.    create default typedflt  as "UNDECIDED"
  17586.  
  17587.  Figure A.1 shows the structure of the pubs sample database.
  17588.  
  17589.  (This figure may be found in the printed book).
  17590.  
  17591.  
  17592.  
  17593.  
  17594.  
  17595.  
  17596.  
  17597.  Glossary
  17598.  ────────────────────────────────────────────────────────────────────────────
  17599.  
  17600.  aggregate functions
  17601.  Often used with GROUP BY and HAVING clauses, aggregate functions generate
  17602.  one summary value from a group of values in a specified column. Aggregate
  17603.  functions include AVG, SUM, MIN, MAX, ANY, and COUNT.
  17604.  
  17605.  alias
  17606.  A temporary name given to a table (in the FROM clause) when it is joined
  17607.  with itself in a self join. The temporary table names are then used to
  17608.  qualify the column names in the join.
  17609.  
  17610.  allocation unit
  17611.  A logical unit of SQL Server storage equal to 256 2K data pages, or 1/2
  17612.  megabyte. The DISK INIT statement initializes a new database device for SQL
  17613.  Server and divides it into 1/2 megabyte pieces called allocation units.
  17614.  
  17615.  application
  17616.  A customized program that performs tasks required by a specific situation.
  17617.  
  17618.  arithmetic operators
  17619.  Addition (+), subtraction (-), division (/), and multiplication (*) are
  17620.  arithmetic operators that can be used with numeric columns. Modulo (%) can
  17621.  be used with int, smallint, and tinyint columns only.
  17622.  
  17623.  backup
  17624.  Any procedure for bringing a computer system back to where it was prior to a
  17625.  system malfunction. In the microcomputer environment, backup refers to the
  17626.  process of copying data files to a second, or backup, disk.
  17627.  
  17628.  backup file
  17629.  A duplicate file maintained on a separate disk and kept in a safe location
  17630.  as insurance against loss of the original file.
  17631.  
  17632.  base date
  17633.  The reference date for SQL Server server, January 1, 1900. If the user does
  17634.  not supply a date, the base date is the default date.
  17635.  
  17636.  base tables
  17637.  The permanent tables on which a view is based. Base tables are also called
  17638.  underlying tables.
  17639.  
  17640.  batch
  17641.  One or more TRANSACT-SQL statements terminated by an end-of-batch signal,
  17642.  which submits them to the SQL Server for processing.
  17643.  
  17644.  binary string
  17645.  A string of binary-encoded data.
  17646.  
  17647.  built-in functions
  17648.  A wide variety of functions that take one or more parameters and return
  17649.  results. The built-in functions include mathematical functions, system
  17650.  functions, string functions, text functions, date functions, and a datatype
  17651.  conversion function.
  17652.  
  17653.  Cartesian product
  17654.  All the possible combinations of the rows from each of the tables. The
  17655.  number of rows in the Cartesian product is equal to the number of rows in
  17656.  the first table times the number of rows in the second table. Once the
  17657.  Cartesian product has been formed, the rows that do not satisfy the join
  17658.  conditions are eliminated. SQL Server creates the Cartesian product as the
  17659.  first step in joining tables.
  17660.  
  17661.  cascading delete
  17662.  An operation implemented with a trigger that deletes data from a table based
  17663.  on a deletion from another table. It is often performed in order to delete
  17664.  detail data when master data is deleted.
  17665.  
  17666.  character string
  17667.  Any group of concatenated characters handled as a single data item by a
  17668.  program. Character strings are normally enclosed in quotation marks since
  17669.  they may contain punctuation or blank spaces.
  17670.  
  17671.  checkpoint
  17672.  The point at which all data pages that have been changed are guaranteed to
  17673.  have been written to the disk.
  17674.  
  17675.  clause
  17676.  Part of a statement beginning with a keyword that names the basic operation
  17677.  to be performed.
  17678.  
  17679.  clustered index
  17680.  An index in which the physical order and the logical (indexed) order is the
  17681.  same. The leaf level of a clustered index represents the data pages
  17682.  themselves.
  17683.  
  17684.  column
  17685.  The logical equivalent of a field, it contains an individual data item
  17686.  within a row or record.
  17687.  
  17688.  command
  17689.  An instruction that specifies an operation to be performed by the computer.
  17690.  
  17691.  command terminator
  17692.  The end-of-batch signal that sends the batch to SQL Server for processing.
  17693.  
  17694.  comparison operators
  17695.  Equal to (=), greater than (>), less than (<), greater than or equal to
  17696.  (>>=), less than or equal to (<=), not equal to (!=), not greater than
  17697.  (!>>), and not less than (!<) can all be used in the format expression
  17698.  comparison_operator expression, where an expression is a column name or a
  17699.  constant or any combination of column names and constants.
  17700.  
  17701.  composite index
  17702.  An index entry composed of two or more columns.
  17703.  
  17704.  concatenation
  17705.  Combining expressions to form longer expressions. The expressions can
  17706.  include binary or character strings, column names, or any combination.
  17707.  
  17708.  concurrency
  17709.  When more than one user accesses a particular set of records or files at the
  17710.  same time.
  17711.  
  17712.  context-sensitive protection
  17713.  Provides certain permissions depending on the identity of the user. This
  17714.  type of protection can be provided by SQL Server using a view and the
  17715.  USER_ID system function.
  17716.  
  17717.  CONTROL key
  17718.  A key that assigns another function to certain keys on the computer
  17719.  keyboard. Like the SHIFT key, the CONTROL key is held down while another is
  17720.  pressed. This effectively increases the number of keys on the keyboard.
  17721.  
  17722.  control-of-flow language
  17723.  Programming-like constructs (IF, ELSE, WHILE, GOTO, and so on) provided by
  17724.  TRANSACT-SQL so that the user can control the flow of execution of
  17725.  TRANSACT-SQL statements.
  17726.  
  17727.  conversion function
  17728.  A function used to convert expressions of one datatype into another datatype
  17729.  whenever these conversions are not performed automatically by SQL Server.
  17730.  
  17731.  correlated subquery
  17732.  A subquery that cannot be evaluated independently, but depends on the outer
  17733.  query for its results. It is also called a repeating subquery, since the
  17734.  subquery is executed once for each row that might be selected by the outer
  17735.  query. See also subquery and nested query.
  17736.  
  17737.  data definition
  17738.  The process of setting up databases and creating database objects such as
  17739.  tables, indexes, rules, defaults, procedures, triggers, and views.
  17740.  
  17741.  data dictionary
  17742.  The system tables that contain descriptions of the database objects and how
  17743.  they are structured.
  17744.  
  17745.  data integrity
  17746.  Accuracy and reliability of data provided through transaction logging,
  17747.  stored procedures, and triggers in SQL Server.
  17748.  
  17749.  data modification
  17750.  Adding, deleting, or changing information in the database with the INSERT,
  17751.  DELETE, and UPDATE statements.
  17752.  
  17753.  data sharing
  17754.  Users' ability to transparently share individual pieces of data in a
  17755.  database across different applications.
  17756.  
  17757.  database
  17758.  A set of related data tables and other database objects that are organized
  17759.  and presented to serve a specific purpose.
  17760.  
  17761.  database device
  17762.  A file on which databases and transaction logs are stored. A database device
  17763.  has both a physical name and a logical name.
  17764.  
  17765.  database management system (DBMS)
  17766.  A consistent method for storing, organizing, retrieving, and calculating
  17767.  data in database devices.
  17768.  
  17769.  database object
  17770.  One of the components of a database: a table, view, index, procedure,
  17771.  trigger, column, default, or rule.
  17772.  
  17773.  Database Owner
  17774.  The user who creates a database. A Database Owner has control over all the
  17775.  database objects in that database.
  17776.  
  17777.  datatype
  17778.  Specifies what kind of information each column will hold and how the data
  17779.  will be stored. Eleven system-supplied datatypes are available, and
  17780.  user-defined datatypes can also be built.
  17781.  
  17782.  date function
  17783.  A function that displays information about dates and times, or manipulates
  17784.  date or time values. The five date functions are GETDATE, DATENAME,
  17785.  DATEPART, DATEDIFF, and DATEADD.
  17786.  
  17787.  DB-LIBRARY
  17788.  A set of C functions and macros that allow your application to interact with
  17789.  SQL Server.
  17790.  
  17791.  deadlock
  17792.  A situation which arises when two users, each having a lock on one piece of
  17793.  data, attempt to acquire a lock on the other's piece of data. SQL Server
  17794.  detects deadlocks and kills one user's process.
  17795.  
  17796.  default
  17797.  The option chosen by the system when no other option is specified.
  17798.  
  17799.  default database
  17800.  The database that a user gets by default when he or she logs in.
  17801.  
  17802.  demand lock
  17803.  Prevents any more shared locks from being set on a data resource (table or
  17804.  data page). Any new shared lock request has to wait for the demand lock
  17805.  request to finish.
  17806.  
  17807.  dependent
  17808.  Data is logically dependent on other data when master data in one table must
  17809.  be kept synchronized with detail data in another table to protect the
  17810.  logical consistency of the database.
  17811.  
  17812.  detail data
  17813.  Data in a detail table that logically depends on data in a master table.
  17814.  
  17815.  device
  17816.  Any part of the computer that is capable of sending or receiving
  17817.  information. The keyboard is an example of an input device; the video
  17818.  monitor and printer are output devices.
  17819.  
  17820.  difference
  17821.  In comparing tables, the set of all elements which belong to one table but
  17822.  not to another.
  17823.  
  17824.  disk allocation pieces
  17825.  Disk allocation pieces are the groups of allocation units from which SQL
  17826.  Server constructs a new database device. The minimum size for a disk
  17827.  allocation piece is one allocation unit or 256 2K pages.
  17828.  
  17829.  drive
  17830.  The disk drive identifier. When used as part of a filename, the disk drive
  17831.  identifier must be followed by a colon.
  17832.  
  17833.  dump device
  17834.  A diskette file or hard disk file used to store a dumped database. A dump
  17835.  device has both a physical name and a logical name.
  17836.  
  17837.  dynamic dump
  17838.  A dump made while the database is active.
  17839.  
  17840.  equijoin
  17841.  A join in which the values in the columns being joined are compared on the
  17842.  basis of equality, and all the columns in the tables being joined are
  17843.  included in the results.
  17844.  
  17845.  error message
  17846.  A message that SQL Server displays at the user's terminal when it detects an
  17847.  error condition.
  17848.  
  17849.  error state number
  17850.  The number attached to an SQL Server error message that allows unique
  17851.  identification of the line of SQL Server code at which the error was raised.
  17852.  
  17853.  exclusive lock
  17854.  A lock that prevents any other transaction from acquiring a lock until the
  17855.  original lock is released at the end of a transaction. An exclusive lock is
  17856.  always applied for update operations (INSERT, UPDATE, and DELETE).
  17857.  
  17858.  expression
  17859.  Returns a value. An expression can be a computation, column data, a built-in
  17860.  function, or a subquery.
  17861.  
  17862.  extent lock
  17863.  A lock held on a group of database pages while they are being allocated or
  17864.  freed.
  17865.  
  17866.  fatal error
  17867.  An error with a severity level of 19 and above. It terminates the user's
  17868.  work session so that it is necessary to log in again.
  17869.  
  17870.  field
  17871.  A single item of information contained in a record. The logical equivalent
  17872.  of a column.
  17873.  
  17874.  file
  17875.  The logical equivalent of a table.
  17876.  
  17877.  foreign key
  17878.  A column (or combination of columns) whose values are required to match a
  17879.  primary key in some other table.
  17880.  
  17881.  functions
  17882.  See built-in functions.
  17883.  
  17884.  global variables
  17885.  System-defined variables that SQL Server updates on an ongoing basis. For
  17886.  example, @ERROR contains the last error number generated by the system.
  17887.  
  17888.  guest account
  17889.  If the user name guest exists in the sysusers table of a database, any user
  17890.  with a valid SQL Server login ID can use that database, with limited
  17891.  permissions.
  17892.  
  17893.  identifier
  17894.  The name of a database object (table, view, index, procedure, trigger,
  17895.  column, default, or rule). An identifier can be from 1 to 30 characters
  17896.  long. The first character must be a letter or the # or _ symbol. The
  17897.  following characters can be letters, digits, or the symbols #, $, or _. (A
  17898.  table name beginning with # denotes a temporary table.) Embedded spaces are
  17899.  not allowed.
  17900.  
  17901.  index
  17902.  A set of pointers that are logically ordered by the values of a key. Indexes
  17903.  provide quick access to data and can enforce uniqueness on the rows in a
  17904.  table.
  17905.  
  17906.  infected process
  17907.  A process that terminates abnormally.
  17908.  
  17909.  inner query
  17910.  Another name for a subquery.
  17911.  
  17912.  intent lock
  17913.  Indicates the intention to acquire a share or exclusive lock on a data page.
  17914.  
  17915.  intersection
  17916.  In table comparisons, the set of all elements that belong to both tables.
  17917.  
  17918.  join
  17919.  A basic operation in a relational system that links the rows in two or more
  17920.  tables by comparing the values in specified columns.
  17921.  
  17922.  key
  17923.  A field used to identify a record, often used as the index field for a
  17924.  table.
  17925.  
  17926.  key value
  17927.  Any value that is indexed.
  17928.  
  17929.  keyword
  17930.  A word or phrase that is reserved for exclusive use by TRANSACT-SQL. A
  17931.  keyword is also known as a reserved word.
  17932.  
  17933.  leaf level
  17934.  The bottom level of a clustered or nonclustered index. In a clustered index,
  17935.  the leaf level contains the actual data pages of the table.
  17936.  
  17937.  livelock
  17938.  A request for an exclusive lock that is repeatedly denied because a series
  17939.  of overlapping shared locks keeps interfering. The SQL Server detects the
  17940.  situation after four denials, and refuses further shared locks.
  17941.  
  17942.  local area network (LAN)
  17943.  A system that enables PCs to have access to common data and peripherals.
  17944.  LANs typically consist of PCs with adapter cards, file servers, a network
  17945.  operating sytem, printers, and gateways to departmental or corporate
  17946.  computers.
  17947.  
  17948.  local variable
  17949.  A variable declared with the DECLARE keyword and assigned an initial value
  17950.  with a SELECT statement.
  17951.  
  17952.  locking
  17953.  The process of restricting access to resources in a multiuser environment to
  17954.  maintain security and prevent concurrent access problems. SQL Server
  17955.  automatically applies locks to tables or pages.
  17956.  
  17957.  logical database devicename
  17958.  The name used by SQL Server for a database device. The filename must follow
  17959.  the rules for identifiers.
  17960.  
  17961.  logical dump device name
  17962.  The name used by SQL Server for a dump device.
  17963.  
  17964.  logical operators
  17965.  Operators (AND, OR, and NOT) that can be used in WHERE clauses. AND joins
  17966.  two or more conditions and returns results when all of the conditions are
  17967.  true. OR connects two or more conditions and returns results when any one of
  17968.  the conditions is true.
  17969.  
  17970.  login ID
  17971.  The name a user uses to log in to SQL Server. A login ID is valid if SQL
  17972.  Server has an entry for that user in the system table syslogins.
  17973.  
  17974.  Master Database
  17975.  The Master Database (master) controls the user databases and the operation
  17976.  of SQL Server as a whole. It keeps track of such things as user accounts,
  17977.  ongoing processes, and system error messages.
  17978.  
  17979.  master database device
  17980.  A file stored in the master database.
  17981.  
  17982.  master table
  17983.  A table that contains data on which detail data in another table logically
  17984.  depends. The master table frequently has a primary key, and a detail table
  17985.  will have a matching foreign key.
  17986.  
  17987.  mathematical function
  17988.  A function used for operations on numeric data.
  17989.  
  17990.  message number
  17991.  The number that uniquely identifies an error message.
  17992.  
  17993.  modulo
  17994.  An arithmetic operator represented by the percent sign (%) that gives the
  17995.  integer remainder after a division operation on two integers. For example,
  17996.  21 % 9 = 3 because 21 divided by 9 equals 2 with a remainder of 3.
  17997.  
  17998.  MS OS/2
  17999.  Microsoft Operating System/2, the second-generation operating system
  18000.  codeveloped by Microsoft and IBM to exploit the power and speed of personal
  18001.  computers based on the Intel 80286 and 80386 microprocessors.
  18002.  
  18003.  multitasking
  18004.  The concurrent execution of two or more distinct tasks by a computer.
  18005.  
  18006.  multiuser
  18007.  The ability of a computer to support many users operating at the same time,
  18008.  while providing the full range of capabilities of the computer system to
  18009.  each user.
  18010.  
  18011.  natural join
  18012.  A join in which the values of the columns being joined are compared on the
  18013.  basis of equality, and all the columns in the tables are included in the
  18014.  results, except that only one of each pair of joined columns is included.
  18015.  
  18016.  nested query
  18017.  A SELECT statement that contains one or more subqueries.
  18018.  
  18019.  nested select statement
  18020.  See nested query.
  18021.  
  18022.  nonclustered index
  18023.  An index that stores key values and pointers to data. The leaf level points
  18024.  to data pages rather than containing the data itself.
  18025.  
  18026.  normalization rules
  18027.  The standard rules of database design in a relational database management
  18028.  system.
  18029.  
  18030.  not-equal join
  18031.  A join on the basis of inequality.
  18032.  
  18033.  null
  18034.  Having no explicitly assigned value. NULL is not equivalent to zero or
  18035.  blank. A value of NULL is not considered to be greater than, less than, or
  18036.  equivalent to any other value, including another value of NULL.
  18037.  
  18038.  object
  18039.  See database object.
  18040.  
  18041.  object permissions
  18042.  Permissions that regulate the use of certain statements (data modification
  18043.  statements, plus SELECT, TRUNCATE TABLE, and EXECUTE) to specific tables,
  18044.  views, or columns. See also statement permission.
  18045.  
  18046.  operating system
  18047.  A group of programs that translates your statements to the computer, helping
  18048.  you perform such tasks as creating files, running programs, and printing
  18049.  documents. SQL Server runs on MS OS/2.
  18050.  
  18051.  operators
  18052.  See arithmetic operators, comparison operators, and logical operators.
  18053.  
  18054.  option
  18055.  An optional value supplied to a statement, program, or procedure.
  18056.  
  18057.  outer join
  18058.  A join in which both matching and nonmatching rows are returned. The
  18059.  operators *= and =* are used to indicate that all the rows in the first or
  18060.  second table should be returned, regardless of whether or not there is a
  18061.  match on the join column.
  18062.  
  18063.  outer query
  18064.  Another name for the principal query in a statement containing a subquery.
  18065.  
  18066.  parameter
  18067.  A value supplied to a statement, program, or procedure.
  18068.  
  18069.  parse
  18070.  The process of breaking down a program statement into its separate
  18071.  processing functions.
  18072.  
  18073.  permissions
  18074.  The authority to perform certain actions on certain database objects or to
  18075.  run certain statements.
  18076.  
  18077.  physical database devicename
  18078.  The operating sytem filename for a database device. The operating system
  18079.  filename must include a complete path.
  18080.  
  18081.  physical dump device name
  18082.  The operating system filename for a dump device. The operating sytem
  18083.  filename must include a complete path.
  18084.  
  18085.  precompiled
  18086.  Analyzed and executed according to a stored plan.
  18087.  
  18088.  primary key
  18089.  The column or columns whose values uniquely identify a row in a table.
  18090.  
  18091.  projection
  18092.  One of the basic query operations in a relational system. A projection is a
  18093.  subset of the columns in a table.
  18094.  
  18095.  qualification
  18096.  A search condition.
  18097.  
  18098.  qualified
  18099.  Preceding the name of a database object with the name of the database and
  18100.  the object owner.
  18101.  
  18102.  query
  18103.  A request for the retrieval of data with a SELECT statement.
  18104.  
  18105.  record
  18106.  A group of related fields (columns) of information treated as a unit; the
  18107.  logical equivalent of a row.
  18108.  
  18109.  referential integrity
  18110.  The rules governing data consistency, specifically the relationships among
  18111.  the primary keys and foreign keys of different tables. SQL Server addresses
  18112.  referential integrity with user-defined triggers.
  18113.  
  18114.  relation
  18115.  Synonym for table.
  18116.  
  18117.  relational database management system
  18118.   Organizes data into rows and columns.
  18119.  
  18120.  repeating subquery
  18121.  See correlated subquery.
  18122.  
  18123.  reserved word
  18124.  A word reserved by SQL Server for use as a keyword. Reserved words cannot be
  18125.  used for names of database objects but can be used for names of local
  18126.  variables and stored procedure parameters.
  18127.  
  18128.  restriction
  18129.  One of the basic query operations in a relational system; also called
  18130.  selection. A restriction is a subset of the rows in a table.
  18131.  
  18132.  rollback transaction
  18133.  A TRANSACT-SQL statement used with a user-defined transaction (before a
  18134.  COMMIT TRANSACTION has been received) that cancels the transaction and
  18135.  undoes any changes that were made to the database.
  18136.  
  18137.  row
  18138.  A set of related columns that describes a specific entity; also called a
  18139.  record.
  18140.  
  18141.  row aggregate functions
  18142.  Functions (SUM, AVG, MIN, MAX, and COUNT) that generate a new row for
  18143.  summary data when used with COMPUTE in a SELECT statement.
  18144.  
  18145.  rule
  18146.  A specification that controls what data can be entered in a particular
  18147.  column or in a column of a particular user-defined datatype.
  18148.  
  18149.  SAF
  18150.  See SQL Server Administration Facility (SAF).
  18151.  
  18152.  savepoint
  18153.  A marker that the user puts inside a user-defined transaction. When
  18154.  transactions are rolled back, they are only rolled back to the savepoint.
  18155.  
  18156.  scalar aggregate
  18157.  An aggregate function that produces a single value from a SELECT statement
  18158.  that does not include a GROUP BY clause. This is true whether the aggregate
  18159.  function is operating on all the rows in a table or on a subset of rows
  18160.  defined by a WHERE clause. (See also vector aggregate.)
  18161.  
  18162.  screen
  18163.  The display portion of a video terminal.
  18164.  
  18165.  select list
  18166.  The columns specified in the main clause of a SELECT statement.
  18167.  
  18168.  selection
  18169.  See restriction.
  18170.  
  18171.  self-join
  18172.  A join used for comparing values within a column of a table. Since this
  18173.  operation involves a join of a table with itself, you need to give the table
  18174.  two temporary names, or aliases. The aliases are then used to qualify the
  18175.  column names in the rest of the query.
  18176.  
  18177.  server
  18178.  A computer on a local-area network that controls access to resources such as
  18179.  files, printers, and modems.
  18180.  
  18181.  server user ID
  18182.  The ID number by which a user is known to SQL Server.
  18183.  
  18184.  severity level number
  18185.  The severity of an error condition: errors with severity levels of 19 and
  18186.  above are fatal errors.
  18187.  
  18188.  shared lock
  18189.  A lock created by nonupdate (read) operations. Other users can read the data
  18190.  concurrently, but no transaction can acquire an exclusive lock on the data
  18191.  until all the shared locks have been released.
  18192.  
  18193.  SQL
  18194.  An acronym for Structured Query Language, a database query and programming
  18195.  sublanguage originally developed for IBM mainframe computers. There is now
  18196.  an ANSI standard SQL definition for all computer systems.
  18197.  
  18198.  SQL Server Administration Facility (SAF)
  18199.  A facility that includes menus for performing many system administration
  18200.  functions and an SQL window for making SQL queries.
  18201.  
  18202.  statement
  18203.  Part of SQL Server language that begins with a keyword that names the basic
  18204.  operation to be performed.
  18205.  
  18206.  statement block
  18207.  A series of TRANSACT-SQL statements enclosed between the keywords BEGIN and
  18208.  END so that they are treated as a unit.
  18209.  
  18210.  statement permission
  18211.  Permission to execute a specific statement. See also object permissions.
  18212.  
  18213.  stored procedure
  18214.  A collection of SQL statements and optional control-of-flow statements
  18215.  stored under a name. SQL Server-supplied stored procedures are called system
  18216.  procedures.
  18217.  
  18218.  string
  18219.  See character string.
  18220.  
  18221.  string function
  18222.  A function that operates on strings of characters or binary data. There are
  18223.  two TRANSACT-SQL string functions, SUBSTRING and CHARINDEX.
  18224.  
  18225.  Structured Query Language
  18226.  See SQL.
  18227.  
  18228.  subquery
  18229.  A SELECT statement that is nested inside another SELECT, INSERT, UPDATE, or
  18230.  DELETE statement, or inside another subquery.
  18231.  
  18232.  syntax
  18233.  The rules governing the structure of a command.
  18234.  
  18235.  System Administrator
  18236.  The person or persons responsible for the administrative and operational
  18237.  functions that are independent of any particular application. The System
  18238.  Administrator is likely to be a person with the best overview of all the
  18239.  applications. The System Administrator advises application designers about
  18240.  the data that already exists on SQL Server, makes recommendations about
  18241.  standardizing data definitions across applications, and so on.
  18242.  
  18243.  system databases
  18244.  The three databases on a newly installed SQL Server: the master database,
  18245.  which controls user databases and the operation of SQL Server; the tempdb
  18246.  database, which is used for temporary tables; and the model database, which
  18247.  is used as a template to create new user databases.
  18248.  
  18249.  system function
  18250.  A function that returns special information from the database, particularly
  18251.  from the system tables.
  18252.  
  18253.  system procedures
  18254.  Stored procedures that SQL Server supplies as shortcuts for retrieving
  18255.  information from the system tables or mechanisms for accomplishing database
  18256.  administration and other tasks that involve updating system tables.
  18257.  
  18258.  system table
  18259.  One of the data dictionary tables. The system tables keep track of
  18260.  information about SQL Server as a whole and about each user database. The
  18261.  master database contains some system tables that are not in user databases.
  18262.  
  18263.  table
  18264.  A collection of rows (records) that have associated columns (fields). A
  18265.  table is the logical equivalent of a database device.
  18266.  
  18267.  target list
  18268.  See select list.
  18269.  
  18270.  text function
  18271.  A function used for operations on text data.
  18272.  
  18273.  theta join
  18274.  A join that uses the comparison operators as the join condition. Comparison
  18275.  operators include equal to (=), greater than (>), less than (<), greater
  18276.  than or equal to (>>=), less than or equal to (<=), not equal to (!=), not
  18277.  greater than (!>>), and not less than (!
  18278.  
  18279.  tick
  18280.  On MS OS/2, 312.5 milliseconds.
  18281.  
  18282.  transaction
  18283.  A series of processing steps that results in a specific function or activity
  18284.  being completed. A mechanism for ensuring that a set of actions is treated
  18285.  as a single unit of work. See also user-defined transaction.
  18286.  
  18287.  transaction log
  18288.  A system table (syslogs) in which all changes to the database are recorded.
  18289.  
  18290.  TRANSACT-SQL
  18291.  SQL Server's enhanced version of SQL, it is the standard language for
  18292.  communicating between applications and the server. TRANSACT-SQL includes
  18293.  statements, commands, control-of-flow language, stored procedures, triggers,
  18294.  rules and defaults. Extensions such as stored procedures make TRANSACT-SQL a
  18295.  full programming language.
  18296.  
  18297.  trigger
  18298.  A special form of a stored procedure that goes into effect when a user gives
  18299.  a change statement such as INSERT, DELETE, or UPDATE to a specified table or
  18300.  column. Triggers are often used to enforce referential integrity.
  18301.  
  18302.  trigger actions
  18303.  The actions for which a trigger is specified.
  18304.  
  18305.  trigger conditions
  18306.  The conditions that cause a trigger to take effect.
  18307.  
  18308.  trigger table
  18309.  The table to which a trigger is attached.
  18310.  
  18311.  unique index
  18312.  An index in which no two rows are permitted to have the same index value.
  18313.  
  18314.  update
  18315.  An addition, deletion, or change to data involving INSERT, DELETE, TRUNCATE
  18316.  TABLE, or UPDATE statements.
  18317.  
  18318.  user-defined datatype
  18319.  A definition of the type of data a column can contain; created by the user.
  18320.  These datatypes are defined in terms of the existing system datatypes. Rules
  18321.  and defaults can be bound to user-defined datatypes (but not to system
  18322.  datatypes).
  18323.  
  18324.  user-defined transaction
  18325.  A method of allowing users to group any number of simple transactions as a
  18326.  single unit which can be completed or canceled.
  18327.  
  18328.  utility program
  18329.  A program provided with SQL Server. Utility programs are executed from the
  18330.  operating system command line.
  18331.  
  18332.  variable
  18333.  An entity (user-defined with DECLARE or system-defined as a global variable)
  18334.  that can assume any of a set of values.
  18335.  
  18336.  vector aggregate
  18337.  A value that results from using an aggregate function with a GROUP BY
  18338.  clause. (See also scalar aggregate.)
  18339.  
  18340.  view
  18341.  An alternative way of looking at the data in one or more tables. A view is
  18342.  usually created as a subset of columns from one or more tables.
  18343.  
  18344.  view resolution
  18345.  In queries that involve a view, the process of verifying the validity of
  18346.  database objects in the query, and combining the query and the stored
  18347.  definition of the view.
  18348.  
  18349.  wildcard characters
  18350.  Special characters, the underscore (_) and the percent sign (%), used with
  18351.  the LIKE keyword to stand for one (_) or any number of (%) characters in
  18352.  pattern-matching.
  18353.  
  18354.  window
  18355.  A portion of the display that appears as a separate viewing area outlined by
  18356.  a frame or border.
  18357.  
  18358.  workstation
  18359.  A computer used by a user to work on a local-area network.
  18360.  
  18361.  
  18362.  
  18363.  
  18364.  
  18365.  INDEX
  18366.  ──────────────────────────────────────────────────────────────────────────
  18367.  
  18368.  
  18369.  
  18370.  + string function
  18371.  
  18372.      A
  18373.  ABS mathematical function
  18374.  ACOS mathematical function
  18375.  Aggregate functions
  18376.    and datatype
  18377.    and GROUP BY clause
  18378.    and null value
  18379.    AVG
  18380.    COUNT
  18381.    COUNT(*)
  18382.    DISTINCT
  18383.    MAX
  18384.    MIN
  18385.    multiple columns
  18386.    nest
  18387.    SUM
  18388.    syntax
  18389.  Alias
  18390.    in correlated subquery
  18391.    in subquery
  18392.    table name
  18393.  ALL keyword
  18394.    and GROUP BY clause
  18395.    with subquery
  18396.  ALLOW_DUP_ROW keyword
  18397.  ALTER DATABASE statement
  18398.  ALTER TABLE statement
  18399.  AND operator
  18400.  ANY keyword
  18401.    with subquery
  18402.  Arithmetic operator
  18403.    add (+)
  18404.    divide (/)
  18405.    modulo (%)
  18406.    multiply (*)
  18407.    precedence
  18408.    subtract (-)
  18409.  ASC keyword
  18410.  ASCII string function
  18411.  ASIN mathematical function
  18412.  ATAN mathematical function
  18413.  ATN2 mathematical function
  18414.  AVG
  18415.    aggregate function
  18416.    row aggregate function
  18417.  
  18418.      B
  18419.  Backslash in long string
  18420.  Base table
  18421.  Batch
  18422.    error
  18423.    example
  18424.    file
  18425.    from isql
  18426.    rules
  18427.  BEGIN keyword
  18428.  BEGIN TRANSACTION statement
  18429.  BETWEEN keyword
  18430.  binary datatype
  18431.  bit
  18432.    datatype conversion
  18433.    datatype
  18434.  Boolean expression
  18435.  BREAK keyword
  18436.    and nested loop
  18437.  Break
  18438.  BREAK
  18439.    keyword
  18440.  Built-in function
  18441.  
  18442.      C
  18443.  Cartesian product
  18444.  Cascading delete
  18445.  Case sensitivity
  18446.  CEILING mathematical function
  18447.  char datatype
  18448.  char
  18449.    datatype conversion
  18450.    datatype
  18451.  Character
  18452.    display string in query results
  18453.    quotation marks in string
  18454.    wildcard
  18455.  CHARINDEX string function
  18456.  Checkpoint
  18457.  Clauses
  18458.    COMPUTE BY
  18459.    COMPUTE
  18460.    FROM
  18461.    GROUP BY
  18462.    HAVING
  18463.    INTO
  18464.    ON DEFAULT
  18465.    ON
  18466.    ORDER BY
  18467.    SET
  18468.    WHERE
  18469.  Clustered index
  18470.  CLUSTERED keyword
  18471.  Column
  18472.    add to existing table
  18473.    bind default
  18474.    choose specific
  18475.    choose
  18476.    computed in view definition
  18477.    computed in view
  18478.    define as NULL
  18479.    heading name
  18480.    insert computed
  18481.    name
  18482.    rearrange order
  18483.    rename in query results
  18484.    retrieve
  18485.  COL_LENGTH system function
  18486.  COL_NAME system function
  18487.  Comment
  18488.  COMMIT TRANSACTION statement
  18489.  Comparison operator
  18490.    and correlated subquery
  18491.    in subquery
  18492.    syntax
  18493.  COMPUTE BY clause
  18494.    groups
  18495.    in view definition
  18496.    multiple columns
  18497.  COMPUTE clause
  18498.    and aggregate function
  18499.    multiple
  18500.    rules
  18501.  Concatenate expressions
  18502.  Configuration option
  18503.  CONTINUE keyword
  18504.  Control-break report
  18505.  Control-of-flow
  18506.    keywords
  18507.    language
  18508.  Convention, naming
  18509.  Conversion function
  18510.  CONVERT function
  18511.    style parameter
  18512.  Correlated subquery
  18513.    in HAVING clause
  18514.    with alias
  18515.    with comparison operator
  18516.  COS mathematical function
  18517.  COT mathematical function
  18518.  COUNT(*)
  18519.    aggregate function
  18520.    and null value
  18521.  COUNT
  18522.    aggregate function
  18523.    row aggregate function
  18524.  CREATE DATABASE statement
  18525.  CREATE DEFAULT statement
  18526.  CREATE INDEX statement
  18527.  CREATE PROCEDURE statement
  18528.    display text
  18529.  CREATE RULE statement
  18530.  CREATE TABLE statement
  18531.  CREATE TRIGGER statement
  18532.    display text
  18533.  CREATE VIEW statement
  18534.  
  18535.      D
  18536.  Data
  18537.    definition
  18538.    delete
  18539.    dictionary
  18540.    group results
  18541.    insert into selected columns
  18542.    integrity
  18543.    logical independence
  18544.    modification statement
  18545.    modify
  18546.    restrict access with view
  18547.    retrieve from more than one table
  18548.    update
  18549.  Database Consistency Checker
  18550.  Database object
  18551.    display information about
  18552.    help
  18553.    naming convention
  18554.    owner permissions
  18555.    rename
  18556.  Database option
  18557.    select into/bulkcopy
  18558.  Database Owner
  18559.    permissions
  18560.  Database
  18561.    backup
  18562.    change default
  18563.    change size
  18564.    choose
  18565.    create
  18566.    default
  18567.    delete
  18568.    device
  18569.    drop
  18570.    help
  18571.    integrity
  18572.    master
  18573.    model
  18574.    object name
  18575.    options
  18576.    owner
  18577.    pubs
  18578.    relational management system
  18579.    relational
  18580.    sample
  18581.    size
  18582.    store
  18583.    system
  18584.    temporary
  18585.    transfer ownership
  18586.    user
  18587.  Datatype
  18588.    and aggregate function
  18589.    assign to column
  18590.    binary
  18591.    bind default to user-defined
  18592.    bit
  18593.    char
  18594.    conversion and join
  18595.    conversion default length
  18596.    conversion function
  18597.    conversion hierarchy
  18598.    conversion
  18599.    create
  18600.    datetime
  18601.    default
  18602.    defaults
  18603.    delete
  18604.    drop user-defined
  18605.    enter character and date
  18606.    entry rule
  18607.    float
  18608.    image
  18609.    int
  18610.    length
  18611.    money
  18612.    rename user-defined
  18613.    rules
  18614.    smallint
  18615.    specify length
  18616.    system-supplied
  18617.    text
  18618.    timestamp
  18619.    tinyint
  18620.    user-defined
  18621.    varbinary
  18622.    varchar
  18623.  Date functions
  18624.    DATEADD
  18625.    DATEDIFF
  18626.    DATENAME
  18627.    DATEPART
  18628.    GETDATE
  18629.  Date
  18630.    calculate
  18631.    compute
  18632.    current
  18633.    default display
  18634.    format
  18635.    in comparison
  18636.  DATEADD date function
  18637.  DATEDIFF date function
  18638.  DATENAME date function
  18639.  DATEPART date function
  18640.  datetime datatype
  18641.  datetime
  18642.    datatype conversion
  18643.    datatype
  18644.  DBCC statement
  18645.    options
  18646.  DB_ID system function
  18647.  DB_NAME system function
  18648.  Deadlock
  18649.  DECLARE keyword
  18650.  Default
  18651.    and null value
  18652.    bind
  18653.    create
  18654.    datatype
  18655.    defined
  18656.    delete
  18657.    drop
  18658.    rename
  18659.    temporary
  18660.    unbind
  18661.    user-defined
  18662.  DEGREES mathematical function
  18663.  DELAY option
  18664.  DELETE statement
  18665.    with nested subquery
  18666.  DESC keyword
  18667.  Device, database
  18668.  Difference set theory operation
  18669.  DIFFERENCE string function
  18670.  DISTINCT keyword
  18671.    and aggregate function
  18672.    and null values
  18673.    and row aggregate function
  18674.    in subquery
  18675.  DROP DATABASE statement
  18676.  DROP DEFAULT statement
  18677.  DROP INDEX statement
  18678.  DROP PROCEDURE statement
  18679.  DROP RULE statement
  18680.  DROP TABLE statement
  18681.  DROP TRIGGER statement
  18682.  DROP VIEW statement
  18683.  DUMP statement
  18684.  Duplicate listing, eliminate
  18685.  
  18686.      E
  18687.  ELSE keyword
  18688.  END keyword
  18689.  Equijoin
  18690.  Error
  18691.    display message
  18692.    flag
  18693.    in batch
  18694.  ERROREXIT option
  18695.  EXECUTE keyword
  18696.  EXECUTE statement
  18697.    WITH RECOMPILE
  18698.  EXISTS keyword
  18699.    in subquery
  18700.  EXP mathematical function
  18701.  Expression
  18702.    concatenate
  18703.    subquery as substitute
  18704.    with aggregate function
  18705.  
  18706.      F
  18707.  Field
  18708.  File, batch
  18709.  FILLFACTOR keyword
  18710.  float datatype
  18711.  FLOOR mathematical function
  18712.  Foreign key
  18713.    insert NULL
  18714.    insert
  18715.    update
  18716.  FROM clause (in join)
  18717.  FROM clause
  18718.    with DELETE
  18719.  Functions
  18720.    aggregate
  18721.    built-in
  18722.    conversion
  18723.    CONVERT
  18724.    date
  18725.    image
  18726.    mathematical
  18727.    nest string
  18728.    row aggregate
  18729.    string
  18730.    system
  18731.    text
  18732.    view with built-in
  18733.  
  18734.      G
  18735.  GETDATE date function
  18736.  Global variable
  18737.  
  18738.      @CONNECTIONS
  18739.      @CPU_BUSY
  18740.      @ERROR
  18741.      @IDLE
  18742.      @IO_BUSY
  18743.      @MAX_CONNECTIONS
  18744.      @NESTLEVEL
  18745.      @PACKET_ERRORS
  18746.      @PACK_RECEIVED
  18747.      @PACK_SENT
  18748.      @PROCID
  18749.      @ROWCOUNT
  18750.      @TEXTSIZE
  18751.      @TIMETICKS
  18752.      @TOTAL_ERROR
  18753.      @TOTAL_READ
  18754.      @TOTAL_WRITE
  18755.      @TRANCOUNT
  18756.      @VERSION
  18757.  GOTO Statement
  18758.  GRANT statement
  18759.    combine with REVOKE
  18760.    conflict with REVOKE
  18761.  GROUP BY clause
  18762.    and aggregate functions
  18763.    and ALL keyword
  18764.    and null value
  18765.    and ORDER BY clause
  18766.    and WHERE clause
  18767.    in subquery
  18768.    in view definition
  18769.    multiple columns
  18770.    syntax
  18771.    without aggregate function
  18772.  Guest user
  18773.  
  18774.      H
  18775.  HAVING clause
  18776.    and logical operator
  18777.    compared to WHERE clause
  18778.    with correlated subquery
  18779.    without aggregate functions
  18780.  Heading
  18781.    column name
  18782.  Help
  18783.    database object
  18784.    database
  18785.    index
  18786.    join
  18787.    stored procedure
  18788.    view
  18789.  HOLDLOCK keyword
  18790.  HOST_ID system function
  18791.  HOST_NAME system function
  18792.  
  18793.      I
  18794.  Identifier
  18795.  IF keyword
  18796.  IF UPDATE keyword
  18797.  IGNORE_DUP_KEY keyword
  18798.  IGNORE_DUP_ROW keyword
  18799.  Image functions
  18800.    PATINDEX
  18801.    TEXTPTR
  18802.    TEXTSIZE
  18803.    TEXTVALID
  18804.  image
  18805.    change value
  18806.    datatype
  18807.    function
  18808.    select value
  18809.  IN keyword
  18810.    in subquery
  18811.  Index
  18812.    clustered
  18813.    composite
  18814.    considerations
  18815.    create
  18816.    delete
  18817.    duplicate value
  18818.    help
  18819.    leaf level
  18820.    multiple columns
  18821.    nonclustered
  18822.    primary key
  18823.    search
  18824.    unique
  18825.  INDEX_COL system function
  18826.  Infected process
  18827.  Inner query
  18828.  INSERT statement
  18829.    error
  18830.    with nested subquery
  18831.    with SELECT
  18832.  Insert
  18833.    computed columns
  18834.  int datatype
  18835.  Integrity
  18836.    data
  18837.    referential
  18838.  Intersection set theory operation
  18839.  INTO clause
  18840.  ISNULL system function
  18841.  isql utility program
  18842.  
  18843.      J
  18844.  Join
  18845.    and view
  18846.    compared with subquery
  18847.    expression
  18848.    help
  18849.    multiple tables
  18850.    natural
  18851.    not-equal
  18852.    operator
  18853.    operator, multiple
  18854.    operator, outer
  18855.    outer
  18856.    processing
  18857.    relational model
  18858.    relational operation
  18859.    selection criteria
  18860.    self
  18861.    theta
  18862.    with null value
  18863.  
  18864.      K
  18865.  Keys
  18866.    and views
  18867.    delete
  18868.    foreign
  18869.    insert foreign
  18870.    insert NULL foreign
  18871.    insert primary
  18872.    primary
  18873.    update foreign
  18874.    update primary
  18875.  Keywords
  18876.    ALL
  18877.    ALLOW_DUP_ROW
  18878.    ASC
  18879.    BEGIN
  18880.    BETWEEN
  18881.    BREAK
  18882.    CLUSTERED
  18883.    CONTINUE
  18884.    Control-of-flow
  18885.    DECLARE
  18886.    DESC
  18887.    DISTINCT
  18888.    ELSE
  18889.    END
  18890.    EXECUTE
  18891.    EXISTS
  18892.    FILLFACTOR
  18893.    HOLDLOCK
  18894.    IF UPDATE
  18895.    IF
  18896.    IGNORE_DUP_KEY
  18897.    IGNORE_DUP_ROW
  18898.    IN
  18899.    LIKE
  18900.    NONCLUSTERED
  18901.    NOT BETWEEN
  18902.    NOT IN
  18903.    NOT LIKE
  18904.    NOT
  18905.    PUBLIC
  18906.    SELECT
  18907.    UNIQUE
  18908.    VALUES
  18909.    WHILE
  18910.    WITH RECOMPILE
  18911.  
  18912.      L
  18913.  Label, GOTO
  18914.  Leaf level
  18915.    clustered index
  18916.    nonclustered index
  18917.  LIKE keyword
  18918.    with datetime value
  18919.  Livelock
  18920.  LOAD statement
  18921.  Local variable
  18922.  Lock
  18923.    dead
  18924.    exclusive
  18925.    live
  18926.    shared
  18927.  LOG mathematical function
  18928.  LOG10 mathematical function
  18929.  Logical operator
  18930.    and HAVING clause
  18931.    precedence
  18932.  Login ID
  18933.  LOWER string function
  18934.  LTRIM string function
  18935.  
  18936.      M
  18937.  master database
  18938.  Mathematical functions
  18939.    ABS
  18940.    ACOS
  18941.    ASIN
  18942.    ATAN
  18943.    ATN2
  18944.    CEILING
  18945.    COS
  18946.    COT
  18947.    DEGREES
  18948.    EXP
  18949.    FLOOR
  18950.    LOG
  18951.    LOG10
  18952.    PI
  18953.    POWER
  18954.    RADIANS
  18955.    RAND
  18956.    ROUND
  18957.    SIGN
  18958.    SQRT
  18959.    TAN
  18960.  MAX
  18961.    aggregate function
  18962.    row aggregate function
  18963.  Message, display
  18964.  MIN
  18965.    aggregate function
  18966.    row aggregate function
  18967.  model database
  18968.  Modulo arithmetic operator
  18969.  money datatype
  18970.  money
  18971.    datatype conversion
  18972.    datatype
  18973.  
  18974.      N
  18975.  Name
  18976.    database object
  18977.    table
  18978.  Naming convention
  18979.    database object
  18980.    table
  18981.  Natural join
  18982.  Nest
  18983.    aggregate functions
  18984.    groups
  18985.    query
  18986.    scalar aggregate
  18987.    SELECT statements
  18988.    sort
  18989.    stored procedure
  18990.    string functions
  18991.    subquery
  18992.    vector aggregate
  18993.    WHILE loops
  18994.  Nonclustered index
  18995.  NONCLUSTERED keyword
  18996.  Normalization rule
  18997.  NOT BETWEEN keyword
  18998.  NOT EXISTS
  18999.    in subquery
  19000.  NOT IN keyword
  19001.    in subquery
  19002.  NOT keyword
  19003.  NOT LIKE keyword
  19004.  NOT operator
  19005.  Not-equal join
  19006.  Notational conventions
  19007.  Null value
  19008.    and aggregate functions
  19009.    and COUNT(*)
  19010.    and default
  19011.    and GROUP BY clause
  19012.    compare
  19013.    in computation
  19014.    in computed columns
  19015.    in joins
  19016.    in stored procedure
  19017.    in underlying object
  19018.    trigger
  19019.  NULL
  19020.    defined
  19021.    sort
  19022.  
  19023.      O
  19024.  Object permissions
  19025.  OBJECT_ID system function
  19026.  OBJECT_NAME system function
  19027.  ON clause
  19028.  ON DEFAULT clause
  19029.  Operator
  19030.    comparison
  19031.    join
  19032.  Options
  19033.    DELAY
  19034.    ERROREXIT
  19035.    PROCESSEXIT
  19036.    TIME
  19037.  OR operator
  19038.  ORDER BY clause
  19039.  Outer join
  19040.  Outer query
  19041.  Owner, database
  19042.  
  19043.      P
  19044.  Parameter
  19045.    stored procedure default
  19046.    use multiple
  19047.  Password
  19048.  PATINDEX function
  19049.  Permissions
  19050.    assign
  19051.    CREATE PROCEDURE
  19052.    data modification
  19053.    Database Object Owner
  19054.    Database Owner
  19055.    DROP TRIGGER
  19056.    hierarchy
  19057.    object
  19058.    on view
  19059.    public
  19060.    statement
  19061.    stored procedure
  19062.    summary table
  19063.    System Administrator
  19064.    system procedures
  19065.    table owner
  19066.    trigger
  19067.  PI mathematical function
  19068.  POWER mathematical function
  19069.  Primary key
  19070.    delete
  19071.    index
  19072.    insert
  19073.    update
  19074.  PRINT statement
  19075.  Procedure
  19076.    name
  19077.    rename
  19078.    stored
  19079.  PROCESSEXIT option
  19080.  Projection relational operation
  19081.  Projection
  19082.  PUBLIC keyword
  19083.  pubs sample database
  19084.  
  19085.      Q
  19086.  Qualification
  19087.  Query results
  19088.    display character string
  19089.    rename columns
  19090.    sort
  19091.  Query
  19092.    inner
  19093.    nest
  19094.    outer
  19095.    processing option
  19096.    view
  19097.  Quotation mark
  19098.    use in character strings
  19099.  
  19100.      R
  19101.  RADIANS mathematical function
  19102.  RAISERROR statement
  19103.  RAND mathematical function
  19104.  Range search condition
  19105.  READTEXT statement
  19106.  Record
  19107.  Referential integrity
  19108.  Relational database
  19109.    management system
  19110.  Relational operation
  19111.  Relational operators
  19112.  REPLICATE string function
  19113.  Report
  19114.    control-break
  19115.  Restriction relational operation
  19116.  Results
  19117.    group data
  19118.    sort
  19119.  RETURN statement
  19120.  REVOKE statement
  19121.    combine with GRANT
  19122.    conflict with GRANT
  19123.  RIGHT string function
  19124.  ROLLBACK TRANSACTION statement
  19125.  ROUND mathematical function
  19126.  Row aggregate functions
  19127.    AVG
  19128.    COUNT
  19129.    MAX
  19130.    MIN
  19131.    SUM
  19132.  Row
  19133.    aggregate function
  19134.    choose
  19135.    copy
  19136.    delete all
  19137.    duplicate
  19138.    insert
  19139.    summary
  19140.    unique
  19141.  Rule
  19142.    bind
  19143.    create
  19144.    datatype
  19145.    defined
  19146.    delete
  19147.    display text
  19148.    drop
  19149.    for batch file
  19150.    normalization
  19151.    rename
  19152.    stored procedure
  19153.    unbind
  19154.  
  19155.      S
  19156.  SAF
  19157.     see SQL Server Administration Facility; see
  19158.  Sample database
  19159.  Sample database, pubs
  19160.  SAVE TRANSACTION statement
  19161.  Savepoint
  19162.  Scalar aggregate
  19163.    nest
  19164.  Search condition
  19165.    comparison operator
  19166.    LIKE clause
  19167.    lists
  19168.    range
  19169.    wildcard
  19170.  Security
  19171.    and permissions
  19172.    with view
  19173.  SELECT * statement
  19174.  select into/bulkcopy database option
  19175.  SELECT keyword
  19176.    in join
  19177.  Select list
  19178.    compute values
  19179.    display character string
  19180.    DISTINCT keyword
  19181.    summary
  19182.  SELECT statement
  19183.    and variable assignment
  19184.    and view
  19185.    clause order
  19186.    in INSERT statement
  19187.    nest
  19188.    use to add row
  19189.  Select
  19190.    image value
  19191.    text value
  19192.  Self-join
  19193.    subquery
  19194.  SET clause
  19195.  SET statement
  19196.    options
  19197.  Set theory operation
  19198.  SETUSER statement
  19199.  SIGN mathematical function
  19200.  smallint datatype
  19201.  Sort
  19202.    nest
  19203.    query results
  19204.  SOUNDEX string function
  19205.  SPACE string function
  19206.  Space
  19207.    used by table
  19208.  sp_addtype
  19209.  sp_adduser
  19210.  sp_bindefault
  19211.  sp_bindrule
  19212.  sp_changedbowner
  19213.  sp_commonkey
  19214.  sp_configure
  19215.  sp_defaultdb
  19216.  sp_depends
  19217.  sp_droptype
  19218.  sp_help
  19219.  sp_helpdb
  19220.  sp_helpindex
  19221.  sp_helpjoins
  19222.  sp_helptext
  19223.  sp_rename
  19224.  sp_spaceused
  19225.  sp_unbindefault
  19226.  sp_unbindrule
  19227.  SQL Server Administration Facility (SAF)
  19228.  SQL
  19229.    extension
  19230.    history
  19231.  SQRT mathematical function
  19232.  Statement permissions
  19233.  Statements
  19234.    ALTER DATABASE
  19235.    ALTER TABLE
  19236.    BEGIN TRANSACTION
  19237.    COMMIT TRANSACTION
  19238.    CREATE DATABASE
  19239.    CREATE DEFAULT
  19240.    CREATE INDEX
  19241.    CREATE PROCEDURE
  19242.    CREATE RULE
  19243.    CREATE TABLE
  19244.    CREATE TRIGGER
  19245.    CREATE VIEW
  19246.    DBCC
  19247.    DELETE
  19248.    DROP DATABASE
  19249.    DROP DEFAULT
  19250.    DROP PROCEDURE
  19251.    DROP RULE
  19252.    DROP TABLE
  19253.    DROP TRIGGER
  19254.    DROP VIEW
  19255.    DUMP
  19256.    GOTO
  19257.    GRANT
  19258.    INSERT
  19259.    LOAD
  19260.    PRINT
  19261.    RAISERROR
  19262.    READTEXT
  19263.    RETURN
  19264.    REVOKE
  19265.    ROLLBACK TRANSACTION
  19266.    SAVE TRANSACTION
  19267.    SELECT
  19268.    SET
  19269.    SETUSER
  19270.    TRUNCATE TABLE
  19271.    UPDATE STATISTICS
  19272.    UPDATE
  19273.    USE
  19274.    WAITFOR
  19275.    WRITETEXT
  19276.  Stored procedure
  19277.    as security mechanism
  19278.    create
  19279.    default parameter
  19280.    delete
  19281.    display report
  19282.    display text
  19283.    drop object
  19284.    execute
  19285.    group
  19286.    help
  19287.    list references
  19288.    multiple parameters
  19289.    name
  19290.    nest
  19291.    null value as default
  19292.    object owner name
  19293.    parameter
  19294.    permissions
  19295.    reference temporary table
  19296.    rename
  19297.    rule
  19298.    wildcard character as default
  19299.    WITH RECOMPILE
  19300.  STR string function
  19301.  String functions
  19302.    +
  19303.    ASCII
  19304.    CHAR
  19305.    CHARINDEX
  19306.    concatenate
  19307.    DIFFERENCE
  19308.    LOWER
  19309.    LTRIM
  19310.    nest
  19311.    REPLICATE
  19312.    RIGHT
  19313.    SOUNDEX
  19314.    SPACE
  19315.    STR
  19316.    STUFF
  19317.    SUBSTRING
  19318.    UPPER
  19319.  String
  19320.    match
  19321.  Structured query language
  19322.     see SQL; see
  19323.  STUFF string function
  19324.  Style parameter
  19325.    CONVERT
  19326.  Subquery
  19327.    compared to not-equal join
  19328.    compared with join
  19329.    correlated
  19330.    correlated, in trigger
  19331.    instead of expression
  19332.    nest
  19333.    repeating
  19334.    rules
  19335.    select list
  19336.    self-join
  19337.    syntax
  19338.    table name
  19339.    with alias
  19340.    with ALL keyword
  19341.    with ANY keyword
  19342.    with comparison operator
  19343.    with DISTINCT keyword
  19344.    with EXISTS keyword
  19345.    with GROUP BY clause
  19346.    with IN keyword
  19347.    with modified comparison operator
  19348.    with NOT EXISTS
  19349.    with NOT IN keyword
  19350.    with WHERE clause
  19351.  SUBSTRING string function
  19352.  SUM
  19353.    aggregate function
  19354.    row aggregate function
  19355.  Summary
  19356.    row
  19357.    value trigger
  19358.    value
  19359.  SUSER_ID system function
  19360.  SUSER_NAME system function
  19361.  Syntax
  19362.    aggregate function
  19363.    ALTER DATABASE statement
  19364.    ALTER TABLE statement
  19365.    BEGIN TRANSACTION
  19366.    BEGIN...END
  19367.    BREAK
  19368.    CHARINDEX string function
  19369.    COMMIT TRANSACTION
  19370.    comparison operator
  19371.    COMPUTE BY
  19372.    COMPUTE clause
  19373.    CONTINUE
  19374.    CONVERT
  19375.    CREATE DATABASE
  19376.    CREATE DEFAULT statement
  19377.    CREATE INDEX
  19378.    CREATE PROCEDURE
  19379.    CREATE RULE
  19380.    CREATE TABLE statement
  19381.    CREATE TRIGGER
  19382.    CREATE VIEW
  19383.    DBCC
  19384.    DELETE
  19385.    DROP DATABASE statement
  19386.    DROP DEFAULT
  19387.    DROP INDEX
  19388.    DROP PROCEDURE
  19389.    DROP RULE
  19390.    DROP TABLE statement
  19391.    DROP TRIGGER
  19392.    DROP VIEW
  19393.    EXECUTE
  19394.    FROM clause
  19395.    GOTO
  19396.    GRANT
  19397.    GROUP BY clause
  19398.    IF...ELSE
  19399.    INSERT
  19400.    local variable
  19401.    RAISERROR
  19402.    READTEXT
  19403.    RETURN
  19404.    REVOKE
  19405.    ROLLBACK TRANSACTION
  19406.    SAVE TRANSACTION
  19407.    SELECT *
  19408.    select list
  19409.    SELECT
  19410.    SET
  19411.    sp_addtype
  19412.    sp_bindefault
  19413.    sp_bindrule
  19414.    sp_help
  19415.    sp_helpjoins
  19416.    sp_rename
  19417.    sp_spaceused
  19418.    sp_unbindrule
  19419.    subquery with comparison operator
  19420.    subquery with IN keyword
  19421.    subquery
  19422.    SUBSTRING function
  19423.    system function
  19424.    TRUNCATE TABLE
  19425.    UPDATE STATISTICS
  19426.    UPDATE
  19427.    USE statement
  19428.    USE
  19429.    WAITFOR
  19430.    WHERE
  19431.    WHILE
  19432.  sysdatabases table
  19433.  sysdevices table
  19434.  System Administrator permissions
  19435.  System database
  19436.  System functions
  19437.    COL_LENGTH
  19438.    COL_NAME
  19439.    DB_ID
  19440.    DB_NAME
  19441.    HOST_ID
  19442.    HOST_NAME
  19443.    INDEX_COL
  19444.    ISNULL
  19445.    OBJECT_ID
  19446.    OBJECT_NAME
  19447.    SUSER_ID
  19448.    SUSER_NAME
  19449.    USER_ID
  19450.    USER_NAME
  19451.  System procedures
  19452.    configuration option
  19453.    current users
  19454.    data definition
  19455.    database objects
  19456.    database options
  19457.    dump devices
  19458.    locks
  19459.    permissions
  19460.    sp_addtype
  19461.    sp_adduser
  19462.    sp_bindefault
  19463.    sp_bindrule
  19464.    sp_changedbowner
  19465.    sp_commonkey
  19466.    sp_configure
  19467.    sp_defaultdb
  19468.    sp_depends
  19469.    sp_droptype
  19470.    sp_help
  19471.    sp_helpdb
  19472.    sp_helpindex
  19473.    sp_helpjoins
  19474.    sp_helptext
  19475.    sp_rename
  19476.    sp_spaceused
  19477.    sp_unbindefault
  19478.    sp_unbindrule
  19479.    user identification
  19480.  System table
  19481.  System tables
  19482.    sysdatabases
  19483.    sysdevices
  19484.    sysusages
  19485.  sysusages table
  19486.  
  19487.      T
  19488.  Table
  19489.    # in name
  19490.    add column
  19491.    alias in correlated subquery
  19492.    alias
  19493.    base
  19494.    Cartesian product
  19495.    change existing
  19496.    create in different database
  19497.    create temporary
  19498.    create
  19499.    delete
  19500.    join multiple
  19501.    name in subquery
  19502.    name
  19503.    naming convention
  19504.    owner permissions
  19505.    rename
  19506.    sample design
  19507.    space used
  19508.    specify
  19509.    steps to create
  19510.    temporary
  19511.  TAN mathematical function
  19512.  tempdb database
  19513.  Temporary table
  19514.  Temporary
  19515.    database
  19516.    table
  19517.  Text functions
  19518.    PATINDEX
  19519.    TEXTPTR
  19520.    TEXTSIZE
  19521.    TEXTVALID
  19522.  text
  19523.    change value
  19524.    datatype
  19525.    function
  19526.    select value
  19527.  TEXTPTR function
  19528.  TEXTSIZE function
  19529.  TEXTVALID function
  19530.  Theta join
  19531.  TIME option
  19532.  Time
  19533.    default display
  19534.    format
  19535.  timestamp datatype
  19536.  tinyint datatype
  19537.  Total
  19538.  TRANSACT-SQL
  19539.    SQL enhancement
  19540.  Transaction
  19541.    backup log
  19542.    log
  19543.    process
  19544.  Trigger
  19545.    computed value
  19546.    create
  19547.    delete
  19548.    display text
  19549.    example
  19550.    list references
  19551.    memory use
  19552.    null value
  19553.    permissions
  19554.    rename
  19555.    report
  19556.    restrictions
  19557.    store
  19558.    summary value
  19559.    with correlated subquery
  19560.    with SET statement
  19561.  TRUNCATE TABLE statement
  19562.    permissions
  19563.  
  19564.      U
  19565.  Unbind
  19566.    default
  19567.    rule
  19568.  UNIQUE keyword
  19569.  UPDATE statement
  19570.    with nested subquery
  19571.  UPDATE STATISTICS statement
  19572.  UPPER string function
  19573.  USE statement
  19574.  User
  19575.    add
  19576.    current
  19577.    database
  19578.    guest
  19579.    identification
  19580.  USER_ID system function
  19581.  USER_NAME system function
  19582.  
  19583.      V
  19584.  Value
  19585.    summary
  19586.    unknown (null)
  19587.  VALUES keyword
  19588.  varbinary datatype
  19589.  varchar datatype
  19590.  varchar
  19591.    datatype conversion
  19592.    datatype
  19593.  Variable
  19594.    global. See Global variable
  19595.    local
  19596.  Vector aggregate
  19597.    nest
  19598.  View
  19599.    advantage of
  19600.    and built-in function
  19601.    and keys
  19602.    and SELECT statement
  19603.    as security mechanism
  19604.    change underlying objects
  19605.    COMPUTE BY in definition
  19606.    computed columns in definition
  19607.    create
  19608.    delete
  19609.    dependent
  19610.    derive from another view
  19611.    drop underlying objects
  19612.    GROUP BY in definition
  19613.    help
  19614.    name
  19615.    null value in underlying object
  19616.    objects referenced
  19617.    permissions
  19618.    projection
  19619.    query
  19620.    redefine
  19621.    rename column
  19622.    rename
  19623.    resolution
  19624.    restrictions
  19625.    use to retrieve data
  19626.    with computed column
  19627.    with join
  19628.  
  19629.      W
  19630.  WAITFOR statement
  19631.  WHERE clause
  19632.    and GROUP BY clause
  19633.    compared to HAVING clause
  19634.    in join
  19635.    in subquery
  19636.    with DELETE
  19637.  WHILE keyword
  19638.  WHILE loops, nest
  19639.  Wildcard character
  19640.    in search
  19641.    in stored procedure
  19642.  WITH RECOMPILE keyword
  19643.    in EXECUTE statement
  19644.    in stored procedure
  19645.  WRITETEXT statement
  19646.  
  19647.