Oracle 'printf' 等效项
-
05-07-2019 - |
题
以下内容是否有等效或替代方案?
SELECT mix_type || ' (' || mix_num || ')' as description
FROM acid_batch
WHERE mix_num < 10
Oracle 有类似 printf 风格的格式吗?
SELECT printf("%s (%s)", mix_type, mix_num) as description,
FROM acid_batch
WHERE mix_num < 10
解决方案
不,没有内置的 Oracle 函数以这种方式应用格式化字符串。尽管为这个特定示例编写自定义函数很容易,但编写基于 PL/SQL 的 printf 实现将具有挑战性。
如果您经常需要这样做,也许您可以编写一个 Oracle 函数来包装 Java 调用,以获得更丰富的字符串处理环境。
其他提示
我可以想到的与printf最接近的标准近似值是 utl_lms.format_message 。但是,它在SQL语句中不起作用,也就是说,这没关系:
begin
dbms_output.put_line(
utl_lms.format_message('hello %s, the number is %d', 'world', 42)
);
end;
/
但这会产生 ORA-00902:无效的数据类型错误:
select utl_lms.format_message('hello %s, the number is %d', 'world', 42)
from dual
另一个想法:我发现REPLACE对这类事情很有用,特别是当模板很复杂时:
SELECT REPLACE(REPLACE(
'%mix_type% (%mix_num%)' /*template*/
,'%mix_type%', mix_type)
,'%mix_num%' , mix_num ) as description,
FROM acid_batch
WHERE mix_num < 10
唯一的缺点是你需要添加与要替换的变量一样多的REPLACE(
,但至少你只需要每个变量一个,无论它出现在模板中多少次。
(注意:使用<!>“;%<!>”作为分隔符并没有特别的意义,它只是我个人的惯例 - 您可以选择不同的模式,例如<mix_type>
或[mix_type]
)
对于这个特殊的例子,它看起来有点过分,但在某些情况下,它可以使事情变得更容易,例如:
template := 'bla bla %a% %b% %a%';
output := REPLACE(REPLACE(template
,'%a%', some_complex_expression)
,'%b%', b);
将上述内容与以下内容进行比较:
output := 'bla bla ' || some_complex_expression || ' ' || b || ' ' || some_complex_expression;
我为Oracle SQL / PLSQL创建了一个名为 ora_te(在GitHub上)的简单模板引擎 。 借助它,您可以通过以下方式实现目标:
使用多个模板字符串解析的无效实现:
with acid_batch as (
select rownum as mix_type, rownum + 2 as mix_num
from all_objects
where rownum < 10
)
--
SELECT pk_te.substitute('$1 ($2)', ty_p( mix_type, mix_num ) ) as description
FROM acid_batch
WHERE mix_num < 10;
一次编译(解析)的有效实现:
with acid_batch as (
select rownum as mix_type, rownum + 2 as mix_num
from all_objects
where rownum < 10
),
--
o as (
select ty_te.compile_numbered( '$1 ($2)' ) te from dual
)
SELECT pk_te.substitute( o.te, ty_p( mix_type, mix_num ) ) as description
FROM acid_batch, o
WHERE mix_num < 10;
BTW它还支持命名占位符。
不隶属于 StackOverflow