databrick多次将python参数传递到循环sql脚本中

u4dcyp6a  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(422)

我试图创建一个python列表,其中包含多个变量,这些变量将用作for循环中的值,for循环通过创建多个表的sql查询,但是我似乎找不到一个示例来显示多次使用的参数。

list = ["a","b","c"]
for x in list:
sql = ''' 
create volatile table test_{} as (
select * from database.tablename_{}
) with data on commit preserve rows;

create volatile table test2_{} as (
select * from database.tablename2_{}
) with data on commit preserve rows;
'''
display(sql)
7z5jn7bk

7z5jn7bk1#

您可以使用所谓的f字符串(从python 3.6开始),将同一变量插入多个位置:

list = ["a","b","c"]
for x in list:
    sql = f'''
create volatile table test_{x} as (
select * from database.tablename_{x}
) with data on commit preserve rows;

create volatile table test2_{x} as (
select * from database.tablename2_{x}
) with data on commit preserve rows;
'''
    print(sql)

或者你可以用 format 带编号占位符

list = ["a","b","c"]
for x in list:
    sql = '''
create volatile table test_{0} as (
select * from database.tablename_{0}
) with data on commit preserve rows;

create volatile table test2_{0} as (
select * from database.tablename2_{0}
) with data on commit preserve rows;
'''.format(x)
    print(sql)

相关问题