我正在编写一个脚本,该脚本在设置表描述元数据的同时创建一个表。最终,这将采用变量表名和表描述作为输入,因此需要execute immediate语句。现在,为了保持整洁,我只是将变量设置为静态字符串。我希望表格描述有多行新行,因为我将在其中包含一些不同的信息,出于易读性的原因,我不希望所有信息都在一行。
我的代码(下面(看起来是正确的,但是当我运行它时,我得到了一个错误:
Invalid EXECUTE IMMEDIATE sql string ` CREATE OR REPLACE TABLE `project.dataset.example_table` OPTIONS ( description = ' This is a table description. It uses multiple lines. ' ) AS ( Select 1 ) `, Syntax error: Unclosed string literal at [12:19]`
我真的不知道这个未闭合的字符串文字在哪里。如果我从错误消息中复制SQL字符串并运行它,它会正常工作。我唯一能想到的是,它是否与table_description变量中的换行符有关?
Declare table_name string;
Declare table_description string;
Set table_name = 'project.dataset.example_table';
Set table_description =
"""
This is a table description.
It uses multiple lines.
""";
EXECUTE IMMEDIATE """
CREATE OR REPLACE TABLE `""" || table_name || """`
OPTIONS (
description = '""" || table_description || """'
) AS (
Select 1
)
""";
下面是固定版本-只需比较即可看到几个"修复";
Declare table_name string;
Declare table_description string;
Set table_name = 'project.dataset.example_table';
Set table_description =
"""
This is a table description.
It uses multiple lines.
""";
EXECUTE IMMEDIATE """
CREATE OR REPLACE TABLE `""" || table_name || """`
OPTIONS (
description = '''""" || table_description || """'''
) AS (
Select 1 as col_name
)
""";