##
PostgreSQL的format函数真有趣
1、概述
继放假5天之后,又开始上班了,客户让我给他拼接一个SQL语句,去查了下format的资料和案例,发现这个函数是真有趣。
2、format
The function format produces output formatted according to a format string, in a style similar to the C function sprintf.
format(formatstr text [, formatarg "any" [, ...] ])
formatstr is a format string that specifies how the result should be formatted. Text in the format string is copied directly to the result, except where format specifiers are used. Format specifiers act as placeholders in the string, defining how subsequent function arguments should be formatted and inserted into the result. Each formatarg argument is converted to text according to the usual output rules for its data type, and then formatted and inserted into the result string according to the format specifier(s).
Format specifiers are introduced by a % character and have the form
%[position][flags][width]type
where the component fields are:
-
position(optional)A string of the form
*n*$wherenis the index of the argument to print. Index 1 means the first argument afterformatstr. If thepositionis omitted, the default is to use the next argument in sequence. -
flags(optional)Additional options controlling how the format specifier’s output is formatted. Currently the only supported flag is a minus sign (
-) which will cause the format specifier’s output to be left-justified. This has no effect unless thewidthfield is also specified. -
width(optional)Specifies the minimum number of characters to use to display the format specifier’s output. The output is padded on the left or right (depending on the
-flag) with spaces as needed to fill the width. A too-small width does not cause truncation of the output, but is simply ignored. The width may be specified using any of the following: a positive integer; an asterisk (*) to use the next function argument as the width; or a string of the form**n*$to use thenth function argument as the width.If the width comes from a function argument, that argument is consumed before the argument that is used for the format specifier’s value. If the width argument is negative, the result is left aligned (as if the-flag had been specified) within a field of lengthabs(width). -
type(required)The type of format conversion to use to produce the format specifier’s output. The following types are supported:
sformats the argument value as a simple string. A null value is treated as an empty string.Itreats the argument value as an SQL identifier, double-quoting it if necessary. It is an error for the value to be null (equivalent toquote_ident).Lquotes the argument value as an SQL literal. A null value is displayed as the stringNULL, without quotes (equivalent toquote_nullable).
In addition to the format specifiers described above, the special sequence %% may be used to output a literal % character.
3、案例





