在单个请求中提交多个 SQL 语句¶
本主题说明如何向 Snowflake SQL API 提交包含多个语句的请求。
Note
Executing multiple statements in a single query requires that a valid warehouse is available in a session.
简介
在某些情况下,可能需要在请求中指定多个 SQL 语句。例如,您可能需要执行以下操作:
- 定义显式事务
- 在请求中的语句中设置和使用会话变量
- 在请求中的语句中创建和使用临时表
- 更改请求中语句的数据库、架构、仓库或角色
以下各部分说明如何提交包含多个 SQL 语句的请求。
在请求中指定多个 SQL 语句¶
要在单个请求中提交多个 SQL 语句,请执行以下操作:
- In the
statementfield, use a semicolon (;) between each statement. - In the
parametersfield, set theMULTI_STATEMENT_COUNTfield to the number of SQL statements in the request.
例如:
In this example MULTI_STATEMENT_COUNT is set to 2 which corresponds to the number of SQL statements being submitted.
To submit a variable number of SQL statements in the statement field, set MULTI_STATEMENT_COUNT to
0. This is useful in an application where the number of SQL statements submitted is not known at runtime.
If the value of MULTI_STATEMENT_COUNT does not match the number of SQL statements specified in the
statement field, the SQL API returns the following error:
其中
actual_countis the number of statements specified in thestatementfield.desired_countis the value ofMULTI_STATEMENT_COUNT.
If you specify multiple SQL statements in the statement field, but do not specify the
MULTI_STATEMENT_COUNT field, the SQL API returns the following error:
Note
Snowflake 目前不支持多语句 SQL 请求中的变量绑定。
获取请求中每个 SQL 语句的结果¶
If a request that contains multiple SQL statements is processed successfully, the response does not include the data returned from
executing the individual statements. Instead, the response contains a statementHandles field that contains an array of the
handles for the individual statements.
Note
The statementHandles field is different from the statementHandle field:
- The
statementHandlefield specifies the handle for the set of SQL statements in the request. - The
statementHandlesfield is an array of the handles of the individual SQL statements in the request.
例如,假设发送了一个指定了两个要执行的 SQL 语句的请求:
The response contains a statementHandles field that contains an array of the handles for the individual statements.
To check the status and retrieve the data for the individual statements, send a GET request to the
/api/v2/statements/ endpoint and append the handle for each statement to the URL path. See
Checking the status of the statement execution and retrieving the data for details.
处理在请求中指定多个语句时的错误
If you specified multiple SQL statements in the request and an error occurred when executing any of the statements, Snowflake returns the HTTP response code 422 with a QueryFailureStatus object.
You can get details about the error from this object.
例如,假设请求指定了以下语句,其中第二个 INSERT 语句包含错误:
Snowflake returns a response with the HTTP response code 422 and with a QueryFailureStatus object that contains the
details about the error:
In the example above, the INSERT statement with the error starts at the character position 75 in the value of the
statement field.
出错语句之前的语句执行成功(在本例中为 CREATE TABLE 和第一个 INSERT 语句)。不执行出错语句之后的语句。