Querying Microsoft SQL Server 2012
boB Taylor MCA, MCM, MCSD, MCSE, MCT
Principal Consultant - Premier DeveloperEmail: [email protected]: @sqlboBTBlog: http://blogs.msdn.com/bobtaylor
YOU KNOW SQL SERVER 2012How do you become certified?
Identify Certification GoalFind GapsFill GapsTake Exam
Microsoft Certification
For YouIncreased confidence in your abilities at workEnhanced product knowledgeLearn about certification to educate your coworkers and bosses
For Your CareerMakes a great commitmentShows drive and initiativeTangible way to demonstrate mastery of a productSets you apart from your peers at review timeRecognition inside and outside of MicrosoftCompletely achievable at TechEd
Changes to Certifications and Exams
Deeper Skill Set
Certification Requirement
Broader Skill Set
Recertification
Relevance Rigor
MCSE and MCSD Certifications
Web Applications Windows Store Apps
Server Infrastructure Desktop Infrastructure
Business Intelligence Data Platform
Private Cloud
Increased RigorReflection of the real worldLearn more, validate moreSolutions are more complex, questions must reflect thatBest way to measure candidates know what they know
New item typesFewer multiple choiceCase studies
Scenario basedSee big picture and make decisions
Innovative item types
Exam Tips
Exam Basics40-60 questions1-4 hours to complete examCan review questions
Cannot move between case studies700 is passing700 is not 70%
Exam ScoringEach exam has a "cut score"Each question is worth one pointNo partial creditNo points deducted for wrong answers
How to interpret questions
One or Multiple Correct Answers
Goal Statement
Business ProblemAll questions have a consistent anatomy
Multiple Distracters
Questions are not intended to trick you
Identify Your Certification Goals
MCSA: SQL Server 2012Certification Requirements
Exam 70-461:Querying Microsoft SQL Server 2012
MCSA: SQL Server 2012
Exam 70-462:Administering Microsoft SQL Server 2012 Databases
Exam 70-463:Implementing a Data Warehouse
with Microsoft SQL Server 2012
MCSE: Data PlatformCertification Requirements
MCSA: SQL Server 2012
MCSE: Data Platform
Exam 70-464:Developing
Microsoft SQL Server 2012 Databases
Exam 70-465:Designing Database
Solutions for SQL Server 2012
FIND KNOWLEDGE GAPS
Exam 70-461 GuideSkills Measured
Functional groups and individual topicsRelative weighting of functional groupsLinks to more information about functional topics
Preparation Options
Check the Exam Guide
70-461 Exam OutlineObjective %
Create Database Objects 24%
Work with Data 27%
Modify Data 24%
Troubleshoot and Optimize Queries 25%
Details of each area
FILL KNOWLEDGE GAPS
Topics Outline
Create Database ObjectsQuerying DataModifying DataOptimizing Queries
Topics Outline
Create Database ObjectsQuerying DataModifying DataOptimizing Queries
Notable Data Types
XMLSpatial
GeometryGeography
DateDateTimeDateTime2DateTimeOffset
Constraints
CheckPrimary KeyForeign KeyUniqueDefault
[ColumnDefinition] ConstraintName TYPE Options
DML Triggers
Update tables to maintain integrityPerform complex checksAuditingTypes
Instead ofAfter
CREATE TRIGGER ProductCategory_InsertON Production.ProductCategoryAFTER INSERTASBEGIN
SET NOCOUNT ONINSERT INTO ProductCategoryLog
(ProductCategoryID, Name, CreationDate)
SELECT INSERTED.ProductCategoryID
, INSERTED.Name, GETDATE()
FROM INSERTEDEND
Note: Always part of the current transaction
View Restrictions
1024 columnsSingle queryRestricted data modificationsNo top (without order by)
View Options
SchemabindingEncryptionView MetadataCheck
QuestionYou are a database developer. One of the requirements is to create searchable maps of floor plans to allow customers to determine where items are stored. What data type should use?A.GeometryB.VarbinaryC.BigIntD.Geography
Answer
You are a database developer. One of the requirements is to create searchable maps of floor plans to allow customers to determine where items are stored. What data type should use?A.GeometryB.VarbinaryC.BigIntD.Geography
Takeaway: Geometry for flat surfaces
Topics Outline
Create Database ObjectsQuerying DataModifying DataOptimizing Queries
SQL 2012 Functions
TRY_CONVERT(type, value)PARSE(value AS type USING culture)
TRY_PARSE also available
FORMAT(value, format, culture)IIF(boolean, True, False)
Ranking Options
RankDense rankNtileRow number
Joins
InnerOuterFullCross
Apply Operators
Join to a functionCross Apply
“Inner Join”
Outer Apply“Outer Join”
Common table expresssion (CTE)
WITH CustomersWithOrders(CustomerID) AS (SELECT CustomerID FROM Sales.Customer INTERSECT SELECT CustomerID FROM Sales.SalesOrderHeader)SELECT cwo.CustomerID, c.FirstName, c.LastName, c.EmailAddressFROM CustomersWithOrders cwo INNER JOIN Sales.Customer c ON cwo.CustomerID = c.CustomerID;
Handling Null Values
Null != NullUse Column IS NULL or Column IS NOT NULL
CaseISNULLCOALESCE
PivotWITH SalesData AS (SELECT st.Name AS TerritoryName, soh.SubTotal AS SalesAmount, Year(soh.OrderDate) AS SalesYear FROM Sales.SalesTerritory st INNER JOIN Sales.SalesOrderHeader soh ON st.TerritoryID = soh.TerritoryID)SELECT *FROM SalesData PIVOT (Sum(SalesAmount) FOR SalesYear IN ([2001], [2002], [2003], [2004])) AS PvtORDER BY TerritoryName;
Rollup and CubeSELECT Region
, Country, Category, SUM(TotalSold) AS TotalSales
FROM Sales.SalesInformation
GROUP BY ROLLUP(Region, Country, Category); -- One pass-- ORGROUP BY ROLLUP(Region, Country, Category); -- Every Pass
Grouping SetsSELECT Region
, Country, Category, SUM(TotalSold) AS TotalSales
FROM Sales.SalesInformationGROUP BY GROUPING SETS (
(Region, Country, Category), (Country, Category), (Region, Category), (Category)
);
FOR XML – RAWSELECT FirstName
, LastNameFROM Person.ContactFOR XML RAW('Contact')
, ROOT('Contacts'), ELEMENTS
<Contacts> <Contact> <FirstName>...</FirstName> <LastName>...</LastName> </Contact></Contacts>
FOR XML – AUTOSELECT FirstName
, LastNameFROM Person.Contact AS ContactFOR XML AUTO
, ROOT('Contacts'), ELEMENTS
<Contacts> <Contact> <FirstName>...</FirstName> <LastName>...</LastName> </Contact></Contacts>
FOR XML - EXPLICITSELECT 1 AS Tag
, NULL AS Parent , ProductID AS [Product!1! ID], Name AS [Product!1!Name!ELEMENT]
FROM SalesLT.ProductWHERE ProductCategoryID = 5FOR XML EXPLICIT
, ROOT('Products');
<Products> <Product ID="..."> <Name>...</Name> </Product></Products>
XML - Retrieving Elements and Attributes (PATH)SELECT ProductID AS [@ID]
, NameFROM SalesLT.ProductWHERE ProductCategoryID = 5FOR XML PATH('Product')
, ROOT('Products');<Products> <Product ID="..."> <Name>...</Name> </Product></Products>
Fetch and OffsetSELECT FirstName
, LastNameFROM HumanResources.EmployeeORDER BY LastName
OFFSET @StartingRowNumber ROWSFETCH NEXT @Rows ROWS ONLY;
QuestionYou have a query that returns data using the cube option. One of the columns contains null data. You need to identify when a field is being used to display aggregated data. What should you include in your query?A.CASEB. ISNULLC.GROUPING_IDD.COALESCE
QuestionYou have a query that returns data using the cube option. One of the columns contains null data. You need to identify when a field is being used to display aggregated data. What should you include in your query?A.CASEB. ISNULLC.GROUPING_IDD.COALESCE
Topics Outline
Create Database ObjectsQuerying DataModifying DataOptimizing Queries
Stored Procedure Options
EncryptionExecute As
OwnerSelfCaller'user'
Recompile
Update StatementUPDATE Production.ProductSET ListPrice = tp.ListPriceOUTPUT DELETED.Name
, INSERTED.ListPrice AS NewPrice, DELETED.ListPrice AS OldPrice
FROM Production.Product pINNER JOIN #TempProducts tp
ON p.ProductID = tp.ProductID
Merge Statement
Merge data from one table with anotherComponents
TargetSourceOn statement
“Join” for Target and SourceMatchedNot matchedOutput
Merge SyntaxMERGE Target AS TUSING Source AS S
ON (T.EmployeeID = S.EmployeeID) WHEN NOT MATCHED BY TARGET -- INSERT THEN INSERT(EmployeeID, EmployeeName)
VALUES(S.EmployeeID, S.EmployeeName)WHEN MATCHED -- UPDATE THEN UPDATE SET T.EmployeeName = S.EmployeeNameOUTPUT $action AS [Action]
, inserted.EmployeeID AS [NewID], inserted.EmployeeName AS [NewName], deleted.EmployeeID AS [OldID], deleted.EmployeeName AS [OldName];
QuestionYou need to create a stored procedure to update rows in a table named Customers. You have permissions to alter rows in Customers. You need to ensure all callers of this stored procedure will be able to perform the operation even if they don’t have permissions access to the table. Which option should you use when creating the stored procedure?A. ENCRYPTIONB. EXECUTE AS CALLERC. EXECUTE AS SELFD. RECOMPILE
QuestionYou need to create a stored procedure to update rows in a table named Customers. You have permissions to alter rows in Customers. You need to ensure all callers of this stored procedure will be able to perform the operation even if they don’t have permissions access to the table. Which option should you use when creating the stored procedure?A. ENCRYPTIONB. EXECUTE AS CALLERC. EXECUTE AS SELFD. RECOMPILE
Topics Outline
Create Database ObjectsQuerying DataModifying DataOptimizing Queries
Join Types
Nested LoopSmall joins
Merge JoinsLarge, sorted data
Hash JoinLarge, unsorted data
Transactions
BeginCommitRollbackSave
Isolation LevelsRead Uncommitted
No locks
Read CommittedSelect only locks during execution
Repeatable ReadSelect locks data that has been returned
SerializableSelect locks the range
May incur a table lock
Snapshot Isolation
Uses versioningEveryone gets a sandbox
Additional TempDB overheadMust be enabled at the database levelREAD_COMMITTED_SNAPSHOT
Converts read committed to snapshot
Try/CatchBEGIN TRY
BEGIN TRANSACTION-- Perform Work, assuming successCOMMIT TRANSACTION
END TRYBEGIN CATCH
ROLLBACK TRANSACTION
PRINT ERROR_MESSAGE()PRINT ERROR_NUMBER()PRINT ERROR_LINE()
END CATCH
Cursors
Row based logicGenerally slows performance
Steps to use a cursorDeclare cursorOpen cursorFetch dataCreate loopUse dataClose cursorDeallocate cursor
Query HintUsed to suggest how optimizer should execute query
Table HintUsed to suggest how optimizer should access a table
Using Hints
SELECT * FROM Person.AddressWHERE City = @city_name AND PostalCode = @postal_codeOPTION (OPTIMIZE FOR (@city_name = 'Seattle', @postal_code UNKNOWN));
UPDATE Production.Product WITH (TABLOCK) SET ListPrice = ListPrice * 1.10WHERE ProductNumber LIKE 'BK-%';
SCHEDULE AND TAKE THE EXAM
Exam Tips• Set a date• Set small goals• Sleep well
Before the Exam
• Don’t panic• Keep an eye on time• Don’t spend too long on one question
During the Exam
• Eliminate wrong answers• Mark the question for review• Guess
Tough Question
Resources
Register for the examwww.prometric.com
Prepare for the examExam 70-461 Exam Preparation
Microsoft Official Courseware10774A – Querying Microsoft SQL Server 2012
Microsoft PressTraining Kit (Exam 70-461) Querying Microsoft SQL Server 2012Microsoft SQL Server 2012 T-SQL Fundamentals
Resources
Learning
Microsoft Certification & Training Resources
www.microsoft.com/learning
msdn
Resources for Developers
http://microsoft.com/msdn
TechNet
Resources for IT Professionals
http://microsoft.com/technet
Sessions on Demand
http://channel9.msdn.com/Events/TechEd
Complete an evaluation and enter to win!
Evaluate this session
Scan this QR code to evaluate this session.
Related contentLabs DBI-H305 What's New for T-SQL in Microsoft SQL Server 2012
Related Certification Exam 70-462 Administering Microsoft SQL Server 2012 Databases
Find Me Later At Ask The Experts
or Exam Prep for Exam 70-462
© 2014 Microsoft Corporation. All rights reserved. Microsoft, Windows, 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.
Top Related