FORMAT_TEXT
功能概述
用编号占位符
{1}{1}
、
{2}{2}
……拼接字符串:模板中的
{n}{n}
替换为第 n 个参数的值。适合生成提示语、通知文案、日志消息等固定模板的文本。
和 FORMAT_STRING 的区别:
FORMAT_STRINGFORMAT_STRING
使用 printf 风格的
%s%s
、
%d%d
,按顺序对应参数;
FORMAT_TEXTFORMAT_TEXT
按编号引用参数,同一个参数可以出现多次、顺序可以打乱,模板更易读。
语法
FORMAT_TEXT(<template> [, <arg1>, <arg2> ...])
参数说明
<template><template>
:STRING 类型,模板字符串。占位符写作 {n}{n}
,n 从 1 开始。需要输出字面量 {n}{n}
时,在 {{
前加一个反斜杠,SQL 字符串中写作 '\{1}''\{1}'
。
⚠️ 注意 :
{0}{0}
、
{}{}
、
{abc}{abc}
等非法占位符会报错,错误信息形如
FORMAT_TEXT: invalid placeholder {0}: N must be a positive integerFORMAT_TEXT: invalid placeholder {0}: N must be a positive integer
。
<arg><arg>
:要填入的值,支持字符串、整数、浮点数、DECIMAL、布尔类型。参数个数必须不少于模板中最大的占位符编号,多出的参数会被忽略。
⚠️ 注意 :任一参数为 NULL 时整个结果为 NULL。需要把 NULL 显示为空串时,先用
COALESCECOALESCE
处理。
使用示例
基本替换、乱序引用和重复引用:
SELECT format_text('hello {1} and {2}', 'world', 'foo') AS r1,
format_text('second: {2}, first: {1}', 'foo', 'bar') AS r2,
format_text('{1} and {1} and {2}', 'foo', 'bar') AS r3;
r1 r2 r3 hello world and foo second: bar, first: foo foo and foo and bar
填入数值和布尔值:
SELECT format_text('count: {1}, price: {2}, flag: {3}', 42, 3.14, true);
count: 42, price: 3.14, flag: true
转义占位符,输出字面量
{1}{1}
:
SELECT format_text('use \{1} for placeholder, actual: {1}', 'value');
use {1} for placeholder, actual: value
也可以只写要转义的占位符:
SELECT format_text('\{1}', 'value');
{1}
按行生成通知文案,并用
COALESCECOALESCE
避免 NULL 导致整行结果为 NULL:
SELECT format_text('{1},你的订单 {2} 已发货,快递公司:{3}', name, order_id, coalesce(carrier, '待定')) AS msg
FROM VALUES ('张三', 'A1001', '顺丰'), ('李四', 'A1002', NULL) AS t(name, order_id, carrier);
msg 张三,你的订单 A1001 已发货,快递公司:顺丰 李四,你的订单 A1002 已发货,快递公司:待定
注意事项
模板必须是字符串常量。
占位符编号从 1 开始;{0}{0}
、空占位符 {}{}
和非数字占位符会报错。
参数个数少于模板引用的最大编号时报错,如 format_text('{1} and {3}', 'a')format_text('{1} and {3}', 'a')
报 FORMAT_TEXT: template requires at least 3 arguments, but got 1FORMAT_TEXT: template requires at least 3 arguments, but got 1
。
任一参数为 NULL,结果为 NULL。
相关文档