2 回答
TA贡献1854条经验 获得超8个赞
最后,我找到了正确的语法。还注意到我的代码中存在一些错误。
错误:
sql=('''.......''')
SQL 变量 ( )中的 SQL 查询语法错误最后一行的打印语句是错误的,我的选择查询没有
url and view_count
列。在动态 SQL 中,我们必须在 where 条件中传递单引号(如果它是一个字符串)
示例工作代码:
代码 1:
from google.cloud import bigquery
table_name='tbla'
client = bigquery.Client()
job_config = bigquery.QueryJobConfig(use_legacy_sql=False)
sql="declare cols string;
set cols=(select STRING_AGG (column_name,',')
from `my_db.INFORMATION_SCHEMA.COLUMNS` where table_name='{}');
EXECUTE IMMEDIATE format(\"\"\"select %s from `manan.tbla` \"\"\",cols)".format(table_name)
print(sql)
query_job = client.query(sql, job_config=job_config)
results = query_job.result()
for row in results:
print(row)
代码 2:
from google.cloud import bigquery
table_name='tbla'
client = bigquery.Client()
job_config = bigquery.QueryJobConfig(use_legacy_sql=False)
sql="declare cols string;
set cols=(select STRING_AGG (column_name,',')
from `my_db.INFORMATION_SCHEMA.COLUMNS` where table_name='{}');
EXECUTE IMMEDIATE format(\"\"\"select ? from `my_db.tbla` \"\"\") using cols".format(table_name)
print(sql)
query_job = client.query(sql, job_config=job_config)
results = query_job.result()
for row in results:
print(row)
代码 3:
from google.cloud import bigquery
table_name='tbla'
client = bigquery.Client()
job_config = bigquery.QueryJobConfig(use_legacy_sql=False)
sql="declare cols string;set cols=(select STRING_AGG (column_name,',') from
`my_db.INFORMATION_SCHEMA.COLUMNS` where table_name='{}');EXECUTE IMMEDIATE
format(\"\"\"select @ col from `my_db.tbla` \"\"\") using cols as col".format(table_name)
print(sql)
query_job = client.query(sql, job_config=job_config)
results = query_job.result()
for row in results:
print(row)
TA贡献1852条经验 获得超7个赞
Jinja2 SQL 模板是构建动态 SQL 的更好选择。例子:
create or replace table {{ params.targetTable }}
as
select
{{ params.targetColumnList|join(',') }},
cast(null as timestamp) as begin_timestamp,
cast(null as timestamp) as end_timestamp
from
{{ params.sourceTable }};
添加回答
举报