How do you use the FORMATMESSAGE function to format messages with placeholders?
Posted by BobHarris
Last Updated: July 02, 2024
The FORMATMESSAGE function in SQL Server is used to format a message string by replacing placeholders with specified values. This can be particularly useful for creating dynamic error messages or log messages with specific data.
Syntax of FORMATMESSAGE:
FORMATMESSAGE ( 'format_string', arg1, arg2, ..., argN )
- format_string: A string containing plain text and placeholders. Placeholders are represented by %1, %2, ..., %n, where each %n refers to the argN argument. - arg1, arg2, ..., argN: Values that will replace their corresponding placeholders in the format string.
Example Usage:
Here’s an example of how to use the FORMATMESSAGE function:
DECLARE @errorMessage NVARCHAR(100);
DECLARE @errorCode INT = 404;
DECLARE @errorDetail NVARCHAR(100) = 'Not found';

SET @errorMessage = FORMATMESSAGE('Error %1: %2', @errorCode, @errorDetail);

PRINT @errorMessage;
Explanation:
1. Declare Variables: In the example, we declare variables for the error code and error detail. 2. Call FORMATMESSAGE: We call FORMATMESSAGE with a format string that includes placeholders %1 and %2, which are replaced by the values of @errorCode and @errorDetail, respectively. 3. Output: The result is stored in @errorMessage, which would output Error 404: Not found.
Placeholders:
- %n: Refers to the nth argument provided to FORMATMESSAGE. - For example: - %1 will be replaced by the first argument. - %2 will be replaced by the second argument, and so on.
Important Notes:
- If you provide more arguments than placeholders in your format string, the extra arguments will be ignored. - If the number of placeholders exceeds the number of provided arguments, SQL Server will generate an error. - Make sure to apply appropriate casting if the argument types do not match the expected output.
Example with Different Data Types:
You can also format messages that include different data types, such as integers and strings:
DECLARE @userID INT = 42;
DECLARE @userName NVARCHAR(50) = 'John Doe';

SELECT FORMATMESSAGE('User ID: %1, Name: %2', @userID, @userName) AS FormattedMessage;
In this example, the output would be:
User ID: 42, Name: John Doe
Using FORMATMESSAGE effectively can help you create clear and structured messages in your SQL Server applications.
Related Content