简体   繁体   English

通过 Python 执行 Bigquery cmd 时处理换行符

[英]Handling newline character while executing Bigquery cmd via Python

I have sql query in a string variable that I am executing via Python.我在通过 Python 执行的字符串变量中有 sql 查询。 The problem I am facing is that I can't pass '\n' in the string variable.我面临的问题是我无法在字符串变量中传递 '\n' 。 When using CHR(13) ||使用 CHR(13) 时 || CHR(10) I get following error - CHR(10) 我收到以下错误 -

Argument 2 to STRING_AGG must be a literal or query parameter STRING_AGG 的参数 2 必须是文字或查询参数

Query -询问 -

sql_stmt="""
    SELECT 
    STRING_AGG(COLUMN_NAME || ' ' || DATA_TYPE || ',' , CHR(13)) AS COLUMN_LIST
    FROM  `prj_name.dataset_name.INFORMATION_SCHEMA.COLUMNS`
"""

I am then using bigquery to execute the above statement using the client.query(sql_stmt) command.然后我使用 bigquery 使用 client.query(sql_stmt) 命令执行上述语句。 If I pass '\n' as command query is failing as string is getting split into two parts and failing.如果我通过 '\n' 作为命令查询失败,因为字符串被分成两部分并且失败。

Can someone tell me how I can handle this situation?有人能告诉我如何处理这种情况吗?

Try with sql_stmt=r"""...""" (note the r ) and using \n instead of CHR(13)尝试使用sql_stmt=r"""...""" (注意r )并使用\n而不是CHR(13)

As @Jaytiger mentined you can use '\\n' instead of CHR(13) .正如@Jaytiger 所说,您可以使用'\\n'而不是CHR(13)

from google.cloud import bigquery

client = bigquery.Client(project="prj_name")

query = """
SELECT  STRING_AGG(COLUMN_NAME || ' ' || DATA_TYPE || ',' , '\\n') AS COLUMN_LIST
FROM  `prj_name.dataset_name.INFORMATION_SCHEMA.COLUMNS`
"""

job = client.query(query)
res = job.result()
for r in res:
    print(r.COLUMN_LIST)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM