Microsoft® SQL Server® 2012 Bible

(Ben Green) #1

129


Chapter 6: Introducing Basic Query Flow


6


(0 row(s) affected)Columns, Stars, Aliases, and Expressions ...................................


The title of this section may read like a bad tabloid headline, but in all seriousness it
means that the SQL SELECT statement returns columns in the order in which you list
them in the SELECT statement. The column may be any expression or any column in the
FROM clause.

Following the FROM clause and the WHERE clause, the next logical step in the query is the
list of returned expressions.

The Star
The *, commonly called “star,” is a special wildcard that includes all columns in their table
order. If the query pulls from multiple tables, the * includes all columns from every table.
Alternatively, tablename.* includes only the columns from the named table. Also, if you
alias any tables in the FROM clause, you can return a complete column list of a specifi c
example by using table alias.*.

Aliases
The name of the column in the underlying table becomes the name of the column in the
result set. Optionally, you can change the column name using a column alias.

Expressions and constants have a blank column heading in the result set unless an alias is
provided.

The AS keyword is optional, but just as with a table alias, using it is a good practice that
improves the readability of the code and helps prevent errors.

To use an alias that’s identical to a SQL Server keyword or that includes a space, enclose the
alias in square brackets, single quotes, or double quotes. Although the square brackets are
not technically required if the alias is the same as an object name (that is, table or column
name), you an explicitly specify that the alias is not a keyword.

The following code demonstrates adding aliases to columns:

USE AdventureWorks;
SELECT
Name AS ProductName,
'abc',
SellStartDate + 365 OneYearSellStartDate
FROM Production.Product;

c06.indd 129c06.indd 129 7/30/2012 4:16:04 PM7/30/2012 4:16:04 PM


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