Preparing SQL Statements

Prepared Query 是提供给Ado.net等工具的一种查询方式,能够复用执行计划,Prepared Query 不是TSQL 语言的功能。

The SQL Server relational engine introduces full support for preparing SQL statements before they are executed. If an application has to execute an SQL statement several times, it can use the database API to do the following:

  • Prepare the statement once. This compiles the SQL statement into an execution plan.
  • Execute the precompiled execution plan every time it has to execute the statement. This prevents having to recompile the SQL statement on each execution after the first time.

    Preparing and executing statements is controlled by API functions and methods. It is not part of the Transact-SQL language. The prepare/execute model of executing SQL statements is supported by the SQL Server Native Client OLE DB Provider and the SQL Server Native Client ODBC driver. On a prepare request, either the provider or the driver sends the statement to SQL Server with a request to prepare the statement. SQL Server compiles an execution plan and returns a handle for that plan to the provider or driver. On an execute request, either the provider or the driver sends the server a request to execute the plan that is associated with the handle.

Prepared statements cannot be used to create temporary objects on SQL Server. Prepared statements cannot reference system stored procedures that create temporary objects, such as temporary tables. These procedures must be executed directly.

Excess use of the prepare/execute model can degrade performance. If a statement is executed only once, a direct execution requires only one network round-trip to the server. Preparing and executing an SQL statement executed only one time

using (SqlCommand command = connection.CreateCommand())
{
    command.CommandText = "SELECT * FROM users WHERE USERNAME = @username AND ROOM = @room";

    command.Parameters.AddWithValue("@username", username);
    command.Parameters.AddWithValue("@room", room);

    using (SqlDataReader dataReader = command.ExecuteReader())
    {
        // ...
    }
}

In database management systems, a prepared statement or parameterized statement is a feature used to execute the same or similar database statements repeatedly with high efficiency. Typically used with SQL statements such as queries or updates, the prepared statement takes the form of a template into which certain constant values are substituted during each execution.

The typical workflow of using a prepared statement is as follows:

  1. Prepare: The statement template is created by the application and sent to the database management system (DBMS). Certain values are left unspecified, called parameters, placeholders or bind variables (labelled "?" below):

    • INSERT INTO PRODUCT (name, price) VALUES (?, ?)
  2. The DBMS parses, compiles, and performs query optimization on the statement template, and stores the result without executing it.
  3. Execute: At a later time, the application supplies (or binds) values for the parameters, and the DBMS executes the statement (possibly returning a result). The application may execute the statement as many times as it wants with different values. In this example, it might supply ‘Bread‘ for the first parameter and ‘1.00‘ for the second parameter.

As compared to executing SQL statements directly, prepared statements offer two main advantages:[1]

  • The overhead of compiling and optimizing the statement is incurred only once, although the statement is executed multiple times. Not all optimization can be performed at the time the prepared statement is compiled, for two reasons: the best plan may depend on the specific values of the parameters, and the best plan may change as tables and indexes change over time.[2]
  • Prepared statements are resilient against SQL injection, because parameter values, which are transmitted later using a different protocol, need not be correctly escaped. If the original statement template is not derived from external input, SQL injection cannot occur.

On the other hand, if a query is executed only once, server-side prepared statements can be slower because of the additional round-trip to the server.[3] Implementation limitations may also lead to performance penalties: some versions of MySQL did not cache results of prepared queries,[4] and some DBMSs such as PostgreSQL do not perform additional query optimization during execution.[5][6]

A stored procedure, which is also precompiled and stored on the server for later execution, has similar advantages. Unlike a stored procedure, a prepared statement is not normally written in a procedural language and cannot use or modify variables or use control flow structures, relying instead on the declarative database query language. Due to their simplicity and client-side emulation, prepared statements are more portable across vendors.

参考文档:

https://technet.microsoft.com/en-us/library/ms175528(v=sql.105).aspx

https://en.wikipedia.org/wiki/Prepared_statement

时间: 2024-08-04 09:40:34

Preparing SQL Statements的相关文章

Access text files using SQL statements by DB Query Analyzer

Access text files using SQL statements by DB Query Analyzer Ma Gen feng (Guangdong Unitoll Services incorporated, Guangzhou510300) Abstract   Is it a dream that you can access text files using SQL statements? But now, it is true that DB Query Analyze

Save results to different files when executing multi SQL statements in DB Query Analyzer 7.01

1 About DB Query Analyzer DB Query Analyzer is presented by Master Genfeng,Ma from Chinese Mainland. It has English version named 'DB Query Analyzer'and Simplified Chinese version named   . DB Query Analyzer is one of the few excellent Client Tools i

Migrating Oracle on UNIX to SQL Server on Windows

Appendices Published: April 27, 2005 On This Page Appendix A: SQL Server for Oracle Professionals Appendix B: Getting the Best Out of SQL Server 2000 and Windows Appendix C: Baselining Appendix D: Installing Common Drivers and Applications Installing

sql monitor生成不了报告& FFS hint不生效两个问题思考

事情的发生就是这么偶然,一步步的深入才能汲取到更深入的知识~~ -------------------START-------------------------------------------   来了一个query running longer than 4hours的邮件,来看看里面有哪些sql: SID    SERIAL#    INST_ID SQL_ID        Run_in_sec OS_user     MACHINE       SQL_TEXT         

LINQ To SQL 语法及实例大全

LINQ to SQL语句(1)之Where Where操作 适用场景:实现过滤,查询等功能. 说明:与SQL命令中的Where作用相似,都是起到范围限定也就是过滤作用的,而判断条件就是它后面所接的子句. Where操作包括3种形式,分别为简单形式.关系条件形式.First()形式.下面分别用实例举例下: 1.简单形式: 例如:使用where筛选在伦敦的客户 var q = from c in db.Customers where c.City == "London" select c

Oracle 动态sql 实现方式

1 /******************************************************************* 2 Sample Program 10: Dynamic SQL Method 4 3 4 This program connects you to ORACLE using your username and 5 password, then prompts you for a SQL statement. You can enter 6 any leg

SQL Server 高性能写入的一些经验总结

转自:http://www.jb51.net/article/31162.htm 本篇博文将针对一些常用的数据库性能调休方法进行介绍,而且,为了编写高效的SQL代码,我们需要掌握一些基本代码优化的技巧,所以,我们将从一些基本优化技巧进行介绍 1.1.1 摘要 在开发过程中,我们不时会遇到系统性能瓶颈问题,而引起这一问题原因可以很多,有可能是代码不够高效.有可能是硬件或网络问题,也有可能是数据库设计的问题. 本篇博文将针对一些常用的数据库性能调休方法进行介绍,而且,为了编写高效的SQL代码,我们需

Datatypes translation between Oracle and SQL Server

Datatypes translation between Oracle and SQL Server part 1: character, binary strings Datatypes translation is one of the most important things you need to consider when migrate your application from one database to the other. This is an article in t

SQL SERVER几种数据迁移/导出导入的实践

SQLServer提供了多种数据导出导入的工具和方法,在此,分享我实践的经验(只涉及数据库与Excel.数据库与文本文件.数据库与数据库之间的导出导入). (一)数据库与Excel 方法1: 使用数据库客户端(SSMS)的界面工具.右键选择要导出数据的数据库,选择“任务”——“导出数据”,下图1,按照向导一步一步操作即可.而导入则相反,导入时,SQLServer会默认创建一张新表,字段名也默认跟导入的Excel标题一样,并且会默认字段数据类型等.当然在可以在向导进行修改.需要注意的是如果标题不是