Microsoft® SQL Server® 2012 Bible

(Ben Green) #1

118


Part II: Building Databases and Working with Data


The output clause is covered in Chapter 12. Consuming the output clause as a subquery is demon-
strated in Chapter 9.

The FROM clause can merge data from multiple sources using several types of joins, as described in detail in Chapter 9.

Table Aliases
You can assign a data source a table alias within the FROM clause. When the data source has
an alias, you must refer to it by this new name. In some cases the data source must have
an alias. The following code accesses the Person table but refers to it within the query as
table P:

-- From Table [AS] Table Alias
USE AdventureWorks;
SELECT
P.LastName,P.FirstName
FROM Person.Person AS P;

In some cases the data source must have an alias. For example, when writing a query that
has a subquery as the source, you must specify an alias. The following code accesses a sub-
query that has an alias of SQ.

--From Subquery [AS] Alias
USE AdventureWorks
SELECT
SQL.LastName, SQL.FirstName
FROM
(
SELECT LastName, FirstName from Person.Person
) AS SQL;

Best Practice


Using the keyword AS to assign an alias to a column or data source is optional and is commonly ignored.
However, this practice leads to errors in the query, as seen regularly in SQL Server newsgroups. As a
rule, always include the AS keyword.

In SQL, the USE command specifi es the current database. It’s the code version of selecting a database from the
toolbar in Management Studio.

c06.indd 118c06.indd 118 7/30/2012 4:15:59 PM7/30/2012 4:15:59 PM


http://www.it-ebooks.info
Free download pdf