DISTINCT, Aliases, scalar functions and CASE, using JOIN and MERGE; Filtering and sorting data, NULL
values
Introduce data types, data type usage, converting data types, understanding SQL Server function types
Aggregate functions, GROUP BY and HAVING clauses, subqueries; self-contained, correlated, and EXISTS; Views, inline-table
valued functions, and derived tables
| Lunch Break
StoreID
------1234
570
902
1898
710
Sales.SalesOrderDetail;
Sales.SalesOrderDetail;
Sales.SalesOrderDetail;
Keyword
Expression component
SELECT
<select list>
CASE
<value to compare>
WHEN
<value to match>
THEN
<result>
END
N/A
FROM
<table source>
Join Type
Description
Cross
Inner
Outer
Starts with Cartesian product; all rows from designated table preserved,
matching rows from other table retrieved. Additional NULLs inserted as
placeholders.
FROM t1 JOIN t2
ON t1.column = t2.column
SELECT SOH.SalesOrderID,
SOH.OrderDate,
SOD.ProductID,
SOD.UnitPrice,
SOD.OrderQty
FROM Sales.SalesOrderHeader AS SOH
JOIN Sales.SalesOrderDetail AS SOD
ON SOH.SalesOrderID = SOD.SalesOrderID;
SELECT
EMP.EmpID, EMP.LastName,
EMP.JobTitle, EMP.MgrID, MGR.LastName
FROM
HR.Employees AS EMP
INNER JOIN HR.Employees AS MGR
ON EMP.MgrID = MGR.EmpID ;
SELECT
EMP.EmpID, EMP.LastName,
EMP.Title, MGR.MgrID
FROM HumanResources.Employee AS EMP
LEFT OUTER JOIN HumanResources.Employee AS MGR
ON EMP.MgrID = MGR.EmpID;
2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, Office, Azure, System Center, Dynamics and other product names are or may be registered trademarks and/or trademarks in
the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because
Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information
provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
DISTINCT, Aliases, scalar functions and CASE, using JOIN and MERGE; Filtering and sorting data, NULL
values
Introduce data types, data type usage, converting data types, understanding SQL Server function types
Aggregate functions, GROUP BY and HAVING clauses, subqueries; self-contained, correlated, and EXISTS; Views, inline-table
valued functions, and derived tables
| Lunch Break
Exact numeric
Unicode characters
Approximate numeric
Binary strings
Other
Character strings
scale
parameters:
Data type
Range
Storage (bytes)
DECLARE
tinyint @mydecimal
0 toAS
255 DECIMAL(8,2)
smallint
Approximate
Numeric-32,768 to 32,768
int
2^31 (-2,147,483,648) to
2^31-1 (2,147,483,647)
2
4
Data Type
Range
float(n)
Bigint
Depends on value of n, 4 or 8
8
bytes
bit
real
(+/- 9 quintillion)
decimal/numeric
- 10^38 +1 through 10^38 1
float(24)
is the ISO synonym
for float
Storage (bytes)
1
5-17
In
float(n),
money
n is the number
of bytes used to store
of the
-922,337,203,685,477.5808
to the mantissa
8
float number in scientific
notation
922,337,203,685,477.5807
smallmoney
- 214,748.3648 to 214,748.3647
Data Type
Range
Storage (bytes)
binary(n)
1-8000 bytes
n bytes
varbinary(n)
1-8000 bytes
n bytes + 2
varbinary(MAX)
actual length + 2
Data Type
Range
Storage
(bytes)
Remarks
rowversion
Auto-generated
uniqueidentifier
Auto-generated
16
xml
0-2 GB
0-2 GB
cursor
N/A
N/A
hierarchyid
N/A
Depends on
content
Represents position in a
hierarchy
sql_variant
0-8000 bytes
Depends on
content
table
N/A
N/A
PARSE element
Comment
String_value
Data_type
Culture
Range
Storage
CHAR(n),
NCHAR(n)
1-8000 characters
n bytes, padded
2*n bytes, padded
VARCHAR(n), NVARCHAR(n)
1-8000 characters
n+2 bytes
(2*n) +2 bytes
VARCHAR(MAX),
NVARCHAR(MAX)
1-2^31-1 characters
Actual length + 2
Function
Syntax
Remarks
SUBSTRING()
LEFT(), RIGHT()
LEN(), DATALENGTH()
LEN ( string_expression )
DATALENGTH ( expression )
CHARINDEX()
CHARINDEX ( expressionToFind,
expressionToSearch )
REPLACE()
UPPER(), LOWER()
UPPER ( character_expression )
LOWER ( character_expression )
Data Type
Storage (bytes)
Date Range
DATETIME
January 1, 1753 to
December 31, 9999
SMALLDATETIME
DATETIME2
Accuracy
3-1/3 milliseconds
'YYMMDD hh:mm:ss:nnn'
1 minute
'YYMMDD hh:mm:ss:nnn'
6 to 8
January 1, 0001 to
December 31, 9999
100 nanoseconds
DATE
January 1, 0001 to
December 31, 9999
1 day
TIME
3 to 5
DATETIMEOFFSET
8 to 10
January 1, 0001 to
December 31, 9999
Recommended
Entry Format
'YYMMDD
hh:mm:ss.nnnnnn'
'YYYY-MM-DD'
100 nanoseconds
'hh:mm:ss:nnnnnnn'
100 nanoseconds
'YY-MM-DD
hh:mm:ss:nnnnnnn [+|]hh:mm'
Data Type
Language-Neutral Formats
Examples
DATETIME
'YYYYMMDD hh:mm:ss.nnn'
'YYYY-MM-DDThh:mm:ss.nnn'
'YYYYMMDD'
'20120212 12:30:15.123'
'2012-02-12T12:30:15.123'
'20120212'
SMALLDATETIME
'YYYYMMDD hh:mm'
'YYYY-MM-DDThh:mm'
'YYYYMMDD'
'20120212 12:30'
'2012-02-12T12:30'
'20120212'
DATETIME2
'YYYY-MM-DD'
'YYYYMMDD hh:mm:ss.nnnnnnn'
'YYYY-MM-DD hh:mm:ss.nnnnnnn'
'YYYY-MM-DDThh:mm:ss.nnnnnnn'
'YYYYMMDD'
'YYYY-MM-DD'
'20120212 12:30:15.1234567'
'2012-02-12 12:30:15.1234567'
'2012-02-12T12:30:15.1234567'
'20120212'
'2012-02-12'
Syntax
Syntax
Syntax
Return Type
Remarks
Return Type
Remarks
Return
Remarks
DATEADD(datepart,
interval,
date)
Adds
interval
to date,
Type
DATEFROMPARTS(year,
month,
day)
date
datetime
Current
date and
time.
No time
zonereturns
offset.same
datatype as date
DATENAME()
DATENAME(datepart, date)
nvarchar
Use 'year', 'month', 'day' as datepart
EOMONTH()
EOMONTH(start_date,
interval)
Returns
last
day of
month as start date,
DATETIMEFROMPARTS()
DATETIMEFROMPARTS(year,
month,
day,
hour,
datetime
GETUTCDATE()
datetime
Current
date
and
time in
UTC.
optional offset
minute,
seconds, milliseconds)
DATEPART()
DATEPART(datepart,
date)
int
Usewith
'year',
'month', 'day' as datepart
CURRENT_TIMESTAMP()
datetime
Current
date
and
time.
No time zone
offset.
SWITCHOFFSET()
SWITCHOFFSET(datetimeoffset,month, day,Changes
offset
DATETIME2FROMPARTS()
DATETIME2FROMPARTS(year,
hour, time zone
Datetime2
ANSI
standard.
time_zone)
DAY()
DAY(datevalue)minute,
int precision)
seconds, fractions,
SYSDATETIME()
datetime2
Current date and
time. No
time zone
TODATETIMEOFFSET()
TODATETIMEOFFSET(expression,
Converts
intooffset
datetimeoffset
DATETIMEOFFSETFROMPARTS()
DATETIMEOFFSETFROMPARTS(year,
month,
day, datetime2
datetime
MONTH()
MONTH(datevalue)
int
time_zone)
hour, minute, seconds, fractions, hour_offset,
STSUTCDATETIME()
datetime2
Current date and time in UTC.
YEAR()
YEAR(datevalue)minute_offset, precision)
int
SMALLDATETIMEFROMPARTS()
SMALLDATETIMEFROMPARTS(year,
month,
day, hour,
SYSDATETIMEOFFSET()
datetimeoffset
Current date
and time.
Includessmalldatetime
time zone offset
minute)
SELECT DATEADD(day,1,'20120212');
SELECT EOMONTH('20120212');
TIMEFROMPARTS()
time
SELECT CURRENT_TIMESTAMP();
Syntax
Remarks
DATENAME(year,'20120212');
SELECT SYSUTCDATETIME();
SELECT DAY('20120212');
DATEDIFF()
DATEDIFF(datepart, start_date, end_date)
Returns the difference in dateparts
Function
SELECT
ISO_style
--------20120212
Function Category
Description
Scalar
Grouped Aggregate
Window
Rowset
Scalar Function
Categories
SELECT SalesOrderID, YEAR(OrderDate) AS
Configuration
OrderYear
Conversion
FROM Sales.SalesOrderHeader;
Cursor
ProductID
--------749
750
751
752
753
Name
---------------Road-150 Red, 62
Road-150 Red, 44
Road-150 Red, 48
Road-150 Red, 52
Road-150 Red, 56
ListPrice RankByPrice
--------- ----------3578.27
1
3578.27
1
3578.27
1
3578.27
1
3578.27
1
IIF Element
Comments
Boolean_expression
True_value
False_value
CHOOSE Element
Comments
Index
Value_list
2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, Office, Azure, System Center, Dynamics and other product names are or may be registered trademarks and/or trademarks in
the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because
Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information
provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
DISTINCT, Aliases, scalar functions and CASE, using JOIN and MERGE; Filtering and sorting data, NULL
values
Introduce data types, data type usage, converting data types, understanding SQL Server function types
Aggregate functions, GROUP BY and HAVING clauses, subqueries; self-contained, correlated, and EXISTS; Views, inline-table
valued functions, and derived tables
| Lunch Break
Common
SUM
MIN
MAX
AVG
COUNT
COUNT_BIG
Statistical
STDEV
STDEVP
VAR
VARP
Other
CHECKSUM_AGG
GROUPING
GROUPING_ID
SELECT <select_list>
FROM <table_source>
WHERE <search_condition>
GROUP BY <group_by_list>;
Logical Order
Phase
Comments
SELECT
FROM
WHERE
GROUP BY
Creates groups
HAVING
Operates on groups
ORDER BY
Show only customers that have placed more than one order:
SELECT Cust.Customerid, COUNT(*) AS cnt
FROM Sales.Customer AS Cust
JOIN Sales.SalesOrderHeader AS Ord ON Cust.CustomerID =
ORD.CustomerID
GROUP BY Cust.CustomerID
HAVING COUNT(*) > 1;
SELECT <column_list>
FROM (
<derived_table_definition>
) AS <derived_table_alias>;
Have an alias
Have names for all
columns
Have unique names
for all columns
Not use an ORDER BY
clause (without TOP or
OFFSET/FETCH)
Not be referred to
multiple times in the
same query
Use internal or
external aliases for
columns
Refer to parameters
and/or variables
Be nested within other
derived tables
WITH CTE_year AS
(
SELECT YEAR(OrderDate) AS OrderYear, customerID
FROM Sales.SalesOrderHeader
)
SELECT orderyear, COUNT(DISTINCT CustomerID) AS CustCount
FROM CTE_year
GROUP BY OrderYear;
Common
SUM
MIN
MAX
AVG
COUNT
COUNT_BIG
Statistical
STDEV
STDEVP
VAR
VARP
Other
CHECKSUM_AGG
GROUPING
GROUPING_ID
DISTINCT, Aliases, scalar functions and CASE, using JOIN and MERGE; Filtering and sorting data, NULL
values
Introduce data types, data type usage, converting data types, understanding SQL Server function types
Aggregate functions, GROUP BY and HAVING clauses, subqueries; self-contained, correlated, and EXISTS; Views, inline-table
valued functions, and derived tables
| Lunch Break
2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, Office, Azure, System Center, Dynamics and other product names are or may be registered trademarks and/or trademarks in
the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because
Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information
provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
06 | Modifying Data
INSERT, UPDATE, and DELETE statements, use of defaults, constraints, and triggers, OUTPUT
Using T-SQL programming elements, implementing error handling, understanding and implementing transactions
Querying system catalogs and dynamic management views, creating and executing stored procedures, improving SQL
Server query performance
<SELECT query_1>
<set_operator>
<SELECT query_2>
[ORDER BY <sort_list>]
Purchasing
Sales
Purchasing
Sales
INTERSECT
Purchasing
Sales
Sales
Purchasing
1.
2.
SELECT <column_list>
FROM
<left_table> AS <alias>
CROSS/OUTER APPLY
<derived_table_expression or inline_TVF> AS <alias>
OrderDate
-------------------------2007-08-01 00:00:00.000
2007-10-01 00:00:00.000
2006-09-01 00:00:00.000
2007-08-01 00:00:00.000
2006-11-01 00:00:00.000
2007-04-01 00:00:00.000
TotalDue TotalDueByCust
-------- -------------3756.989
9115.1341
2587.8769 9115.1341
2770.2682 9115.1341
2674.0227 7054.1875
3729.364
7054.1875
650.8008 7054.1875
Function
Description
RANK
DENSE_RANK
ROW_NUMBER
NTILE
Function
Description
LAG
LEAD
FIRST_VALUE
LAST_VALUE
Pivoted data
5
4
4
4
5
5
4
5
<SELECT query_1>
<set_operator>
<SELECT query_2>
[ORDER BY <sort_list>]
2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, Office, Azure, System Center, Dynamics and other product names are or may be registered trademarks and/or trademarks in
the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because
Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information
provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
06 | Modifying Data
INSERT, UPDATE, and DELETE statements, use of defaults, constraints, and triggers, OUTPUT
Using T-SQL programming elements, implementing error handling, understanding and implementing transactions
Querying system catalogs and dynamic management views, creating and executing stored procedures, improving SQL
Server query performance
-- Define a sequence
CREATE SEQUENCE dbo.InvoiceSeq AS INT START WITH 5
INCREMENT BY 5;
-- Retrieve next available value from sequence
SELECT NEXT VALUE FOR dbo.InvoiceSeq;
UPDATE Production.UnitMeasure
SET ModifiedDate = (GETDATE())
WHERE UnitMeasureCode = M2
Constraints can be used to control the behavior of SQL Server when data is
added, modified, or deleted. There are five constraints types that you can use:
PRIMARY KEY
FOREIGN KEY
UNIQUE
CHECK
DEFAULT
DML triggers are T-SQL statements used to enforce business rules and
provide data integrity when an INSERT, UPDATE, or DELETE command is
executed
CREATE TRIGGER reminder1 ON Sales.Customer
AFTER INSERT, UPDATE
AS RAISERROR ('Notify Customer Relations', 16, 10);
2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, Office, Azure, System Center, Dynamics and other product names are or may be registered trademarks and/or trademarks in
the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because
Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information
provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
06 | Modifying Data
INSERT, UPDATE, and DELETE statements, use of defaults, constraints, and triggers, OUTPUT
Using T-SQL programming elements, implementing error handling, understanding and implementing transactions
Querying system catalogs and dynamic management views, creating and executing stored procedures, improving SQL
Server query performance
--Valid batch
INSERT INTO Production.UnitMeasure (Name,
UnitMeasureCode, ModifiedDate)
VALUES (N'Square Footage', NF4', GETDATE()),
(N'Square Inches', NI2', GETDATE());
GO
--Invalid batch
INSERT INTO dbo.t1 VALUE(1,2,N'abc');
INSERT INTO dbo.t1 VALUES(2,3,N'def');
GO
Property
Function to Query
Description
Number
ERROR_NUMBER
Message
ERROR_MESSAGE
Severity
ERROR_SEVERITY
Procedure Name
ERROR_PROCEDURE
Line Number
ERROR_LINE
BEGIN TRY
-- Generate a divide-by-zero error.
SELECT 1/0;
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
GO
BEGIN TRY
-- Table does not exist; object name resolution
-- error not caught.
SELECT * FROM IDontExist;
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_MESSAGE() AS ErrorMessage;
END CATCH
Msg 208, Level 16, State 1, Line 4
Invalid object name IDontExist'.
BEGIN TRY
SELECT 100/0 AS 'Problem';
END TRY
BEGIN CATCH
PRINT 'Code inside CATCH is beginning'
PRINT MyError: ' + CAST(ERROR_NUMBER()
AS VARCHAR(255));
THROW;
END CATCH
BEGIN TRY
BEGIN TRANSACTION
INSERT INTO Sales.SalesOrderHeader... --Succeeds
INSERT INTO Sales.SalesOrderDetail... --Fails
COMMIT TRANSACTION -- If no errors, transaction completes
END TRY
BEGIN CATCH
--Inserted rows still exist in Sales.SalesOrderHeader
SELECT ERROR_NUMBER()
ROLLBACK TRANSACTION --Any transaction work undone
END CATCH;
BEGIN TRY
BEGIN TRANSACTION -- marks beginning of transaction
INSERT INTO Sales.SalesOrderHeader... -Completed
INSERT INTO Sales.SalesOrderDetail... -Completed
...
BEGIN TRY
BEGIN TRAN -- marks beginning of transaction
INSERT INTO Sales.SalesOrderHeader...
INSERT INTO Sales.SalesOrderDetail...
COMMIT TRAN -- mark the transaction as complete
END TRY
BEGIN CATCH
SELECT ERROR_NUMBER() --sample error handling
ROLLBACK TRAN
END CATCH;
2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, Office, Azure, System Center, Dynamics and other product names are or may be registered trademarks and/or trademarks in
the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because
Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information
provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
06 | Modifying Data
INSERT, UPDATE, and DELETE statements, use of defaults, constraints, and triggers, OUTPUT
Using T-SQL programming elements, implementing error handling, understanding and implementing transactions
Querying system catalogs and dynamic management views, creating and executing stored procedures, improving SQL
Server query performance
SELECT referencing_schema_name,
referencing_entity_name,
referencing_class_desc
FROM
sys.dm_sql_referencing_entities(
'Sales.SalesOrderHeader', 'OBJECT');
GO
Naming pattern
Description
db
Database-related information
exec
io
I/O statistics
os
tran
Transaction-related information
Name
Description
sp_databases
sp_tables
sp_columns
2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, Office, Azure, System Center, Dynamics and other product names are or may be registered trademarks and/or trademarks in
the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because
Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information
provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.