EXECUTE IMMEDIATE
適用於: Databricks SQL
Databricks Runtime 14.3 和以上版本
執行 SQL 語句,此語句由 STRING
提供。
語句選擇性地將自變數傳遞至 參數標記, 並將結果指派給 變數。
語法
EXECUTE IMMEDIATE sql_string
[ INTO var_name [, ...] ]
[ USING { arg_expr [ AS ] [alias] } [, ...] ]
為了與其他 SQL 方言相容, EXECUTE IMMEDIATE
也支援 USING ( { arg_expr [ AS ] [alias] } [, ...] )
參數
sql_string
一個
STRING
字面值或變數,生成符合規範的 SQL 語句。您無法嵌套
EXECUTE IMMEDIATE
語句。INTO ( var_name [, ...] )
選擇性地將單一數據列查詢的結果傳回 SQL 變數。 如果查詢未傳回任何資料列,則結果為
NULL
。如果語句不是 查詢,Azure Databricks 會傳回
INVALID_STATEMENT_FOR_EXECUTE_INTO
錯誤。如果查詢傳回一個以上的數據列,Azure Databricks 就會 引發ROW_SUBQUERY_TOO_MANY_ROWS 錯誤。
-
SQL 變數。 不允許對變數進行多次引用。
-
USING { arg_expr [ AS ] [alias] } [, ...]
或者,如果
sql_string
包含參數標記,則會將值系結至參數。
範例
-- A self-contained execution using a literal string
> EXECUTE IMMEDIATE 'SELECT SUM(c1) FROM VALUES(?), (?) AS t(c1)' USING 5, 6;
11
-- A SQL string composed in a SQL variable
> DECLARE sqlStr = 'SELECT SUM(c1) FROM VALUES(?), (?) AS t(c1)';
> DECLARE arg1 = 5;
> DECLARE arg2 = 6;
> EXECUTE IMMEDIATE sqlStr USING arg1, arg2;
11
-- Using the INTO clause
> DECLARE sum INT;
> EXECUTE IMMEDIATE sqlStr INTO sum USING arg1, arg2;
> SELECT sum;
11
-- Using named parameter markers
> SET VAR sqlStr = 'SELECT SUM(c1) FROM VALUES(:first), (:second) AS t(c1)';
> EXECUTE IMMEDIATE sqlStr INTO sum
USING (5 AS first, arg2 AS second);
> SELECT sum;
11