TSQL Coding Techniques Are You Playing with Fire? Mindy Curnutt TMW Systems / Trimble Navigation
About Me Wife & Mother Busy-Bee Musician Soap Making Baking Crocheting Entrepreneur Event Planning
About Me VP, Information Management, TMW SQL Server MVP SQL Server since 6.5 / 1995 (20 Years) SQLPASS Speaker, 2005, 2012-2015 PASS Program Manager 2015 & 2016 Twitter: @sqlgirl Email: mindycurnutt@hotmail.com
Agenda Non-Set Based Approaches Scalar Functions Implicit Conversions Non Parameterized SQL Parameter Sniffing
Looping Cursors While Loops Scalar Functions For / Next…
Looping While Loops For / Next Do Until Cursors
How to Not Loop? Think COLUMN instead of ROW Change many rows with one statement
Scalar Functions Simplify your code Code Re-Use Great - under certain conditions Under the wrong conditions – can be deadly!
How to Use Scalar Functions Safely? ONLY in Select Clause and with a Small Result Set Do not reference tables Not in Where Clause!
Implicit Conversions Who wants to take the time to research and declare the correct data type? BORING “I tried to think of the most harmless thing. Something I loved from my childhood. Something that could never ever possibly destroy us.” Cursors While Loops For / Next…
How to Avoid Implicit Conversions Correctly define data types Match data types up Do not mix data of different types in tables Know your precision levels Watch the ORM code
Non Parameterized SQL I’ve got a plan. You’ve got a plan too? Hey, look at that, We’ve all got our own SEPARATE PLANS!
How to use Parameterization Do not concatenate SQL parameters as string values Learn how to use the parameter feature of sp_executeSQL
Parameter Sniffing What’s that first value you gave me? Great, I’ll make you the perfect execution plan for that! Next time, we don’t have to waste time figuring out a plan, we can use the one I have right here! Cursors While Loops For / Next…
How Parameter Sniffing can go awry Values within a column have very different distribution Column is naturally increasing at a high rate Statistics are not accurate Statistic sampling is not sufficient
Value Lists IN() CHARINDEX() Convert to a Table Variable and Join
High Performing Value Lists Convert value list into a Table Variable Submit value list as a Table Valued Parameter
Mindy Curnutt VP, Information Management, TMW Systems T H A N K Y O U Mindy Curnutt VP, Information Management, TMW Systems p: 440.721.2819 e: mcurnutt@tmwsystems.com t: @sqlgirl M O V I N G Y O U F O R W A R D