20761B 08
20761B 08
20761B 08
numorderlines totalsales
------------- ----------
2155 56500.91
Window Functions
CAST syntax:
CAST(<value> AS <datatype>)
CAST CAST(SYSDATETIME()
SELECT example: AS date);
Returnstoan
--attempt error
convert if datatotypes
datetime2 int are
SELECT CAST(SYSDATETIME() AS int);
incompatible:
Msg 529, Level 16, State 2, Line 1
Explicit conversion from data type datetime2 to int is not
allowed.
Converting with CONVERT
PARSE example:
SELECT PARSE('02/12/2012' AS datetime2
USING 'en-US') AS parse_result;
Converting with TRY_PARSE and
TRY_CONVERT
TRY_PARSE and TRY_CONVERT:
Return the results of a data type conversion:
Like PARSE and CONVERT, they convert strings to
date, time and numeric types
Unlike PARSE and CONVERT, they return a NULL if
the conversion fails
TRY_PARSE Example:
SELECT TRY_PARSE(SQLServer' AS datetime2
USING 'en-US') AS try_parse_result;
try_parse_result
----------------
NULL
Demonstration: Using Conversion
Functions
Example:
SELECT ISNUMERIC('SQL') AS isnmumeric_result;
isnmumeric_result
-----------------
0
IIF example:
SELECT productid, unitprice,
IIF(unitprice > 50, 'high','low') AS pricepoint
FROM Production.Products;
Selecting Items from a List with CHOOSE
choose_result
-------------
Confections
Demonstration: Using Logical Functions
ISNULL example:
SELECT custid, city, ISNULL(region, 'N/A') AS region, country
FROM Sales.Customers;
custid city region country
----------- --------------- --------------- ---------------
7 Strasbourg N/A France
9 Marseille N/A France
32 Eugene OR USA
43 Walla Walla WA USA
45 San Francisco CA USA
Using COALESCE to Return Non-NULL
Values
COALESCE returns the first non-NULL value in a
list:
With only two arguments, COALESCE behaves like ISNULL
If all arguments are NULL, COALESCE returns NULL
COALESCE is standards-based
COALESCE example:
SELECT custid, country, region, city,
country + ',' + COALESCE(region, ' ') + ', ' + city as location
FROM Sales.Customers;
emp_id actual_if_different
----------- -------------------
1 110
2 NULL
3 90
4 80
Demonstration: Using Functions to Work
with NULL
Review Question(s)
Best Practice