使用语句参数Using Statement Parameters

适用对象:yesSQL ServeryesAzure SQL 数据库yesAzure SQL 数据仓库yes并行数据仓库APPLIES TO: yesSQL Server yesAzure SQL Database yesAzure SQL Data Warehouse yesParallel Data Warehouse

参数在 SQL 语句中是一种变量,它使 ODBC 应用程序能够:A parameter is a variable in an SQL statement that can enable an ODBC application to:

  • 有效地为表中的列提供值。Efficiently provide values for columns in a table.

  • 在构造查询条件时增强用户交互。Enhance user interaction in constructing query criteria.

  • 管理文本ntext,并图像数据和SQL ServerSQL Server-特定的 C 数据类型。Manage text, ntext, and image data and SQL ServerSQL Server-specific C data types.

例如,部件表中包含名为的列PartID说明,以及价格For example, a Parts table has columns named PartID, Description, and Price. 若要添加不带参数的部分,需要构造 SQL 语句,例如:To add a part without parameters requires constructing an SQL statement such as:

INSERT INTO Parts (PartID, Description, Price) VALUES (2100, 'Drive shaft', 50.00)  

尽管使用已知的值集插入一行时可接受此语句,但要求应用程序插入多行时使用此语句会很不适合。Although this statement is acceptable for inserting one row with a known set of values, it is awkward when an application is required to insert several rows. ODBC 可通过使应用程序将 SQL 语句中的任何数据值替换为参数标记来解决此问题。ODBC addresses this by letting an application to replace any data value in an SQL statement by a parameter maker. 这种参数标记由问号 (?) 表示。This is denoted by a question mark (?). 在下面的示例中,三个数据值被替换为参数标记:In the following example, three data values are replaced with parameter markers:

INSERT INTO Parts (PartID, Description, Price) VALUES (?, ?, ?)  

参数标记然后被绑定到应用程序变量。The parameter markers are then bound to application variables. 若要插入新行,应用程序只需设置变量的值并执行此语句。To insert a new row, the application has only to set the values of the variables and execute the statement. 然后,驱动程序检索变量的当前值并将其发送至数据源。The driver then retrieves the current values of the variables and sends them to the data source. 如果多次执行此语句,则应用程序可通过准备此语句使该进程更加有效。If the statement is executed multiple times, the application can make the process even more efficient by preparing the statement.

每个参数标记均按从左到右的顺序由其分配至参数的序号引用。Each parameter marker is referenced by its ordinal number assigned to the parameters from left to right. 在 SQL 语句中,最左侧的参数标记的序号值为 1;下一个的序号为 2,以此类推。The leftmost parameter marker in an SQL statement has an ordinal value of 1; the next one is ordinal 2, and so on.

本节内容In This Section

请参阅See Also

执行查询(ODBC)Executing Queries (ODBC)