// strings reference

SQL FORMATMESSAGE function

Substitutes arguments into a message template the way RAISERROR does, returning the string instead of raising an error.

카테고리
Strings
Returns
string
In this category
22 of 172

구문

FORMATMESSAGE('template %s %d', arg1, arg2)

엔진 지원

엔진Support메모
SQL Server 예 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.

예시

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;

알아 두면 좋은 정보

  • 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.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, SQLite.

// fewer lookups

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.