CHAPTER 2
Single-Table Queries
65
This query produces the following output.
empid fullname
----------- -------------------------------
1 Sara Davis
2 Don Funk
3 Judy Lew
4 Yael Peled
5 Sven Buck
6 Paul Suurs
7 Russell King
8 Maria Cameron
9 Zoya Dolgopyatova
Standard SQL dictates that a concatenation with a NULL should yield a NULL. This is the default be-
havior of SQL Server. For example, consider the query against the Customers table shown in Listing 2-7.
LISTING 2-7
Query Demonstrating String Concatenation
SELECT custid, country, region, city,
country + N',' + region + N',' + city AS location
FROM Sales.Customers;
Some of the rows in the Customers table have a NULL in the region column. For those, SQL Server
returns by default a NULL in the location result column.
custid country region city location
----------- --------------- ------ --------------- -------------------
1 Germany NULL Berlin NULL
2 Mexico NULL México D.F. NULL
3 Mexico NULL México D.F. NULL
4 UK NULL London NULL
5 Sweden NULL Luleå NULL
6 Germany NULL Mannheim NULL
7 France NULL Strasbourg NULL
8 Spain NULL Madrid NULL
9 France NULL Marseille NULL
10 Canada BC Tsawassen Canada,BC,Tsawassen
11 UK NULL London NULL
12 Argentina NULL Buenos Aires NULL
13 Mexico NULL México D.F. NULL
14 Switzerland NULL Bern NULL
15 Brazil SP Sao Paulo Brazil,SP,Sao Paulo
16 UK NULL London NULL
17 Germany NULL Aachen NULL
18 France NULL Nantes NULL
19 UK NULL London NULL
20 Austria NULL Graz NULL
...
(91 row(s) affected)
www.it-ebooks.info
66
Microsoft SQL Server 2012 T-SQL Fundamentals
To treat a NULL as an empty string—or more accurately, to substitute a NULL with an empty
string—you can use the COALESCE function. This function accepts a list of input values and returns
the first that is not NULL. Here’s how you can revise the query from Listing 2-7 to programmatically
substitute NULL marks with empty strings.
SELECT custid, country, region, city,
country + COALESCE( N',' + region, N'') + N',' + city AS location
FROM Sales.Customers;
SQL Server 2012 introduces a new function called CONCAT that accepts a list of inputs for concat-
enation and automatically substitutes NULL marks with empty strings. For example, the expression
CONCAT(‘a’, NULL, ‘b’) returns the string ‘ab’.
Here’s how to use the CONCAT function to concatenate the customer’s location elements, replac-
ing NULL marks with empty strings.
SELECT custid, country, region, city,
CONCAT(country, N',' + region, N',' + city) AS location
FROM Sales.Customers;
Do'stlaringiz bilan baham: |