BigQuery 存储过程 SQL%RowFound

BigQuery Stored Procedure SQL%RowFound

如何检查存储过程中的 SQL 语句是否成功返回一行或多行。以下是我检查特定 table 是否有重复项的存储过程。我不确定如何在存储过程中编写 IF 语句

CREATE OR REPLACE PROCEDURE my_project.LOGGING.check_dup_prc(project_name STRING, data_set_name STRING, table_name STRING, date_id DATE, cols STRING,OUT found_duplicates STRING) 
BEGIN DECLARE sql STRING; 
set sql ='Select date,'||cols||','||'count(1) from '||project_name||'.'||data_set_name||'.'||table_name|| ' where date=\''||date_id || '\' GROUP BY date,'||cols||'HAVING COUNT(*)>1'; 
EXECUTE IMMEDIATE (SQL); 

if SQL%ROWSFOUND THEN
   found_duplicates ='Y'
ELSE 
   found_duplicates='N'
END;

END;

我建议将 sql 写成:

DECLARE rowsFound BOOL;

set sql ='Select count(*) > 0 from '||project_name||'.'||data_set_name||'.'||table_name|| ' where date=@date_id GROUP BY date,'||cols; 
EXECUTE IMMEDIATE (SQL) INTO rowsFound USING date_id AS date_id; 

注意date_id也作为参数传入@date_id,始终推荐这样。

您还可以找到更多关于 INTOUSING for EXECUTE IMMEDIATE from public documentation.

您还应该调整 sql 以确保它只吐出 1 行以使 INTO 工作。

更新:如果您需要捕获多行

DECLARE rowsFound ARRAY<BOOL>;

SET sql ='Select <some_array>'; 
EXECUTE IMMEDIATE (SQL) INTO rowsFound;