Mssql raise error

Technical documentation for Microsoft SQL Server, tools such as SQL Server Management Studio (SSMS) , SQL Server Data Tools (SSDT) etc. - sql-docs/raiserror-transact-sql.md at live · MicrosoftDocs...
title description author ms.author ms.date ms.service ms.subservice ms.topic f1_keywords helpviewer_keywords dev_langs monikerRange

RAISERROR (Transact-SQL)

RAISERROR (Transact-SQL)

rwestMSFT

randolphwest

08/09/2022

sql

t-sql

reference

RAISERROR

RAISERROR_TSQL

RAISEERROR_TSQL

sysmessages system table

errors [SQL Server], RAISERROR statement

user-defined error messages [SQL Server]

system flags

generating errors [SQL Server]

TRY block [SQL Server]

recording errors

ad hoc messages

RAISERROR statement

CATCH block

messages [SQL Server], RAISERROR statement

TSQL

>= aps-pdw-2016 || = azuresqldb-current || = azure-sqldw-latest || >= sql-server-2016 || >= sql-server-linux-2017 || = azuresqldb-mi-current

[!INCLUDE sql-asdb-asdbmi-asa-pdw]

[!NOTE]
The RAISERROR statement does not honor SET XACT_ABORT. New applications should use THROW instead of RAISERROR.

Generates an error message and initiates error processing for the session. RAISERROR can either reference a user-defined message stored in the sys.messages catalog view, or build a message dynamically. The message is returned as a server error message to the calling application or to an associated CATCH block of a TRY...CATCH construct. New applications should use THROW instead.

:::image type=»icon» source=»../../includes/media/topic-link-icon.svg» border=»false»::: Transact-SQL syntax conventions

Syntax

Syntax for SQL Server and Azure SQL Database:

RAISERROR ( { msg_id | msg_str | @local_variable }
    { , severity, state }
    [ , argument [ , ...n ] ] )
    [ WITH option [ , ...n ] ]

Syntax for Azure Synapse Analytics and Parallel Data Warehouse:

RAISERROR ( { msg_str | @local_variable }
    { , severity, state }
    [ , argument [ , ...n ] ] )
    [ WITH option [ , ...n ] ]

[!INCLUDEsql-server-tsql-previous-offline-documentation]

Arguments

msg_id

A user-defined error message number stored in the sys.messages catalog view using sp_addmessage. Error numbers for user-defined error messages should be greater than 50000. When msg_id is not specified, RAISERROR raises an error message with an error number of 50000.

msg_str

A user-defined message with formatting similar to the printf function in the C standard library. The error message can have a maximum of 2,047 characters. If the message contains 2,048 or more characters, only the first 2,044 are displayed and an ellipsis is added to indicate that the message has been truncated. Note that substitution parameters consume more characters than the output shows because of internal storage behavior. For example, the substitution parameter of %d with an assigned value of 2 actually produces one character in the message string but also internally takes up three additional characters of storage. This storage requirement decreases the number of available characters for message output.

When msg_str is specified, RAISERROR raises an error message with an error number of 50000.

msg_str is a string of characters with optional embedded conversion specifications. Each conversion specification defines how a value in the argument list is formatted and placed into a field at the location of the conversion specification in msg_str. Conversion specifications have this format:

% [[flag] [width] [. precision] [{h | l}]] type

The parameters that can be used in msg_str are:

flag

A code that determines the spacing and justification of the substituted value.

Code Prefix or justification Description
— (minus) Left-justified Left-justify the argument value within the given field width.
+ (plus) Sign prefix Preface the argument value with a plus (+) or minus (-) if the value is of a signed type.
0 (zero) Zero padding Preface the output with zeros until the minimum width is reached. When 0 and the minus sign (-) appear, 0 is ignored.
# (number) 0x prefix for hexadecimal type of x or X When used with the o, x, or X format, the number sign (#) flag prefaces any nonzero value with 0, 0x, or 0X, respectively. When d, i, or u are prefaced by the number sign (#) flag, the flag is ignored.
‘ ‘ (blank) Space padding Preface the output value with blank spaces if the value is signed and positive. This is ignored when included with the plus sign (+) flag.

width

An integer that defines the minimum width for the field into which the argument value is placed. If the length of the argument value is equal to or longer than width, the value is printed with no padding. If the value is shorter than width, the value is padded to the length specified in width.

An asterisk (*) means that the width is specified by the associated argument in the argument list, which must be an integer value.

precision

The maximum number of characters taken from the argument value for string values. For example, if a string has five characters and precision is 3, only the first three characters of the string value are used.

For integer values, precision is the minimum number of digits printed.

An asterisk (*) means that the precision is specified by the associated argument in the argument list, which must be an integer value.

{h | l} type

Used with character types d, i, o, s, x, X, or u, and creates shortint (h) or longint (l) values.

Type specification Represents
d or i Signed integer
o Unsigned octal
s String
u Unsigned integer
x or X Unsigned hexadecimal

These type specifications are based on the ones originally defined for the printf function in the C standard library. The type specifications used in RAISERROR message strings map to [!INCLUDEtsql] data types, while the specifications used in printf map to C language data types. Type specifications used in printf are not supported by RAISERROR when [!INCLUDEtsql] does not have a data type similar to the associated C data type. For example, the %p specification for pointers is not supported in RAISERROR because [!INCLUDEtsql] does not have a pointer data type.

To convert a value to the [!INCLUDEtsql] bigint data type, specify %I64d.

@local_variable

Is a variable of any valid character data type that contains a string formatted in the same manner as msg_str. @local_variable must be char or varchar, or be able to be implicitly converted to these data types.

severity

The user-defined severity level associated with this message. When using msg_id to raise a user-defined message created using sp_addmessage, the severity specified on RAISERROR overrides the severity specified in sp_addmessage.

For severity levels from 19 through 25, the WITH LOG option is required. Severity levels less than 0 are interpreted as 0. Severity levels greater than 25 are interpreted as 25.

[!CAUTION]
Severity levels from 20 through 25 are considered fatal. If a fatal severity level is encountered, the client connection is terminated after receiving the message, and the error is logged in the error and application logs.

You can specify -1 to return the severity value associated with the error as shown in the following example.

RAISERROR (15600, -1, -1, 'mysp_CreateCustomer');

[!INCLUDEssResult]

Msg 15600, Level 15, State 1, Line 1
An invalid parameter or option was specified for procedure 'mysp_CreateCustomer'.

state

An integer from 0 through 255. Negative values default to 1. Values larger than 255 should not be used.

If the same user-defined error is raised at multiple locations, using a unique state number for each location can help find which section of code is raising the errors.

argument

The parameters used in the substitution for variables defined in msg_str or the message corresponding to msg_id. There can be 0 or more substitution parameters, but the total number of substitution parameters cannot exceed 20. Each substitution parameter can be a local variable or any of these data types: tinyint, smallint, int, char, varchar, nchar, nvarchar, binary, or varbinary. No other data types are supported.

option

A custom option for the error and can be one of the values in the following table.

Value Description
LOG Logs the error in the error log and the application log for the instance of the [!INCLUDEmsCoName] [!INCLUDEssNoVersion] [!INCLUDEssDE]. Errors logged in the error log are currently limited to a maximum of 440 bytes. Only a member of the sysadmin fixed server role or a user with ALTER TRACE permissions can specify WITH LOG.

[!INCLUDEapplies] [!INCLUDEssNoVersion]

NOWAIT Sends messages immediately to the client.

[!INCLUDEapplies] [!INCLUDEssNoVersion], [!INCLUDEssSDS]

SETERROR Sets the @@ERROR and ERROR_NUMBER values to msg_id or 50000, regardless of the severity level.

[!INCLUDEapplies] [!INCLUDEssNoVersion], [!INCLUDEssSDS]

Remarks

The errors generated by RAISERROR operate the same as errors generated by the [!INCLUDEssDE] code. The values specified by RAISERROR are reported by the ERROR_LINE, ERROR_MESSAGE, ERROR_NUMBER, ERROR_PROCEDURE, ERROR_SEVERITY, ERROR_STATE, and @@ERROR system functions. When RAISERROR is run with a severity of 11 or higher in a TRY block, it transfers control to the associated CATCH block. The error is returned to the caller if RAISERROR is run:

  • Outside the scope of any TRY block.

  • With a severity of 10 or lower in a TRY block.

  • With a severity of 20 or higher that terminates the database connection.

CATCH blocks can use RAISERROR to rethrow the error that invoked the CATCH block by using system functions such as ERROR_NUMBER and ERROR_MESSAGE to retrieve the original error information. @@ERROR is set to 0 by default for messages with a severity from 1 through 10.

When msg_id specifies a user-defined message available from the sys.messages catalog view, RAISERROR processes the message from the text column using the same rules as are applied to the text of a user-defined message specified using msg_str. The user-defined message text can contain conversion specifications, and RAISERROR will map argument values into the conversion specifications. Use sp_addmessage to add user-defined error messages and sp_dropmessage to delete user-defined error messages.

RAISERROR can be used as an alternative to PRINT to return messages to calling applications. RAISERROR supports character substitution similar to the functionality of the printf function in the C standard library, while the [!INCLUDEtsql] PRINT statement does not. The PRINT statement is not affected by TRY blocks, while a RAISERROR run with a severity of 11 to 19 in a TRY block transfers control to the associated CATCH block. Specify a severity of 10 or lower to use RAISERROR to return a message from a TRY block without invoking the CATCH block.

Typically, successive arguments replace successive conversion specifications; the first argument replaces the first conversion specification, the second argument replaces the second conversion specification, and so on. For example, in the following RAISERROR statement, the first argument of N'number' replaces the first conversion specification of %s; and the second argument of 5 replaces the second conversion specification of %d.

RAISERROR (N'This is message %s %d.', -- Message text.
           10, -- Severity,
           1, -- State,
           N'number', -- First argument.
           5); -- Second argument.
-- The message text returned is: This is message number 5.
GO

If an asterisk (*) is specified for either the width or precision of a conversion specification, the value to be used for the width or precision is specified as an integer argument value. In this case, one conversion specification can use up to three arguments, one each for the width, precision, and substitution value.

For example, both of the following RAISERROR statements return the same string. One specifies the width and precision values in the argument list; the other specifies them in the conversion specification.

RAISERROR (N'<<%*.*s>>', -- Message text.
           10, -- Severity,
           1, -- State,
           7, -- First argument used for width.
           3, -- Second argument used for precision.
           N'abcde'); -- Third argument supplies the string.
-- The message text returned is: <<    abc>>.
GO
RAISERROR (N'<<%7.3s>>', -- Message text.
           10, -- Severity,
           1, -- State,
           N'abcde'); -- First argument supplies the string.
-- The message text returned is: <<    abc>>.
GO

Permissions

Severity levels from 0 through 18 can be specified by any user. Severity levels from 19 through 25 can only be specified by members of the sysadmin fixed server role or users with ALTER TRACE permissions.

Examples

A. Returning error information from a CATCH block

The following code example shows how to use RAISERROR inside a TRY block to cause execution to jump to the associated CATCH block. It also shows how to use RAISERROR to return information about the error that invoked the CATCH block.

[!NOTE]
RAISERROR only generates errors with state from 1 through 127. Because the [!INCLUDEssDE] may raise errors with state 0, we recommend that you check the error state returned by ERROR_STATE before passing it as a value to the state parameter of RAISERROR.

BEGIN TRY
    -- RAISERROR with severity 11-19 will cause execution to
    -- jump to the CATCH block.
    RAISERROR ('Error raised in TRY block.', -- Message text.
               16, -- Severity.
               1 -- State.
               );
END TRY
BEGIN CATCH
    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT
        @ErrorMessage = ERROR_MESSAGE(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState = ERROR_STATE();

    -- Use RAISERROR inside the CATCH block to return error
    -- information about the original error that caused
    -- execution to jump to the CATCH block.
    RAISERROR (@ErrorMessage, -- Message text.
               @ErrorSeverity, -- Severity.
               @ErrorState -- State.
               );
END CATCH;

B. Creating an ad hoc message in sys.messages

The following example shows how to raise a message stored in the sys.messages catalog view. The message was added to the sys.messages catalog view by using the sp_addmessage system stored procedure as message number 50005.

EXEC sp_addmessage @msgnum = 50005,
              @severity = 10,
              @msgtext = N'<<%7.3s>>';
GO
RAISERROR (50005, -- Message id.
           10, -- Severity,
           1, -- State,
           N'abcde'); -- First argument supplies the string.
-- The message text returned is: <<    abc>>.
GO
EXEC sp_dropmessage @msgnum = 50005;
GO

C. Using a local variable to supply the message text

The following code example shows how to use a local variable to supply the message text for a RAISERROR statement.

DECLARE @StringVariable NVARCHAR(50);
SET @StringVariable = N'<<%7.3s>>';

RAISERROR (@StringVariable, -- Message text.
           10, -- Severity,
           1, -- State,
           N'abcde'); -- First argument supplies the string.
-- The message text returned is: <<    abc>>.
GO

See also

  • Built-in Functions (Transact-SQL)
  • DECLARE @local_variable (Transact-SQL)
  • PRINT (Transact-SQL)
  • sp_addmessage (Transact-SQL)
  • sp_dropmessage (Transact-SQL)
  • sys.messages (Transact-SQL)
  • xp_logevent (Transact-SQL)
  • @@ERROR (Transact-SQL)
  • ERROR_LINE (Transact-SQL)
  • ERROR_MESSAGE (Transact-SQL)
  • ERROR_NUMBER (Transact-SQL)
  • ERROR_PROCEDURE (Transact-SQL)
  • ERROR_SEVERITY (Transact-SQL)
  • ERROR_STATE (Transact-SQL)
  • TRY…CATCH (Transact-SQL)

message_text — сообщение, которое вы хотите показать при ошибке. Замечание: вы можете добавлять пользовательские сообщения для вывода информации об ошибке. Смотрите следующий раздел статьи.
message_id — id сообщения об ошибке. Если вы хотите вывести пользовательское сообщение, вы можете определить этот идентификатор. Посмотрите список идентификаторов сообщений в sys.messages DMV.
Запрос:

select * from sys.messages

Вывод:

severity — серьезность ошибки. Тип данных переменной severity — smallint, значения находятся в диапазоне от 0 до 25. Допустимыми значениями серьезности ошибки являются:

  • 0-10
  • — информационные сообщения

  • 11-18
  • — ошибки

  • 19-25
  • — фатальные ошибки

Замечание: Если вы создаете пользовательское сообщение, сложность, указанная в этом сообщении, будет перебиваться сложностью, заданной в операторе RAISERROR.
state — уникальное идентификационное число, которое может использоваться для раздела кода, вызывающего ошибку. Тип данных параметра state — smallint, и допустимые значения между 0 и 255.

Теперь давайте перейдем к практическим примерам.

Пример 1: использование оператора SQL Server RAISERROR для вывода сообщения

В этом примере вы можете увидеть, как можно отобразить ошибку или информационное сообщение с помощью оператора RAISERROR.

Предположим, что вы хотите отобразить сообщение после вставки записей в таблицу. Мы можем использовать операторы PRINT или RAISERROR. Ниже — код:

SET nocount ON 
INSERT INTO tblpatients
(patient_id,
patient_name,
address,
city)
VALUES ('OPD00006',
'Nimesh Upadhyay',
'AB-14, Ratnedeep Flats',
'Mehsana')
RAISERROR ( 'Patient detail added successfully',1,1)

Вывод:

Как видно на рисунке выше, ID сообщения равно 50000, поскольку это пользовательское сообщение.

Пример 2: оператор SQL RAISERROR с текстом динамического сообщения

Теперь посмотрите, как мы можем создать текст динамического сообщения для оператора SQL RAISERROR.

Предположим, что мы хотим напечатать в сообщении ID пациента. Я описал локальную переменную с именем @PatientID, которая содержит patient_id. Чтобы отобразить значение переменной @PatientID в тексте сообщения, мы можем использовать следующий код:

DECLARE @PatientID VARCHAR(15) 
DECLARE @message NVARCHAR(max)
SET @PatientID='OPD00007'
SET @message ='Patient detail added successfully. The OPDID is %s'
INSERT INTO tblpatients
(patient_id,
patient_name,
address,
city)
VALUES ('' + @PatientID + '',
'Nimesh Upadhyay',
'AB-14, Ratnedeep Flats',
'Mehsana')
RAISERROR ( @message,1,1,@patientID)

Вывод:

Для отображения строки в операторе RAISERROR, мы должны использовать операторы print в стиле языка Си.

Как видно на изображении выше, для вывода параметра в тексте сообщения я использую опцию %s, которая отображает строковое значение параметра. Если вы хотите вывести целочисленный параметр, вы можете использовать опцию %d.

Использование SQL RAISERROR в блоке TRY..CATCH

В этом примере мы добавляем SQL RAISERROR в блок TRY. При запуске этого кода он выполняет связанный блок CATCH. В блоке CATCH мы будем выводить подробную информацию о возникшей ошибке.

BEGIN try 
RAISERROR ('Error invoked in the TRY code block.',16,1 );
END try
BEGIN catch
DECLARE @ErrorMsg NVARCHAR(4000);
DECLARE @ErrSeverity INT;
DECLARE @ErrState INT;
SELECT @ErrorMsg = Error_message(),
@ErrSeverity = Error_severity(),
@ErrState = Error_state();
RAISERROR (@ErrorMsg,
@ErrSeverity,
@ErrState
);
END catch;

Так мы добавили оператор RAISERROR с ВАЖНОСТЬЮ МЕЖДУ 11 И 19. Это вызывает выполнение блока CATCH.

В блоке CATCH мы показываем информацию об исходной ошибке, используя оператор RAISERROR.
Вывод:

Как вы можете увидеть, код вернул информацию об исходной ошибке.

Теперь давайте разберемся, как добавить пользовательское сообщение, используя хранимую процедуру sp_addmessage.

Хранимая процедура sp_addmessage

Мы можем добавить пользовательское сообщение, выполнив хранимую процедуру sp_addmessages. Синтаксис процедуры:

EXEC Sp_addmessage 
@msgnum= 70001,
@severity=16,
@msgtext='Please enter the numeric value',
@lang=NULL,
@with_log='TRUE',
@replace='Replace';

@msgnum: задает номер сообщения. Тип данных параметра — integer. Это ID пользовательского сообщения.
@severity: указывает уровень серьезности ошибки. Допустимые значения от 1 до 25. Тип данных параметра — smallint.
@messagetext: задает текст сообщения, который вы хотите выводить. Тип данных параметра nvarchar(255), значение по умолчанию NULL.
@lang: задает язык, который вы хотите использовать для вывода сообщения об ошибке. Значение по умолчанию NULL.
@with_log: этот параметр используется для записи сообщения в просмотрщик событий. Допустимые значения TRUE и FALSE. Если вы задаете TRUE, сообщение об ошибке будет записано в просмотрщик событий Windows. Если выбрать FALSE, ошибка не будет записана в журнал ошибок Windows.
@replace: если вы хотите заменить существующее сообщение об ошибке на пользовательское сообщение и уровень серьезности, вы можете указать это в хранимой процедуре.

Предположим, что вы хотите создать сообщение об ошибке, которое возвращает ошибку о недопустимом качестве (invalid quality). В операторе INSERT значение invalid_quality находится в диапазоне между 20 и 100. Сообщение следует рассматривать как ошибку с уровнем серьезности 16.

Чтобы создать такое сообщение, выполните следующий запрос:

USE master;
go
EXEC Sp_addmessage
70001,
16,
N'Product Quantity must be between 20 and 100.';
go

После добавления сообщения выполните запрос ниже, чтобы увидеть его:

USE master 
go
SELECT * FROM sys.messages WHERE message_id = 70001

Вывод:

Как использовать пользовательские сообщения об ошибках

Как упоминалось выше, мы должны использовать message_id в операторе RAISERROR для пользовательских сообщений.

Мы создали сообщение с ID = 70001. Оператор RAISERROR должен быть таким:

USE master 
go
RAISERROR (70001,16,1 );
go

Вывод:

Оператор RAISERROR вернул пользовательское сообщение.

Хранимая процедура sp_dropmessage

Хранимая процедура sp_dropmessage используется для удаления пользовательских сообщений. Синтаксис оператора:

EXEC Sp_dropmessage @msgnum

Здесь @msgnum задает ID сообщения, которое вы хотите удалить.

Теперь мы хотим удалить сообщение, с ID = 70001. Запрос:

EXEC Sp_dropmessage 70001

Выполним следующий запрос для просмотра сообщения после его удаления:

USE master 
go
SELECT * FROM sys.messages WHERE message_id = 70001

Вывод:

Как видно, сообщение было удалено.

Summary: in this tutorial, you will learn how to use the SQL Server RAISERROR statement to generate user-defined error messages.

If you develop a new application, you should use the THROW statement instead.

SQL Server RAISEERROR statement overview

The RAISERROR statement allows you to generate your own error messages and return these messages back to the application using the same format as a system error or warning message generated by SQL Server Database Engine. In addition, the RAISERROR statement allows you to set a specific message id, level of severity, and state for the error messages.

The following illustrates the syntax of the RAISERROR statement:

RAISERROR ( { message_id | message_text | @local_variable } { ,severity ,state } [ ,argument [ ,...n ] ] ) [ WITH option [ ,...n ] ];

Code language: SQL (Structured Query Language) (sql)

Let’s examine the syntax of the RAISERROR for better understanding.

message_id

The message_id is a user-defined error message number stored in the sys.messages catalog view.

To add a new user-defined error message number, you use the stored procedure sp_addmessage. A user-defined error message number should be greater than 50,000. By default, the RAISERROR statement uses the message_id 50,000 for raising an error.

The following statement adds a custom error message to the sys.messages view:

EXEC sp_addmessage @msgnum = 50005, @severity = 1, @msgtext = 'A custom error message';

Code language: SQL (Structured Query Language) (sql)

To verify the insert, you use the following query:

SELECT * FROM sys.messages WHERE message_id = 50005;

Code language: SQL (Structured Query Language) (sql)

To use this message_id, you execute the RAISEERROR statement as follows:

RAISERROR ( 50005,1,1)

Code language: SQL (Structured Query Language) (sql)

Here is the output:

A custom error message Msg 50005, Level 1, State 1

Code language: SQL (Structured Query Language) (sql)

To remove a message from the sys.messages, you use the stored procedure sp_dropmessage. For example, the following statement deletes the message id 50005:

EXEC sp_dropmessage @msgnum = 50005;

Code language: SQL (Structured Query Language) (sql)

message_text

The message_text is a user-defined message with formatting like the printf function in C standard library. The message_text can be up to 2,047 characters, 3 last characters are reserved for ellipsis (…). If the message_text contains 2048 or more, it will be truncated and is padded with an ellipsis.

When you specify the message_text, the RAISERROR statement uses message_id 50000 to raise the error message.

The following example uses the RAISERROR statement to raise an error with a message text:

RAISERROR ( 'Whoops, an error occurred.',1,1)

Code language: SQL (Structured Query Language) (sql)

The output will look like this:

Whoops, an error occurred. Msg 50000, Level 1, State 1

Code language: SQL (Structured Query Language) (sql)

severity

The severity level is an integer between 0 and 25, with each level representing the seriousness of the error.

0–10 Informational messages 11–18 Errors 19–25 Fatal errors

Code language: SQL (Structured Query Language) (sql)

state

The state is an integer from 0 through 255. If you raise the same user-defined error at multiple locations, you can use a unique state number for each location to make it easier to find which section of the code is causing the errors. For most implementations, you can use 1.

WITH option

The option can be LOG, NOWAIT, or SETERROR:

  • WITH LOG logs the error in the error log and application log for the instance of the SQL Server Database Engine.
  • WITH NOWAIT sends the error message to the client immediately.
  • WITH SETERROR sets the ERROR_NUMBER and @@ERROR values to message_id or 50000, regardless of the severity level.

SQL Server RAISERROR examples

Let’s take some examples of using the RAISERROR statement to get a better understanding.

A) Using SQL Server RAISERROR with TRY CATCH block example

In this example, we use the RAISERROR inside a TRY block to cause execution to jump to the associated CATCH block. Inside the CATCH block, we use the RAISERROR to return the error information that invoked the CATCH block.

DECLARE @ErrorMessage NVARCHAR(4000), @ErrorSeverity INT, @ErrorState INT; BEGIN TRY RAISERROR('Error occurred in the TRY block.', 17, 1); END TRY BEGIN CATCH SELECT @ErrorMessage = ERROR_MESSAGE(), @ErrorSeverity = ERROR_SEVERITY(), @ErrorState = ERROR_STATE(); -- return the error inside the CATCH block RAISERROR(@ErrorMessage, @ErrorSeverity, @ErrorState); END CATCH;

Code language: SQL (Structured Query Language) (sql)

Here is the output:

Msg 50000, Level 17, State 1, Line 16 Error occurred in the TRY block.

Code language: SQL (Structured Query Language) (sql)

B) Using SQL Server RAISERROR statement with a dynamic message text example

The following example shows how to use a local variable to provide the message text for a RAISERROR statement:

DECLARE @MessageText NVARCHAR(100); SET @MessageText = N'Cannot delete the sales order %s'; RAISERROR( @MessageText, -- Message text 16, -- severity 1, -- state N'2001' -- first argument to the message text );

Code language: SQL (Structured Query Language) (sql)

The output is as follows:

Msg 50000, Level 16, State 1, Line 5 Cannot delete the sales order 2001

Code language: SQL (Structured Query Language) (sql)

When to use RAISERROR statement

You use the RAISERROR statement in the following scenarios:

  • Troubleshoot Transact-SQL code.
  • Return messages that contain variable text.
  • Examine the values of data.
  • Cause the execution to jump from a TRY block to the associated CATCH block.
  • Return error information from the CATCH block to the callers, either calling batch or application.

In this tutorial, you will learn how to use the SQL Server RAISERROR statement to generate user-defined error messages.

Содержание

  1. SQL-Ex blog
  2. Оператор SQL Server RAISERROR на простых примерах
  3. Синтаксис и параметры оператора SQL RAISERROR
  4. Пример 1: использование оператора SQL Server RAISERROR для вывода сообщения
  5. Пример 2: оператор SQL RAISERROR с текстом динамического сообщения
  6. Использование SQL RAISERROR в блоке TRY..CATCH
  7. Хранимая процедура sp_addmessage
  8. Как использовать пользовательские сообщения об ошибках
  9. Хранимая процедура sp_dropmessage
  10. Обратные ссылки
  11. Комментарии
  12. RAISERROR (Transact-SQL)
  13. Синтаксис
  14. Аргументы
  15. msg_id
  16. msg_str
  17. @local_variable
  18. severity
  19. state
  20. argument
  21. Параметр
  22. Remarks
  23. Разрешения
  24. Примеры
  25. A. Возвращение сведений об ошибке из блока CATCH
  26. Б. Создание нерегламентированного сообщения в представлении каталога sys.messages
  27. В. Использование локальной переменной для предоставления текста сообщения

SQL-Ex blog

Новости сайта «Упражнения SQL», статьи и переводы

Оператор SQL Server RAISERROR на простых примерах

Оператор RAISERROR используется для посылки подготовленного сообщения в клиентское приложение. Он также может использоваться для отладки приложения и применения механизма обработки ошибок.

Синтаксис и параметры оператора SQL RAISERROR

Оператор SQL RAISERROR имеет следующий синтаксис:

Ниже описание ключевых параметров RAISERROR, которые вы можете задать:

message_text — сообщение, которое вы хотите показать при ошибке. Замечание: вы можете добавлять пользовательские сообщения для вывода информации об ошибке. Смотрите следующий раздел статьи.
message_id — id сообщения об ошибке. Если вы хотите вывести пользовательское сообщение, вы можете определить этот идентификатор. Посмотрите список идентификаторов сообщений в sys.messages DMV.
Запрос:

severity — серьезность ошибки. Тип данных переменной severity — smallint, значения находятся в диапазоне от 0 до 25. Допустимыми значениями серьезности ошибки являются:

  • 0-10 — информационные сообщения
  • 11-18 — ошибки
  • 19-25 — фатальные ошибки

Замечание: Если вы создаете пользовательское сообщение, сложность, указанная в этом сообщении, будет перебиваться сложностью, заданной в операторе RAISERROR.
state — уникальное идентификационное число, которое может использоваться для раздела кода, вызывающего ошибку. Тип данных параметра state — smallint, и допустимые значения между 0 и 255.

Теперь давайте перейдем к практическим примерам.

Пример 1: использование оператора SQL Server RAISERROR для вывода сообщения

В этом примере вы можете увидеть, как можно отобразить ошибку или информационное сообщение с помощью оператора RAISERROR.

Предположим, что вы хотите отобразить сообщение после вставки записей в таблицу. Мы можем использовать операторы PRINT или RAISERROR. Ниже — код:

Вывод:

Как видно на рисунке выше, ID сообщения равно 50000, поскольку это пользовательское сообщение.

Пример 2: оператор SQL RAISERROR с текстом динамического сообщения

Теперь посмотрите, как мы можем создать текст динамического сообщения для оператора SQL RAISERROR.

Предположим, что мы хотим напечатать в сообщении ID пациента. Я описал локальную переменную с именем @PatientID, которая содержит patient_id. Чтобы отобразить значение переменной @PatientID в тексте сообщения, мы можем использовать следующий код:

Вывод:

Для отображения строки в операторе RAISERROR, мы должны использовать операторы print в стиле языка Си.

Как видно на изображении выше, для вывода параметра в тексте сообщения я использую опцию %s, которая отображает строковое значение параметра. Если вы хотите вывести целочисленный параметр, вы можете использовать опцию %d.

Использование SQL RAISERROR в блоке TRY..CATCH

В этом примере мы добавляем SQL RAISERROR в блок TRY. При запуске этого кода он выполняет связанный блок CATCH. В блоке CATCH мы будем выводить подробную информацию о возникшей ошибке.

Так мы добавили оператор RAISERROR с ВАЖНОСТЬЮ МЕЖДУ 11 И 19. Это вызывает выполнение блока CATCH.

В блоке CATCH мы показываем информацию об исходной ошибке, используя оператор RAISERROR.
Вывод:

Как вы можете увидеть, код вернул информацию об исходной ошибке.

Теперь давайте разберемся, как добавить пользовательское сообщение, используя хранимую процедуру sp_addmessage.

Хранимая процедура sp_addmessage

Мы можем добавить пользовательское сообщение, выполнив хранимую процедуру sp_addmessages. Синтаксис процедуры:

@msgnum: задает номер сообщения. Тип данных параметра — integer. Это ID пользовательского сообщения.
@severity: указывает уровень серьезности ошибки. Допустимые значения от 1 до 25. Тип данных параметра — smallint.
@messagetext: задает текст сообщения, который вы хотите выводить. Тип данных параметра nvarchar(255), значение по умолчанию NULL.
@lang: задает язык, который вы хотите использовать для вывода сообщения об ошибке. Значение по умолчанию NULL.
@with_log: этот параметр используется для записи сообщения в просмотрщик событий. Допустимые значения TRUE и FALSE. Если вы задаете TRUE, сообщение об ошибке будет записано в просмотрщик событий Windows. Если выбрать FALSE, ошибка не будет записана в журнал ошибок Windows.
@replace: если вы хотите заменить существующее сообщение об ошибке на пользовательское сообщение и уровень серьезности, вы можете указать это в хранимой процедуре.

Предположим, что вы хотите создать сообщение об ошибке, которое возвращает ошибку о недопустимом качестве (invalid quality). В операторе INSERT значение invalid_quality находится в диапазоне между 20 и 100. Сообщение следует рассматривать как ошибку с уровнем серьезности 16.

Чтобы создать такое сообщение, выполните следующий запрос:

После добавления сообщения выполните запрос ниже, чтобы увидеть его:

Как использовать пользовательские сообщения об ошибках

Как упоминалось выше, мы должны использовать message_id в операторе RAISERROR для пользовательских сообщений.

Мы создали сообщение с Оператор RAISERROR должен быть таким:

Оператор RAISERROR вернул пользовательское сообщение.

Хранимая процедура sp_dropmessage

Хранимая процедура sp_dropmessage используется для удаления пользовательских сообщений. Синтаксис оператора:

Здесь @msgnum задает ID сообщения, которое вы хотите удалить.

Теперь мы хотим удалить сообщение, с Запрос:

Выполним следующий запрос для просмотра сообщения после его удаления:

Как видно, сообщение было удалено.

Обратные ссылки

Нет обратных ссылок

Комментарии

Показывать комментарии Как список | Древовидной структурой

Автор не разрешил комментировать эту запись

Источник

RAISERROR (Transact-SQL)

Область применения: SQL Server (все поддерживаемые версии) База данных SQL Azure Управляемый экземпляр SQL Azure Azure Synapse Analytics Analytics Platform System (PDW)

Инструкция RAISERROR не учитывает SET XACT_ABORT . Новые приложения должны использовать THROW вместо RAISERROR .

Создает сообщение об ошибке и запускает обработку ошибок для сеанса. RAISERROR может либо ссылаться на определяемое пользователем сообщение, хранящееся в sys.messages , либо динамически создавать сообщение. Это сообщение возвращается как сообщение об ошибке сервера вызывающему приложению или соответствующему блоку CATCH конструкции TRY. CATCH . В новых же приложениях следует использовать инструкцию THROW.

Соглашения о синтаксисе Transact-SQL

Синтаксис

Синтаксис для SQL Server и Базы данных SQL Azure:

Синтаксис для Azure Synapse Analytics и Parallel Data Warehouse:

Ссылки на описание синтаксиса Transact-SQL для SQL Server 2014 и более ранних версий, см. в статье Документация по предыдущим версиям.

Аргументы

msg_id

Определяемый пользователем номер сообщения об ошибке, который хранится в представлении каталога sys.messages с помощью sp_addmessage . Номера пользовательских сообщений об ошибках должны быть больше 50 000. Если аргумент msg_id не определен, то инструкция RAISERROR создает сообщение об ошибке с номером ошибки 50000.

msg_str

Определяемое пользователем сообщение с форматом, аналогичным формату функции printf из стандартной библиотеки языка С. Это сообщение об ошибке не должно содержать более 2 047 символов. Если сообщение содержит 2 048 и более символов, то отображаются только первые 2 044, а за ними появляется знак многоточия, показывающий, что сообщение было усечено. Обратите внимание, что параметры подстановки содержат больше символов, чем видно на выходе из-за внутренней структуры хранения. Например, если параметр подстановки %d имеет значение 2, он выводит один символ в строку сообщения, хотя при хранении занимает три дополнительных символа. Из-за этой особенности хранения количество доступных символов для выходного сообщения уменьшается.

Если аргумент msg_str определен, то инструкция RAISERROR создает сообщение об ошибке с номером ошибки 50000.

Аргумент msg_str является символьной строкой, которая может содержать спецификации преобразования. Каждая спецификация преобразования определяет, каким образом значение из списка аргументов будет отформатировано и помещено в поле в местоположении спецификации преобразования в строке msg_str. Спецификации преобразования имеют следующий формат:

В строке msg_str могут использоваться следующие параметры:

Код, определяющий промежутки и выравнивание подставляемого значения.

Код Префикс или выравнивание Описание
— (знак «минус») Выравнивать слева Выравнивает значение аргумента по левой границе поля заданной ширины.
+ (знак «плюс») Префикс знака Добавляет перед значением аргумента знак «плюс» (+) или «минус» (-), если значение принадлежит к типу со знаком.
0 (ноль) Дополнение нулями Добавляет к выходному значению спереди нули до тех пор, пока не будет достигнута минимальная ширина. При одновременном указании 0 и знака «минус» (-) флаг 0 не учитывается.
# (число) Префикс 0x для шестнадцатеричного типа x или X При использовании формата o, x или X флаг знака числа (#) предшествует любому ненулевому значению 0, 0x или 0X соответственно. Если флаг знака числа (#) стоит перед d, i или u, он пропускается.
‘ ‘ (blank) Заполнение пробелами Добавляет к выходным значениям пробелы, если значение со знаком и положительно. Этот параметр не учитывается, если включается вместе с флагом знака «плюс» (+).

width

Целое число, определяющее минимальную ширину поля, в которое помещается значение аргумента. Если длина значения аргумента равна значению параметра width или превышает его, то значение записывается без заполнения. Если значение короче, чем значение параметра width, оно дополняется до длины, определенной в параметре width.

Символ «звездочка» (*) означает, что ширина определяется соответствующим аргументом в списке аргументов, значение которого должно быть целым числом.

precision

Максимальное число символов, берущееся из значения аргумента для значения строки. Например, если в строке содержится пять символов, а точность равна 3, то для значения строки используются первые три символа.

Для целых значений аргумент precision определяет минимальное количество отображаемых цифр.

Символ «звездочка» (*) означает, что точность определяется соответствующим аргументом в списке аргументов, значение которого должно быть целым числом.

Используется с типами символов d, i, o, s, x, X или u, создает значения типа данных shortint (h) или longint (l).

Спецификация типа Представляет
d или i Целое число со знаком
o Восьмеричное число без знака
s Строка
u Целое число без знака
x или X Шестнадцатеричное число без знака

Эти спецификации типа основаны на изначально определенных доя функции printf в стандартной библиотеке C. Спецификации типов, используемые в строках сообщений инструкции RAISERROR , сопоставляются с типами данных языка Transact-SQL, а спецификации, используемые в функции printf , сопоставляются с типами данных языка C. Спецификации типов, используемые в функции printf , не поддерживаются инструкцией RAISERROR , если в языке Transact-SQL нет типов данных, схожих с соответствующими типами данных языка C. Например, спецификация %p для указателей не поддерживается инструкцией RAISERROR , так как в языке Transact-SQL нет типа данных для указателей.

Для преобразования какого-либо значения в тип данных Transact-SQL bigint нужно указать спецификацию %I64d.

@local_variable

Переменная любого допустимого типа данных для символов, содержащая строку того же формата, что и строка msg_str. Аргумент @local_variable должен иметь тип char или varchar, либо поддерживать неявное преобразование в эти типы данных.

severity

Определенный пользователем уровень серьезности, связанный с этим сообщением. Если при помощи аргумента msg_id вызываются определяемые пользователем сообщения, созданные процедурой sp_addmessage , то уровень серьезности, указанный в RAISERROR , заменяет уровень серьезности, указанный в процедуре sp_addmessage .

Для степеней серьезности от 19 до 25 требуется параметр WITH LOG. Степени серьезности меньше 0 интерпретируются как 0. Степени серьезности больше 25 интерпретируются как 25.

Уровни серьезности от 20 до 25 считаются неустранимыми. Если обнаруживается неустранимый уровень серьезности, то после получения сообщения соединение с клиентом обрывается и регистрируется сообщение об ошибке в журналах приложений и ошибок.

Можно указать -1 , чтобы получить степень серьезности, связанную с ошибкой, как показано в следующем примере.

state

Целое число от 0 до 255. Для отрицательных значений по умолчанию используется 1. Значения больше 255 использовать не следует.

Если одна и та же пользовательская ошибка возникает в нескольких местах, то при помощи уникального номера состояния для каждого местоположения можно определить, в каком месте кода появилась ошибка.

argument

Параметры, использующиеся при подстановке для переменных, определенных в msg_str, или для сообщений, соответствующих аргументу msg_id. Число параметров подстановки может быть от 0 и более, при этом общее количество параметров подстановки не может превышать 20. Каждый параметр подстановки может быть локальной переменной или любым из этих типов данных: tinyint, smallint, int, char, varchar, nchar, nvarchar, binary или varbinary. Другие типы данных не поддерживаются.

Параметр

Настраиваемый параметр для ошибки может принимать одно из значений, находящихся в следующей таблице.

Значение Описание
LOG Записывает сообщения об ошибках в журнал ошибок и журнал приложения экземпляра компонента Microsoft SQL Server Компонент Database Engine. Сообщения об ошибках в журнале ошибок ограничены размером в 440 байт. Только члены предопределенной роли сервера sysadmin или пользователи с разрешениями ALTER TRACE могут указывать ключевое слово WITH LOG.

Применяется к: SQL Server

NOWAIT Немедленно посылает сообщения клиенту.

Применимо к: SQL Server, База данных SQL

SETERROR Устанавливает значения параметров @@ERROR и ERROR_NUMBER равными msg_id или 50000, независимо от уровня серьезности.

Применимо к: SQL Server, База данных SQL

Ошибки, созданные инструкцией RAISERROR , аналогичны ошибкам, созданным кодом компонента «Ядро СУБД». Значения, указанные RAISERROR , передаются системными функциями ERROR_LINE , ERROR_MESSAGE , ERROR_NUMBER , ERROR_PROCEDURE , ERROR_SEVERITY , ERROR_STATE и @@ERROR . Если инструкция RAISERROR с уровнем серьезности 11 или выше выполняется в блоке TRY, управление передается соответствующему блоку CATCH . Ошибка возвращается вызывающему объекту, если инструкция RAISERROR вызывается:

за пределами области любого блока TRY ;

с уровнем серьезности, равным 10 и менее в блоке TRY ;

с уровнем серьезности, равным 20 и выше, что приводит к обрыву подключения к базе данных.

В блоках CATCH инструкция RAISERROR может использоваться для передачи сообщения об ошибке, вызывающего блок CATCH , во время получения исходных сведений об ошибке при помощи таких системных функций, как ERROR_NUMBER и ERROR_MESSAGE . По умолчанию для сообщений с серьезностью от 1 до 10 параметр @@ERROR устанавливается в значение 0.

Если при помощи аргумента msg_id задано определяемое пользователем сообщение, доступное в представлении каталога sys.messages, RAISERROR обрабатывает сообщение из текстового столбца при помощи тех же правил, которые применялись к тексту определяемого пользователем сообщения, заданного аргументом msg_str. Текст сообщения, определяемого пользователем, может содержать спецификации преобразования, а RAISERROR сопоставит значения аргументов данным спецификациям преобразования. Процедура sp_addmessage позволяет добавить пользовательские сообщения об ошибках, процедура sp_dropmessage — удалять их.

Инструкция RAISERROR может использоваться в качестве альтернативы инструкции PRINT для возвращения сообщений вызывающим приложениям. Инструкция RAISERROR поддерживает функцию подстановки символов, сходную с функцией printf стандартной библиотеки языка С, которая отличается от инструкции Transact-SQL PRINT . Инструкция PRINT не зависит от блоков TRY , в то время как инструкция RAISERROR , выполняемая с уровнем серьезности от 11 до 19 в блоке TRY, передает управление процессом соответствующему блоку CATCH . Задайте уровень серьезности, равный 10 или меньше, чтобы инструкция RAISERROR возвращала сообщения из блока TRY без вызова блока CATCH .

Обычно последовательные аргументы заменяют последовательные спецификации преобразования; первый аргумент заменяет первую спецификацию преобразования, второй аргумент заменяет вторую спецификацию преобразования и так далее. Например, в следующей инструкции RAISERROR первый аргумент N’number’ подставляется на место первой спецификации преобразования %s , а второй аргумент 5 — на место второй спецификации преобразования %d. .

Если в качестве ширины или точности спецификации преобразования задан символ «звездочка» ( * ), то используемое для ширины или для точности значение определяется как значение аргумента целого типа. В этом случае одна спецификация преобразования может использоваться до трех аргументов — для значений ширины, точности и подстановки.

Например, каждая из следующих инструкций RAISERROR возвращает одну и ту же строку. Одна определяет значения ширины и точности в списке аргументов, другая определяет их в спецификации преобразования.

Разрешения

Степень серьезности от 0 до 18 может указать любой пользователь. Уровни серьезности от 19 до 25 могут быть указаны только членами предопределенной роли сервера sysadmin и пользователями с разрешениями ALTER TRACE.

Примеры

A. Возвращение сведений об ошибке из блока CATCH

Следующий пример кода показывает, как можно использовать инструкцию RAISERROR внутри блока TRY , чтобы передать управление блоку CATCH . Также в этом примере показано, каким образом для возвращения сведений об ошибке используется инструкция RAISERROR , которая вызывает блок CATCH .

Инструкция RAISERROR может формировать только ошибки с состоянием от 1 до 127 включительно. Так как компонент «Ядро СУБД» может вызывать ошибки с состоянием 0, рекомендуется проверять состояние ошибки, возвращаемое функцией ERROR_STATE, перед передачей его по значению в виде параметра состояния для RAISERROR .

Б. Создание нерегламентированного сообщения в представлении каталога sys.messages

В следующем примере показано, как инициировать сообщение, хранящееся в представлении каталога sys.messages. Это сообщение было добавлено в представление каталога sys.messages при помощи системной хранимой процедуры sp_addmessage как сообщение с номером 50005 .

В. Использование локальной переменной для предоставления текста сообщения

В следующем примере кода показано, как использовать локальную переменную для предоставления текста сообщения для инструкции RAISERROR .

Источник

Содержание

  • 1 Raise error in case of error
  • 2 Raise error out of a procedure
  • 3 Raise exception with parameters
  • 4 RAISERROR ( -1, @parm1, @parm2)
  • 5 RAISERROR syntax
  • 6 Raising a message not defined in sysmessages.
  • 7 The syntax of the RAISERROR statement: RAISERROR ({message_id|message_string}, severity, state [, argument]…)
  • 8 Using RAISERROR without an Error Number
  • 9 Using RAISERROR with the SETERROR Option

Raise error in case of error

   <source lang="sql">

6> DECLARE @sql AS NVARCHAR(4000),
7> @b AS VARBINARY(1000), @s AS VARCHAR(2002);
8> SET @s = «0x0123456789abcdef»;
9>
10> IF @s NOT LIKE «0x%» OR @s LIKE «0x%[^0-9a-fA-F]%»
11> BEGIN
12> RAISERROR(«Possible SQL Injection attempt.», 16, 1);
13> RETURN;
14> END
15>
16> SET @sql = N»SET @o = » + @s + N»;»;
17> EXEC sp_executesql
18> @stmt = @sql,
19> @params = N»@o AS VARBINARY(1000) OUTPUT»,
20> @o = @b OUTPUT;
21>
22> SELECT @b;
23> GO




0x0123456789ABCDEF

1>
2></source>

Raise error out of a procedure

   <source lang="sql">

13> create table Billings (
14> BankerID INTEGER,
15> BillingNumber INTEGER,
16> BillingDate datetime,
17> BillingTotal INTEGER,
18> TermsID INTEGER,
19> BillingDueDate datetime ,
20> PaymentTotal INTEGER,
21> CreditTotal INTEGER
22>
23> );
24> GO
1>
2> INSERT INTO Billings VALUES (1, 1, «2005-01-22″, 165, 1,»2005-04-22»,123,321);
3> GO
(1 rows affected)
1> INSERT INTO Billings VALUES (2, 2, «2001-02-21″, 165, 1,»2002-02-22»,123,321.);
2> GO
(1 rows affected)
1> INSERT INTO Billings VALUES (3, 3, «2003-05-02″, 165, 1,»2005-04-12»,123,321);
2> GO
(1 rows affected)
1> INSERT INTO Billings VALUES (4, 4, «1999-03-12″, 165, 1,»2005-04-18»,123,321);
2> GO
(1 rows affected)
1> INSERT INTO Billings VALUES (5, 5, «2000-04-23″, 165, 1,»2005-04-17»,123,321);
2> GO
(1 rows affected)
1> INSERT INTO Billings VALUES (6, 6, «2001-06-14″, 165, 1,»2005-04-18»,123,321);
2> GO
(1 rows affected)
1> INSERT INTO Billings VALUES (7, 7, «2002-07-15″, 165, 1,»2005-04-19»,123,321);
2> GO
(1 rows affected)
1> INSERT INTO Billings VALUES (8, 8, «2003-08-16″, 165, 1,»2005-04-20»,123,321);
2> GO
(1 rows affected)
1> INSERT INTO Billings VALUES (9, 9, «2004-09-17″, 165, 1,»2005-04-21»,123,321);
2> GO
(1 rows affected)
1> INSERT INTO Billings VALUES (0, 0, «2005-10-18″, 165, 1,»2005-04-22»,123,321);
2> GO
(1 rows affected)
1>
2>
3> CREATE PROC spInsertBilling
4> @BankerID int, @BillingNumber varchar(50),
5> @BillingDate smalldatetime, @BillingTotal money,
6> @TermsID int, @BillingDueDate smalldatetime
7> AS
8> IF EXISTS(SELECT * FROM Billings WHERE BankerID = @BankerID)
9> BEGIN
10> INSERT Billings (BankerID)
11> VALUES (@BankerID)
12> END
13> ELSE
14> BEGIN
15> RAISERROR(«Not a valid BankerID!»,1,1)
16> RETURN -100
17> END
18> GO
1>
2>
3> DECLARE @ReturnVar int
4> EXEC @ReturnVar = spInsertBilling
5> 799,»ZXK-799″,»2002-07-01″,299.95,1,»2001-08-01″
6> PRINT «Return code was: » + CONVERT(varchar,@ReturnVar)
7> GO
Not a valid BankerID!
Return code was: -100
1>
2> drop PROC spInsertBilling;
3> GO
1>
2>
3> drop table Billings;
4> GO</source>

Raise exception with parameters

   <source lang="sql">

6> DECLARE @ProductId INT
7> SET @ProductId = 100
8>
9>
10> RAISERROR(«Problem with ProductId %i», 16, 1, @ProductId)
11> GO
Msg 50000, Level 16, State 1, Server JSQLEXPRESS, Line 10
Problem with ProductId 100
1></source>

RAISERROR ( -1, @parm1, @parm2)

   <source lang="sql">

28> DECLARE @parm1 varchar(30), @parm2 int
29> SELECT @parm1=USER_NAME(), @parm2=@@spid
30> RAISERROR (50001, 15, -1, @parm1, @parm2)
31> GO
Msg 50001, Level 15, State 1, Server JSQLEXPRESS, Line 30
The specified value for dbo was invalid.
1></source>

RAISERROR syntax

   <source lang="sql">

RAISERROR ({msg_id | msg_str}, severity, state[, argument1
[, argumentn]])
[WITH LOG]|[WITH NOWAIT]
RAISERROR Options Value Description
LOG Logs the error in the SQL Server error log and the application log.
NOWAIT Sends messages immediately to the client.
SETERROR Sets @@ERROR value to msg_id or 50000, regardless of the severity level.</source>

Raising a message not defined in sysmessages.

   <source lang="sql">

6> DECLARE @chrPrintMsg CHAR(255)
7>
8> RAISERROR(«Undefined error raised using the WITH SETERROR option»,1,2) WITH SETERROR
9>
10> SELECT @chrPrintMsg = «Using WITH SETERROR sets the error number generated to » + CONVERT(char,@@error)
11> PRINT @chrPrintMsg
12> GO
Undefined error raised using the WITH SETERROR option
Using WITH SETERROR sets the error number generated to 50000</source>

The syntax of the RAISERROR statement: RAISERROR ({message_id|message_string}, severity, state [, argument]…)

   <source lang="sql">

13> create table Billings (
14> BankerID INTEGER,
15> BillingNumber INTEGER,
16> BillingDate datetime,
17> BillingTotal INTEGER,
18> TermsID INTEGER,
19> BillingDueDate datetime ,
20> PaymentTotal INTEGER,
21> CreditTotal INTEGER
22>
23> );
24> GO
1>
2> INSERT INTO Billings VALUES (1, 1, «2005-01-22″, 165, 1,»2005-04-22»,123,321);
3> GO
(1 rows affected)
1> INSERT INTO Billings VALUES (2, 2, «2001-02-21″, 165, 1,»2002-02-22»,123,321.);
2> GO
(1 rows affected)
1> INSERT INTO Billings VALUES (3, 3, «2003-05-02″, 165, 1,»2005-04-12»,123,321);
2> GO
(1 rows affected)
1> INSERT INTO Billings VALUES (4, 4, «1999-03-12″, 165, 1,»2005-04-18»,123,321);
2> GO
(1 rows affected)
1> INSERT INTO Billings VALUES (5, 5, «2000-04-23″, 165, 1,»2005-04-17»,123,321);
2> GO
(1 rows affected)
1> INSERT INTO Billings VALUES (6, 6, «2001-06-14″, 165, 1,»2005-04-18»,123,321);
2> GO
(1 rows affected)
1> INSERT INTO Billings VALUES (7, 7, «2002-07-15″, 165, 1,»2005-04-19»,123,321);
2> GO
(1 rows affected)
1> INSERT INTO Billings VALUES (8, 8, «2003-08-16″, 165, 1,»2005-04-20»,123,321);
2> GO
(1 rows affected)
1> INSERT INTO Billings VALUES (9, 9, «2004-09-17″, 165, 1,»2005-04-21»,123,321);
2> GO
(1 rows affected)
1> INSERT INTO Billings VALUES (0, 0, «2005-10-18″, 165, 1,»2005-04-22»,123,321);
2> GO
(1 rows affected)
1>
2>
3> CREATE PROC spInsertBilling
4> @BankerID int, @BillingNumber varchar(50),
5> @BillingDate smalldatetime, @BillingTotal money,
6> @TermsID int, @BillingDueDate smalldatetime
7> AS
8> IF EXISTS(SELECT * FROM Bankers WHERE BankerID = @BankerID)
9> BEGIN
10> INSERT Billings (BankerID)
11> VALUES (@BankerID)
12> END
13> ELSE
14> BEGIN
15> RAISERROR(«Not a valid BankerID!»,1,1)
16> RETURN -100
17> END
18> GO
1>
2>
3> drop PROC spInsertBilling;
4> GO
1>
2>
3> drop table Billings;
4> GO</source>

Using RAISERROR without an Error Number

   <source lang="sql">

3>
4> RAISERROR («we have a problem.», 16, 1)
5></source>

Using RAISERROR with the SETERROR Option

   <source lang="sql">

6> sp_addmessage
7> 60000,
8> 16,
9> «Unable to find ID %09d»
10> GO
Msg 15043, Level 16, State 1, Server BCE67B1242DE45ASQLEXPRESS, Procedure sp_addmessage, Line 137
You must specify «REPLACE» to overwrite an existing message.
1>
2>
3> RAISERROR (60000, 1, 2)
4> SELECT @@ERROR
5> GO
Unable to find ID (null)


         0

(1 rows affected)
1> RAISERROR (60000, 1, 2) WITH SETERROR
2> SELECT @@ERROR
3>
4> sp_dropmessage
5> 60000
6> GO
Msg 102, Level 15, State 1, Server BCE67B1242DE45ASQLEXPRESS, Line 5
Incorrect syntax near «60000».
1></source>

When something goes wrong in your T-SQL, you want to fix the problem quickly with minimal digging around and disruption to users. SQL Server-generated error messages are highly technical and hard to understand, which can make it difficult to isolate issues and can slow down resolution time. Fortunately, DBAs can implement SQL Server RAISERROR as an alternative to SQL Server error messages.

RAISERROR is a SQL Server error handling statement that generates an error message and initiates error processing. RAISERROR can either reference a user-defined message that is stored in the sys.messages catalog view or it can build a message dynamically. The message is returned as a server error message to the calling application or to an associated CATCH block of a TRY…CATCH construct.

There are several scenarios in which it’s appropriate to use the RAISERROR statement:

  • Transact-SQL code troubleshooting
  • Returning messages that contain variable text
  • Examining data values
  • When you need the execution to jump from a TRY block to the associated CATCH block or return error information from the CATCH block to the callers

It’s important to note that when developing new applications, a THROW statement is now preferable to RAISERROR for error handling. But more on that later.

Why Use RAISERROR for SQL Server Error Handling?

There are two primary reasons for choosing RAISERROR over SQL Server-generated error handling:

  1. The RAISERROR messages are customizable with regard to level of severity and state
  2. They can be written in natural language that is easy to understand

RAISERROR returns error messages to the application in the same format that is generated by SQL Server Database Engine. It allows developers to generate their own error messages, so anyone reading the message will be able to understand what the actual problem is instead of trying to decipher SQL Server’s technical error message. Developers can also set their own severity level, message ID, and state for error messages. 

Using RAISERROR with the TRY…CATCH Construct

TRY…CATCH is an error handling construct that lets you execute code in the TRY section and handle errors in the CATCH section. In general, TRY…CATCH is an effective way to identify many T-SQL errors, but there are a few exceptions. 

This tutorial provides a detailed walkthrough of how to use RAISERROR in conjunction with TRY…CATCH. The author uses an example showing how to use the RAISERROR inside a TRY block to cause execution to jump to the associated CATCH block. Inside the CATCH block, the author demonstrates how to use the RAISERROR to return the error information that invoked the CATCH block. The output displays the message ID, level of severity, and error state.

RAISERROR vs. THROW Error Handling Statements

RAISERROR was introduced in SQL Server 7.0 and has been an effective way to handle T-SQL errors for many years. But if you are developing new apps, Microsoft now recommends using THROW statements instead of RAISERROR. 

As organizations update to SQL Server 2012 and above, RAISERROR is being phased out. In fact, RAISERROR can’t be used in SQL Server 2014’s natively compiled Stored Procedures. THROW is considered an improvement over RAISERROR because it is easier to use. 

Microsoft’s SQL Server documentation breaks down the differences between the RAISERROR and THROW error handling statements as follows:

RAISERROR statement

  • If a msg_id is passed to RAISERROR, the ID must be defined in sys.messages.
  • The msg_str parameter can contain printf formatting styles.

The severity parameter specifies the severity of the exception.

THROW statement

  • The error_number parameter does not have to be defined in sys.messages.
  • The message parameter does not accept printf style formatting.
  • There is no severity parameter. The exception severity is always set to 16.

Although RAISERROR’s days may be numbered, it remains a viable error handling option on older versions of SQL Server. Microsoft is pushing users of newer versions of SQL Server (SQL SERVER 2012 and above) to use the THROW statement instead of RAISERROR for implementing error handling. Microsoft hasn’t announced RAISERROR deprecation yet, but it seems likely that it will sooner rather than later.

SQL Server performance monitoring with the power of the cloud.

Понравилась статья? Поделить с друзьями:
  • Msado15 dll как исправить ошибку
  • Mssql error unable to connect using the connection information provided retry profile creation
  • Mssql error number 18456
  • Mssql error message
  • Mssql error converting data type varchar to numeric