SQL FORMATMESSAGE function
Substitutes arguments into a message template the way RAISERROR does, returning the string instead of raising an error.
- Categoria
- Strings
- Returns
string- In this category
- 22 of 172
Sintaxe
FORMATMESSAGE('template %s %d', arg1, arg2)
Suporte a mecanismos
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Sim | format-string styles need SQL Server 2016+ |
| PostgreSQL | Different name or syntax | format() covers the same ground |
| MySQL | Not built in | No built-in equivalent. |
| SQLite | Different name or syntax | printf()/format() |
| Oracle | Not built in | No built-in equivalent. |
Exemplos
SQL Server
SELECT FORMATMESSAGE('Order %s has %d items', 'A-100', 3) AS msg; -- Order A-100 has 3 items
PostgreSQL
SELECT format('Order %s has %s items', 'A-100', 3) AS msg;
Bom saber
- Passing a template string with placeholders needs SQL Server 2016+; older builds only format messages by sys.messages message_id.
- Placeholders mirror RAISERROR: %s string, %d integer, %i signed, %% for a literal percent sign.
- PostgreSQL's format() is the portable twin: format('%s bought %s items', name, n), with %I and %L for safe identifiers and literals.
- Missing arguments print as (null): FORMATMESSAGE('%s has %s', 'A') returns 'A has (null)'. Types must match the placeholder or the substitution misfires.
Questions about FORMATMESSAGE
Is FORMATMESSAGE the same as RAISERROR?
Same placeholder engine, different effect: RAISERROR raises an error, FORMATMESSAGE just returns the formatted string, which you can use in variables and queries.
What is the PostgreSQL equivalent of FORMATMESSAGE?
format(): format('%s = %s', k, v) with %s, %I and %L placeholders. SQLite's printf()/format() is a closer sprintf with %d and %f.
Why does my output contain (null)?
A placeholder had no matching argument, or the argument was NULL. Count placeholders against arguments, and write a literal percent sign as %%.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, SQLite.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.