Dynamic SQL Writing Efficient Queries on the Fly ED POLLACK AUTOTASK CORPORATION DATABASE OPTIMIZATION ENGINEER.

Slides:



Advertisements
Similar presentations
Understand Database Security Concepts
Advertisements

LCT2506 Internet 2 Further SQL Stored Procedures.
A Guide to SQL, Seventh Edition. Objectives Embed SQL commands in PL/SQL programs Retrieve single rows using embedded SQL Update a table using embedded.
Chapter 7 Managing Data Sources. ASP.NET 2.0, Third Edition2.
Handling Security Threats in Kentico CMS Karol Jarkovsky Sr. Solution Architect Kentico Software
Sql Server Advanced Features MIS 424 Professor Sandvig.
Database Design for DNN Developers Sebastian Leupold.
Advanced Excel for Finance Professionals A self study material from South Asian Management Technologies Foundation.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 10 Database Performance Tuning and Query Optimization.
About Dynamic Sites (Front End / Back End Implementations) by Janssen & Associates Affordable Website Solutions for Individuals and Small Businesses.
OracleAS Reports Services. Problem Statement To simplify the process of managing, creating and execution of Oracle Reports.
9 Chapter Nine Compiled Web Server Programs. 9 Chapter Objectives Learn about Common Gateway Interface (CGI) Create CGI programs that generate dynamic.
Tom Castiglia Hershey Technologies
Dinamic SQL & Cursor. Why Dinamic SQL ? Sometimes there is a need to dynamically create a SQL statement on the fly and then run that command. This can.
Module 7 Reading SQL Server® 2008 R2 Execution Plans.
Stored Procedures, Transactions, and Error-Handling
Module 9 Designing and Implementing Stored Procedures.
PowerBuilder Online Courses - by Prasad Bodepudi
Discovering Computers Fundamentals Fifth Edition Chapter 9 Database Management.
Database Unit Test MSSQL 2008 & VS 2010 Aung Kyaw Myo.
Oracle Data Integrator Procedures, Advanced Workflows.
Copyright © Curt Hill Stored Procedures In Transact-SQL.
Database Design and Management CPTG /23/2015Chapter 12 of 38 Functions of a Database Store data Store data School: student records, class schedules,
SQL Injection Jason Dunn. SQL Overview Structured Query Language For use with Databases Purpose is to retrieve information Main Statements Select Insert.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
10 | Programming with Transact-SQL Graeme Malcolm | Senior Content Developer, Microsoft Geoff Allix | Principal Technologist, Content Master.
Chapter 15 Introduction to PL/SQL. Chapter Objectives  Explain the benefits of using PL/SQL blocks versus several SQL statements  Identify the sections.
Guide to Oracle 10g ITBIS373 Database Development Lecture 4a - Chapter 4: Using SQL Queries to Insert, Update, Delete, and View Data.
SQL Fundamentals  SQL: Structured Query Language is a simple and powerful language used to create, access, and manipulate data and structure in the database.
Chapter 9: Advanced SQL and PL/SQL Guide to Oracle 10g.
A Guide to SQL, Eighth Edition Chapter Eight SQL Functions and Procedures.
Database Security Cmpe 226 Fall 2015 By Akanksha Jain Jerry Mengyuan Zheng.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Chapter 5 : Integrity And Security  Domain Constraints  Referential Integrity  Security  Triggers  Authorization  Authorization in SQL  Views 
NSF DUE ; Wen M. Andrews J. Sargeant Reynolds Community College Richmond, Virginia.
Learningcomputer.com SQL Server 2008 –Views, Functions and Stored Procedures.
Stored Procedure Optimization Preventing SP Time Out Delay Deadlocking More DiskReads By: Nix.
Meta Data Cardinality Explored CSSQLUG User Group - June 2009.
Quick Test Professional 9.2. Testing Process Preparing to Record Recording Enhancing a Test Debugging Running the Test and Analyzing the Results Reporting.
Stored Procedures / Session 4/ 1 of 41 Session 4 Module 7: Introducing stored procedures Module 8: More about stored procedures.
SQL Query Analyzer. Graphical tool that allows you to:  Create queries and other SQL scripts and execute them against SQL Server databases. (Query window)
Text TCS INTERNAL Oracle PL/SQL – Introduction. TCS INTERNAL PL SQL Introduction PLSQL means Procedural Language extension of SQL. PLSQL is a database.
Relational Database Systems Bartosz Zagorowicz. Flat Databases  Originally databases were flat.  All information was stored in a long text file, called.
Module 9: Using Advanced Techniques. Considerations for Querying Data Working with Data Types Cursors and Set-Based Queries Dynamic SQL Maintaining Query.
SQL Triggers, Functions & Stored Procedures Programming Operations.
Create Stored Procedures and Functions Database Management Fundamentals LESSON 2.4.
Diving into Query Execution Plans ED POLLACK AUTOTASK CORPORATION DATABASE OPTIMIZATION ENGINEER.
Some of the utilities associated with the development of programs. These program development tools allow users to write and construct programs that the.
1 c6212 Advanced Database and Client Server MS SQL Server 2000 Stored Procedures and Parameters What ? Why ? How ?
University of Kansas Department of Electrical Engineering and Computer Science Dr. Susan Gauch April 21, 2005 I T T C Introduction to Web Technologies.
Web Database Programming Using PHP
Creating Database Objects
A Guide to SQL, Seventh Edition
Query Optimization Techniques
Dynamic SQL Writing Efficient Queries on the Fly
Stored Procedures.
SQL and SQL*Plus Interaction
Stored Procedures – Facts and Myths
Web Database Programming Using PHP
Dynamic SQL: Writing Efficient Queries on the Fly
Dynamic SQL Writing Efficient Queries on the Fly
Microsoft Access Illustrated
Database Performance Tuning and Query Optimization
Query Optimization Techniques
Dynamic SQL: Writing Efficient Queries on the Fly
Using Table Expressions
Chapter 11 Database Performance Tuning and Query Optimization
SQL Server Query Design and Optimization Recommendations
Query Optimization Techniques
Creating Database Objects
Presentation transcript:

Dynamic SQL Writing Efficient Queries on the Fly ED POLLACK AUTOTASK CORPORATION DATABASE OPTIMIZATION ENGINEER

What is Dynamic SQL? Build up a TSQL statement as a character string. Can incorporate unknowns into the SQL statement: variables, parameters, and table data. Statements can be simple and executed all at once, or built up over the course of a stored proc, in order to handle more complex logic. String manipulation functions can be used to facilitate creating the command string. Quick SQL Example: Dynamic SQL basics.

Advantages of Dynamic SQL Optional or custom searches. Dynamic WHERE, GROUP BY, HAVING, TOP X, ORDER BY, windowing functions, etc… Can greatly speed up complex queries where, at any given time, only a small amount of the SQL is needed. Generate large or complex SQL statements quickly and/or automatically. Execute TSQL on other databases or servers.

Dynamic SQL’s Weaknesses Character strings with apostrophes MUST always be managed correctly (SQL injection) Dynamic SQL can become very complex, difficult to read, hard to maintain and to debug. Permissions are different than with standard SQL. Unexpected results from unexpected input. Dynamic SQL (within quotes) always compiles successfully, but could error on execution. Cannot use dynamic SQL in functions.

Basic Tips for Writing Better Dynamic SQL Document thoroughly!!! Debugging: Use PRINT statements liberally to preview SQL text Test thoroughly all use cases, especially “dumb” input For complex procs, consider parameter Write dynamic SQL text just like you would regular SQL, with similar spacing and indenting. Always check spacing! NVARCHAR vs. VARCHAR (use the right one!) SQL Example: Good dynamic SQL Style

Scope Each dynamic SQL statement occurs in its own local scope! Variables & objects declared in your dynamic SQL statement will not be available elsewhere in your stored proc, or in other dynamic SQL statements. # temp tables will be unavailable outside of a dynamic SQL statement. ## temp tables can be created in dynamic SQL & used anywhere (beware security/dupes/misuse)

Efficiently Generating Lists Dynamic SQL can be used to quickly build lists--- either from variable inputs, or from columns of data in target tables. SQL Example: Efficiently Generating Lists From Table Data

sp_executesql System procedure that allows SQL text to be efficiently executed. Must use NVARCHAR for command string. Parameters can be passed in. Output parameters can be specified so that data can be retrieved from the dynamic SQL. Allows for execution plan reuse (if desired). SQL Example: sp_executesql

Parameter Sniffing Using sp_executesql will allow for plan reuse and force parameter sniffing. Using EXECUTE/EXEC will cause the statement to be executed completely dynamically. Queries are cached based on their EXACT text. A stored proc or sp_executesql allows their contents to be cached, with the parameters handled separately. Parameter sniffing is generally a good feature. It is how SQL Server reuses execution plans. In some scenarios, we may want to change this, but this will typically be rare.

Parameter Sniffing: SQL Example

SQL Injection SQL Example: SQL Injection Converting quotes into double-quotes is a common solution, but not necessarily good enough! Ensure security is limited enough to not allow purposeful (or accidental) access. This counts for user SQL accounts, but also for web logins or process accounts. Use sp_executesql for all searches w/ user input. Never expose error messages to the end user! Use QUOTENAME() for database objects. Use dbo (or schema name) with all object names.

Permissions & Security Dynamic SQL does not benefit from ownership chaining! Ensure the user running dynamic SQL has the correct permissions. AS USER = ‘Ed’ AS LOGIN = ‘MYLAPTOP\Ed’ Beware disk & OS permissions when using xp_cmdshell or any other OS level commands.

Saving Output You can insert the results of a dynamic SQL select into a temp table or table variable. This can be very useful in statements where the column list is known, but the contents can vary greatly. Using the OUTPUT keyword on a parameter, you can output data from a dynamic SQL command directly to the parameter. SQL Example: Saving Dynamic SQL Output

Bonus: The Crazy Dynamic Pivot PIVOT can allow a row set to be flipped into column headers… …But the column names must be predefined! Dynamic SQL allows for an ad-hoc column structure when you want data to determine this, and not a static list. SQL Example: The Crazy Dynamic Pivot

Conclusion Dynamic SQL is very versatile and powerful Only use it when appropriate Dynamic SQL generating dynamic SQL? Always cleanse inputs Always verify security & access to objects Be a neat freak & document thoroughly Also, come to SQL Saturday Albany! How to find SQL Server Central Facebook