-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path02_Functions and expressions.sql
92 lines (79 loc) · 1.61 KB
/
02_Functions and expressions.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*
T-SQL Functions and Expressions:
Basic addition and mathematical expressions
String manipulation functions and expressions
Working with Date functions
Dateadd
Datediff
Year / Month
*/
-- Mathematical Expressions
SELECT
UnitPrice,
UnitPrice + 10 AS Plus10,
UnitPrice * 2 AS Doubled,
UnitPrice * OrderQty AS LineTotalCalc,
LineTotal
FROM
Sales.SalesOrderDetail;
-- String manipulation Expressions
SELECT
Firstname,
LEFT(FirstName, 3) AS First3,
RIGHT(FirstName, 3) AS Last3
FROM
Person.Person
SELECT
Firstname,
UPPER(FirstName) AS UpperFirst,
LOWER(FirstName) AS LowerFirst
FROM
Person.Person
SELECT
Firstname,
REPLACE(FirstName, 'a', '*') AS ReplaceA
FROM
Person.Person
SELECT
LEN(FirstName) AS LengthOfName,
FirstName
FROM
Person.Person
-- Date Functions
SELECT GETDATE() AS SystemTime
SELECT
GETDATE() SystemTime,
DATEPART(YEAR, GETDATE()) AS SystemYear,
DATEPART(MONTH, GETDATE()) AS SystemMonth;
SELECT
GETDATE() SystemTime,
YEAR(GETDATE()) AS SystemYear,
MONTH(GETDATE()) AS SystemMonth;
SELECT
OrderDate,
YEAR(OrderDate) AS OrderYear,
MONTH(OrderDate) AS OrderMonth
FROM
Sales.SalesOrderHeader
ORDER BY
OrderMonth
-- DATEADD
SELECT
OrderDate,
DATEADD(YEAR, -1, OrderDate) AS PreviousYear
FROM
Sales.SalesOrderHeader
-- DATEDIFF
SELECT
OrderDate,
DATEDIFF(DAY, OrderDate, ShipDate) AS DaysToShip
FROM
Sales.SalesOrderHeader
-- DATEDIFF
SELECT
OrderDate,
DATEDIFF(MONTH, OrderDate, GETDATE()) AS MonthsSinceOrder
FROM
Sales.SalesOrderHeader
ORDER BY
MonthsSinceOrder