取消语句¶
取消语句的推荐方法是,使用运行查询的应用程序的界面(例如 Snowflake Web 界面中的 Worksheet),或者使用由 Snowflake ODBC 或 JDBC 驱动程序提供的取消 API。但是,在某些情况下,必须使用 SQL 取消查询。
Snowflake 提供以下函数,以支持使用 SQL 取消正在运行的/活跃的语句:
示例¶
以下 Java 示例代码使用 SYSTEM$CANCEL_ALL_QUERIES 和其他 Snowflake 函数在 5 秒钟后取消当前会话中正在运行的语句:
示例代码首先对 CURRENT_SESSION 发出 SQL 命令,以获取会话标识符。
然后,它会创建一个任务,在 5 秒钟后执行。此任务使用会话标识符作为 SYSTEM$CANCEL_ALL_QUERIES 的参数。
然后,使用 GENERATOR 表函数执行长时间运行的语句,在 120 秒时限内生成行。
public void testCancelQuery() throws IOException, SQLException
{
Statement statement = null;
ResultSet resultSet = null;
ResultSetMetaData resultSetMetaData = null;
final Connection connection = getConnection(true);
try
{
// Get the current session identifier
Statement getSessionIdStmt = connection.createStatement();
resultSet = getSessionIdStmt.executeQuery("SELECT current_session()");
resultSetMetaData = resultSet.getMetaData();
assertTrue(resultSet.next());
final int sessionId = resultSet.getInt(1);
// Use Timer to cancel all queries of session in 5 seconds
Timer timer = new Timer();
timer.schedule( new TimerTask()
{
@Override
public void run()
{
try
{
// Cancel all queries on session
PreparedStatement cancelAll;
cancelAll = connection.prepareStatement(
"call system$cancel_all_queries(?)");
// bind the session identifier as first argument
cancelAll.setInt(1, sessionId);
cancelAll.executeQuery();
}
catch (SQLException ex)
{
logger.log(Level.SEVERE, "Cancel failed with exception {}", ex);
}
}
}, 5000);
// Use the internal row generator to execute a query for 120 seconds
statement = connection.createStatement();
resultSet = statement.executeQuery(
"SELECT count(*) FROM TABLE(generator(timeLimit => 120))");
resultSetMetaData = resultSet.getMetaData();
statement.close();
}
catch (SQLException ex)
{
// assert the sqlstate is what we expect (QUERY CANCELLED)
assertEquals("sqlstate mismatch",
SqlState.QUERY_CANCELED, ex.getSQLState());
}
catch (Throwable ex)
{
logger.log(Level.SEVERE, "Test failed with exception: ", ex);
}
finally
{
if (resultSet != null)
resultSet.close();
if (statement != null)
statement.close();
// close connection
if (connection != null)
connection.close();
}
}