Top 17 Mssql Raiserror Top Answer Update

You are looking for information, articles, knowledge about the topic nail salons open on sunday near me mssql raiserror on Google, you do not find the information you need! Here are the best content compiled and compiled by the https://chewathai27.com/to team, along with other related topics such as: mssql raiserror SQL RAISERROR stored procedure, IF…ELSE in function SQL Server, Error number in sql server, THROW SQL Server, Sql server raiserror does not stop execution, RAISERROR 16 1, Raiserror state sql, Sql server raiserror datetime


Raiserror in SQL Server
Raiserror in SQL Server


RAISERROR (Transact-SQL) – SQL Server | Microsoft Docs

  • Article author: docs.microsoft.com
  • Reviews from users: 20498 ⭐ Ratings
  • Top rated: 3.9 ⭐
  • Lowest rated: 1 ⭐
  • Summary of article content: Articles about RAISERROR (Transact-SQL) – SQL Server | Microsoft Docs RAISERROR can be used as an alternative to PRINT to return messages to calling applications. RAISERROR supports character substitution similar … …
  • Most searched keywords: Whether you are looking for RAISERROR (Transact-SQL) – SQL Server | Microsoft Docs RAISERROR can be used as an alternative to PRINT to return messages to calling applications. RAISERROR supports character substitution similar … RAISERROR (Transact-SQL)
  • Table of Contents:

Syntax

Arguments

Remarks

Permissions

Examples

See Also

Feedback

RAISERROR (Transact-SQL) - SQL Server | Microsoft Docs
RAISERROR (Transact-SQL) – SQL Server | Microsoft Docs

Read More

Tìm hiểu về câu lệnh RAISERROR của SQL Server

  • Article author: www.vndba.net
  • Reviews from users: 23699 ⭐ Ratings
  • Top rated: 3.3 ⭐
  • Lowest rated: 1 ⭐
  • Summary of article content: Articles about Tìm hiểu về câu lệnh RAISERROR của SQL Server Câu lệnh RAISERROR được dùng để tạo một nội dung (thường là lỗi, nhưng cũng có thể là nội dung khác như debug) để trả về cho ứng dụng. Nội dung … …
  • Most searched keywords: Whether you are looking for Tìm hiểu về câu lệnh RAISERROR của SQL Server Câu lệnh RAISERROR được dùng để tạo một nội dung (thường là lỗi, nhưng cũng có thể là nội dung khác như debug) để trả về cho ứng dụng. Nội dung … Bài viết này sẽ giúp chúng ta có cái nhìn tổng quan về câu lệnh RAISERROR trong SQL Server. Ngoài ra chúng ta sẽ có một vài ví dụ để có thể áp dụng câu lệnh này vào code một cách hiệu quả nhất.
  • Table of Contents:

Giới thiệu

Cú pháp

Sử dụng định danh của mẫu có sẵn trong SQL Server

Sử dụng nội dung tự chọn

Sử dụng biến làm đầu vào

Độ nghiêm trọng severity và tình trạng state của thông báo lỗi

Định nghĩa và sử dụng tham số nhúng

Tùy chọn bổ sung WITH NOWAIT

Lời kết

Tìm hiểu về câu lệnh RAISERROR của SQL Server
Tìm hiểu về câu lệnh RAISERROR của SQL Server

Read More

sql – What is the syntax meaning of RAISERROR() – Stack Overflow

  • Article author: stackoverflow.com
  • Reviews from users: 37245 ⭐ Ratings
  • Top rated: 3.7 ⭐
  • Lowest rated: 1 ⭐
  • Summary of article content: Articles about sql – What is the syntax meaning of RAISERROR() – Stack Overflow It is the severity level of the error . The levels are from 11 – 20 which throw an error in SQL . The higher the level, the more severe the … …
  • Most searched keywords: Whether you are looking for sql – What is the syntax meaning of RAISERROR() – Stack Overflow It is the severity level of the error . The levels are from 11 – 20 which throw an error in SQL . The higher the level, the more severe the …
  • Table of Contents:

5 Answers
5

Your Answer

Not the answer you’re looking for Browse other questions tagged sql sql-server database sql-server-2008 sql-server-2008-r2 or ask your own question

sql - What is the syntax meaning of RAISERROR() - Stack Overflow
sql – What is the syntax meaning of RAISERROR() – Stack Overflow

Read More

SQL RAISERROR Statement with Simple Examples

  • Article author: codingsight.com
  • Reviews from users: 43160 ⭐ Ratings
  • Top rated: 4.5 ⭐
  • Lowest rated: 1 ⭐
  • Summary of article content: Articles about SQL RAISERROR Statement with Simple Examples The SQL RAISERROR statement is used to send a custom message to the client application. It also can be used to debug the application and … …
  • Most searched keywords: Whether you are looking for SQL RAISERROR Statement with Simple Examples The SQL RAISERROR statement is used to send a custom message to the client application. It also can be used to debug the application and … Article explores SQL RAISERROR statement, demonstrates its usage on examples as well as clarifies usage of sp_addmessage and sp_dropmessage SPs
  • Table of Contents:

SQL RAISERROR Statement Syntax and Parameters

Example 1 Use SQL Server RAISERROR Statement to Print the Output

Example 2 SQL RAISERROR Statement with the Dynamic Message Text

Use SQL RAISERROR in TRYCATCH Block

sp_addmessage Stored Procedure

How to Use User-defined Error Messages

sp_dropmessage Stored Procedure

Summary

How to Read and Interpret SQL Errors

SQL BETWEEN-Smart Tips to Scan for a Range of Values

SQL Server ROUND() Function What It’s For and Why Should You Care

SQL AS Usage Examples and How it Can Benefit You Best

SQL RAISERROR Statement with Simple Examples
SQL RAISERROR Statement with Simple Examples

Read More

Ý nghĩa cú pháp của RAISERROR ()

  • Article author: helpex.vn
  • Reviews from users: 41549 ⭐ Ratings
  • Top rated: 4.8 ⭐
  • Lowest rated: 1 ⭐
  • Summary of article content: Articles about Ý nghĩa cú pháp của RAISERROR () Đây là mức độ nghiêm trọng của error . Các cấp độ từ 11 – 20 sẽ xảy ra lỗi SQL . Càng lên cao, mức độ càng nặng và transaction cần phải bỏ … …
  • Most searched keywords: Whether you are looking for Ý nghĩa cú pháp của RAISERROR () Đây là mức độ nghiêm trọng của error . Các cấp độ từ 11 – 20 sẽ xảy ra lỗi SQL . Càng lên cao, mức độ càng nặng và transaction cần phải bỏ … Tôi vừa tạo một Trình kích hoạt Thay thế Sau khi có cú pháp như sau: Create trigger tgrInsteadTrigger on copytableto Instead of Insert as Declare @store_name varchar(30); declare @sales int;…sql, sql server, database, sql server 2008, sql-server-2008-r2
  • Table of Contents:
Ý nghĩa cú pháp của RAISERROR ()
Ý nghĩa cú pháp của RAISERROR ()

Read More

RAISERROR statement [T-SQL]

  • Article author: infocenter.sybase.com
  • Reviews from users: 46465 ⭐ Ratings
  • Top rated: 3.4 ⭐
  • Lowest rated: 1 ⭐
  • Summary of article content: Articles about RAISERROR statement [T-SQL] The RAISERROR statement allows user-defined errors to be signaled, and sends a message on the client. The error-number is a 5-digit integer greater than 17000. …
  • Most searched keywords: Whether you are looking for RAISERROR statement [T-SQL] The RAISERROR statement allows user-defined errors to be signaled, and sends a message on the client. The error-number is a 5-digit integer greater than 17000.
  • Table of Contents:
RAISERROR statement [T-SQL]
RAISERROR statement [T-SQL]

Read More

SQL Server – Xử lý ngoại lệ trong T-SQL – hoadm.net

  • Article author: hoadm.net
  • Reviews from users: 13751 ⭐ Ratings
  • Top rated: 3.9 ⭐
  • Lowest rated: 1 ⭐
  • Summary of article content: Articles about SQL Server – Xử lý ngoại lệ trong T-SQL – hoadm.net Tuy nhiên, chúng ta hãy cùng xem qua, cách mà T-SQL hiện thực chúng. Mục lục. 1. TRY – CATCH. 2. RAISERROR. …
  • Most searched keywords: Whether you are looking for SQL Server – Xử lý ngoại lệ trong T-SQL – hoadm.net Tuy nhiên, chúng ta hãy cùng xem qua, cách mà T-SQL hiện thực chúng. Mục lục. 1. TRY – CATCH. 2. RAISERROR. Trong một vài trường hợp, logic của câu truy vấn sẽ bị sai lệch, ảnh hưởng đến toàn bộ hệ thống. SQL cung cấp cho chúng ta một số câu lệnh để xử lý ngoại lệ
  • Table of Contents:

TRY – CATCH

RAISERROR

THROW

SQL Server - Xử lý ngoại lệ trong T-SQL - hoadm.net
SQL Server – Xử lý ngoại lệ trong T-SQL – hoadm.net

Read More

SQL Server RAISERROR Statement

  • Article author: linuxhint.com
  • Reviews from users: 21046 ⭐ Ratings
  • Top rated: 3.6 ⭐
  • Lowest rated: 1 ⭐
  • Summary of article content: Articles about SQL Server RAISERROR Statement The RAISERROR statement in SQL Server allows you to generate and display user-defined error messages. Using the RAISERROR statement, you can create … …
  • Most searched keywords: Whether you are looking for SQL Server RAISERROR Statement The RAISERROR statement in SQL Server allows you to generate and display user-defined error messages. Using the RAISERROR statement, you can create … This article provides a guide on using the RAISERROR Statement in the SQL Server. This tutorial highlights using the RAISERROR statement to generate custom error messages in the SQL Server and displaying in your applications. This includes creating ad-hoc messages with the sp_addmessage procedure and using RAISERROR in Try/Catch Block.
  • Table of Contents:

Create Ad Hoc Messages With the sp_addmessage Procedure

RAISERROR Statement in TryCatch Block

Conclusion

SQL Server RAISERROR Statement
SQL Server RAISERROR Statement

Read More

SQL Syntax Error -RAISERROR – MariaDB Knowledge Base

  • Article author: mariadb.com
  • Reviews from users: 49205 ⭐ Ratings
  • Top rated: 4.5 ⭐
  • Lowest rated: 1 ⭐
  • Summary of article content: Articles about SQL Syntax Error -RAISERROR – MariaDB Knowledge Base SQL Syntax Error -RAISERROR. I’m trying to create a trigger which raises an error when old password and new password are equal when updating it. …
  • Most searched keywords: Whether you are looking for SQL Syntax Error -RAISERROR – MariaDB Knowledge Base SQL Syntax Error -RAISERROR. I’m trying to create a trigger which raises an error when old password and new password are equal when updating it. I’m trying to create a trigger which raises an error when old password and new password are equal when updating it. However, I keep getting this error :
    #1064 – You have an er…
  • Table of Contents:

Answer
Answered by

Ian Gilfillan
in this comment

Comments

SQL Syntax Error -RAISERROR - MariaDB Knowledge Base
SQL Syntax Error -RAISERROR – MariaDB Knowledge Base

Read More


See more articles in the same category here: Chewathai27.com/to/blog.

RAISERROR (Transact-SQL) – SQL Server

Table of contents

RAISERROR (Transact-SQL)

Article

05/27/2022

11 minutes to read

19 contributors

In this article

Applies to: SQL Server (all supported versions) Azure SQL Database Azure SQL Managed Instance Azure Synapse Analytics Analytics Platform System (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.

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 ] ]

Note To view Transact-SQL syntax for SQL Server 2014 and earlier, see Previous versions documentation.

Arguments

msg_id

Is 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

Is 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

Is 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

Is 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

Is 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

Is 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

Note 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 Transact-SQL 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 Transact-SQL 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 Transact-SQL does not have a pointer data type.

Note To convert a value to the Transact-SQL 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

Is 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’);

Here is the result set.

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

state

Is 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

Are 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

Is 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 Microsoft SQL Server Database Engine. 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.

Applies to: SQL Server, SQL Database NOWAIT Sends messages immediately to the client.

Applies to: SQL Server, SQL Database SETERROR Sets the @@ERROR and ERROR_NUMBER values to msg_id or 50000, regardless of the severity level.

Applies to: SQL Server, SQL Database

Remarks

The errors generated by RAISERROR operate the same as errors generated by the Database Engine 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 Transact-SQL 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 Database Engine 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 .

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 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)

Tìm hiểu về câu lệnh RAISERROR của SQL Server

Ảnh chụp bởi Camylla Battani / Unsplash

Các bạn có thể xem tài liệu chính thức về câu lệnh RAISERROR của Microsoft tại đây.

Giới thiệu

Câu lệnh RAISERROR được dùng để tạo một nội dung (thường là lỗi, nhưng cũng có thể là nội dung khác như debug) để trả về cho ứng dụng. Nội dung này có thể được bắt bởi câu lệnh TRY…CATCH hoặc trả về trực tiếp cho ứng dụng đang kết nối vào SQL Server.

Nếu ứng dụng là SSMS thì nội dung này sẽ nằm trong tab Messages.

Cú pháp

RAISERROR ( { msg_id | msg_str | @local_variable } { ,severity ,state } [ ,argument [ ,…n ] ] ) [ WITH option [ ,…n ] ] Cú pháp câu lệnh RAISERROR (nguồn: Microsoft)

Như có thể thấy trong cú pháp này, RAISERROR nhận 1 trong 3 loại đầu vào cho tham số đầu tiên:

msg_id – là số định danh của mẫu câu có sẵn được lưu trong SQL Server

– là số định danh của mẫu câu có sẵn được lưu trong SQL Server msg_str – là nội dung tự chọn mà bạn mong muốn được xuất ra bởi RAISERROR

– là nội dung tự chọn mà bạn mong muốn được xuất ra bởi @local_variable – là biến của ngôn ngữ T-SQL, có thể là số (tương ứng với msg_id ) hoặc chuỗi (tương ứng với msg_str )

Sử dụng định danh của mẫu có sẵn trong SQL Server

Nếu tham số đầu tiên là số dưới dạng INT , SQL Server sẽ sử dụng con số này để lấy mẫu câu có sẵn được lưu trong bảng sys.messages để làm nội dung xuất ra cho RAISERROR .

Các bạn có thể đọc thêm tài liệu chính thức của Microsoft về bảng sys.messages tại đây.

Sử dụng mẫu của hệ thống

Mẫu có sẵn của hệ thống mà RAISERROR có thể dùng được có định danh nằm trong khoảng 13000 đến 49999 . Cụ thể, các bạn có thể sử dụng câu lệnh ở dưới để liệt kê các mẫu có sẵn của hệ thống.

SELECT * FROM sys.messages WHERE message_id BETWEEN 13000 AND 49999; Truy vấn danh sách mẫu có sẵn của hệ thống

Truy vấn danh sách mẫu có sẵn của hệ thống

Ví dụ, nếu bạn muốn lấy mẫu có định danh 14138 với tham số cho mẫu là Aha , bạn có thể sử dụng câu lệnh sau:

RAISERROR(14138, -1, -1, N’Aha’); Sử dụng RAISERROR với mẫu có sẵn của hệ thống

Sử dụng RAISERROR với mẫu có sẵn của hệ thống

Sử dụng mẫu tự tạo

Ngoài mẫu có sẵn của hệ thống, SQL Server cũng cho phép người dùng tự tạo mẫu cho riêng mình bằng cách sử dụng SP (stored procedure) sys.sp_addmessage (xem thêm).

Mẫu tự tạo mới bắt buộc phải sử dụng định danh từ 50001 trở lên và không trùng định danh với mẫu đã tạo trước đó.

SELECT * FROM sys.messages WHERE message_id > 50000; EXECUTE sys.sp_addmessage @msgnum = 50001 , @severity = 16 , @msgtext = N’vndba.net test error message – %s’ ; SELECT * FROM sys.messages WHERE message_id > 50000; Thêm mẫu tự tạo mới vào danh sách mẫu câu của SQL Server

Thêm mẫu tự tạo mới vào danh sách mẫu câu của SQL Server

Sau khi tạo mẫu thì chúng ta có thể sử dụng nó giống như là mẫu của hệ thống.

RAISERROR(50001, -1, -1, N’Aha’); Sử dụng RAISERROR với mẫu tự tạo

Sử dụng RAISERROR với mẫu tự tạo

Sử dụng nội dung tự chọn

Nếu tham số đầu tiên là chuỗi dưới dạng CHAR , NCHAR , VARCHAR hoặc NVARCHAR , SQL Server sẽ sử dụng chuỗi này để làm nội dung xuất ra cho RAISERROR .

RAISERROR chỉ hỗ trợ chuỗi với nội dung không quá 2047 ký tự. Nếu nội dung có số lượng ký tự từ 2048 trở lên, RAISERROR sẽ chỉ in ra 2044 ký tự và kết thúc bằng dấu ba chấm …

Khi sử dụng cách này, RAISERROR sẽ sử dụng định danh 50000 cho nội dung trả về.

RAISERROR(N’Custom message from vndba.net – %s’, 16, 1, N’Aha’); Sử dụng RAISERROR với nội dung tự chọn

Sử dụng RAISERROR với nội dung tự chọn

Sử dụng biến làm đầu vào

Nếu tham số đầu tiên là biến của T-SQL, thì tùy theo kiểu dữ liệu của biến là INT hay CHAR / NCHAR / VARCHAR / NVARCHAR mà RAISERROR sẽ xử lý tương ứng như đã trình bày ở trên.

Ví dụ nếu biến là định danh của mẫu:

DECLARE @input INT = 50001; RAISERROR(@input, -1, -1, N’Aha’); Sử dụng RAISERROR với biến là định danh của mẫu

Sử dụng RAISERROR với biến là định danh của mẫu

Và ví dụ nếu biến là nội dung tự chọn:

DECLARE @input NVARCHAR(MAX) = N’Custom message from vndba.net – %s’; RAISERROR(@input, 16, 1, N’Aha’); Sử dụng RAISERROR với biến là nội dung tự chọn

Sử dụng RAISERROR với biến là nội dung tự chọn

Độ nghiêm trọng severity và tình trạng state của thông báo lỗi

Mục tiêu của bài này là giới thiệu sơ bộ nên mình sẽ không đi sâu vào giải thích 2 thuộc tính này. Nếu có dịp mình sẽ trình bày trong một bài khác.

Tuy nhiên để có thể sử dụng RAISERROR theo ý muốn thì các bạn cũng nên có một cái nhìn sơ về 2 thuộc tính này.

Độ nghiêm trọng severity

Mỗi thông báo lỗi đều được gắn với một mức độ nghiêm trọng để SQL Server và ứng dụng có thể biết được để xử lý tương xứng. Cụ thể về severity các bạn có thể xem thêm tại đây.

Cơ bản thì mình quan tâm đến các giá trị sau của severity :

severity Cách sử dụng 0 | 10 Nội dung bình thường (không phải lỗi), và chỉ in nội dung.

Sử dụng cho nội dung thông báo bình thường (information). 1 ~ 9 Nội dung bình thường (không phải lỗi), và in đầy đủ thông tin.

Sử dụng cho nội dung debug. 16 Sử dụng cho lỗi tự tạo -1 Sử dụng giá trị mặc định của mẫu

Khi các bạn sử dụng SSMS thì toàn bộ nội dung mà RAISERROR tạo ra đều nằm trong tab Messages. Nội dung bình thường sẽ có màu đen còn nội dung lỗi sẽ có màu đỏ.

Tình trạng state

Gọi là tình trạng vậy thôi, chứ trên thực tế giá trị này được tạo ra để có thể xác định vị trí của lỗi một cách dễ dàng hơn bằng cách sử dụng các giá trị state khác nhau ở những đoạn code khác nhau.

state nhận giá trị từ 0 đến 255 , và mình cũng khuyến khích các bạn sử dụng giá trị trong khoảng này.

Ví dụ

RAISERROR(N’This message has severity [0] and state [0]’, 0, 0); PRINT ‘—‘; RAISERROR(N’This message has severity [1] and state [1]’, 1, 1); PRINT ‘—‘; RAISERROR(N’This message has severity [7] and state [7]’, 7, 7); PRINT ‘—‘; RAISERROR(N’This message has severity [16] and state [1]’, 16, 1); PRINT ‘—‘; RAISERROR(N’This message has severity [16] and state [255]’, 16, 255); PRINT ‘—‘; Sử dụng RAISERROR với các giá trị severity và state khác nhau

Sử dụng RAISERROR với các giá trị severity và state khác nhau

Định nghĩa và sử dụng tham số nhúng

Ở một vài ví dụ ở trên, các bạn có thể thấy mình sử dụng tham số cho mẫu hoặc nội dung bằng cách truyền giá trị tham số vào vị trí thứ 4 trong câu lệnh. Giá trị này thay thế cờ %s trong nội dung được in ra.

Sử dụng tham số nhúng bên trong nội dung của RAISERROR

Bạn có thể định nghĩa nhiều hơn một cờ trong nội dung, khi đó RAISERROR sẽ sử dụng các tham số ở vị trí tiếp theo để thay thế cho các cờ này.

Cấu trúc hoàn chỉnh của cờ khá là phức tạp, nên mình để dành nội dung này cho một bài khác. Trong bài này mình chỉ liệt kê ra các cờ thông dụng mà mình hay sử dụng và kiểu dữ liệu tương ứng có thể sử dụng cho cờ đó.

Cờ Kiểu dữ liệu có thể dùng %s CHAR NCHAR VARCHAR NVARCHAR %d INT %I64d BIGINT %#x BINARY VARBINARY %% In ra ký tự %

Điểm trừ lớn nhất của tham số nhúng là không hỗ trợ các kiểu dữ liệu thập phân như DECIMAL , FLOAT hay MONEY / SMALLMONEY . Tuy nhiên các bạn vẫn có thể dùng CAST hoặc CONVERT để chuyển dữ liệu thập phân về dạng chuỗi, sau đó sử dụng cờ %s để làm tham số nhúng.

DECLARE @s NVARCHAR(MAX) = N’Test string’ , @d INT = 12345 , @I64d BIGINT = 123456789012345 , @x VARBINARY(MAX) = 0x12345678 , @f DECIMAL(16,3) = 12345.678 , @fs NVARCHAR(MAX) ; SELECT @fs = CONVERT(NVARCHAR(MAX), @f); RAISERROR(N’\ Flag %%s – %s — Flag %%d – %d — Flag %%I64d – %I64d — Flag %%#x – %#x — Flag %%s for decimal – %s —‘, 0, 0, @s, @d, @I64d, @x, @fs); Sử dụng tham số nhúng trong RAISERROR

Sử dụng tham số nhúng trong RAISERROR

Tùy chọn bổ sung WITH NOWAIT

RAISERROR cho phép người dùng bổ sung thêm tùy chọn để thay đổi cách SQL Server xử lý câu lệnh. Trong bài này, mình chỉ đề cập đến tùy chọn được sử dụng nhiều nhất, cũng như là lý do chính mà mình sử dụng RAISERROR , đó là tùy chọn WITH NOWAIT .

Hãy lấy ví dụ sau làm minh họa cho tình huống thực tế (ví dụ như theo dõi tiến độ chạy của script):

RAISERROR(N’First message’, 0, 0); PRINT ‘—‘; RAISERROR(N’Second message’, 0, 0); PRINT ‘—‘; WAITFOR DELAY ’00:00:05′; RAISERROR(N’Final message after 5 seconds’, 0, 0); PRINT ‘—‘; RAISERROR không có tùy chọn

Trong đoạn code trên, mình đang muốn in ra nội dung First message và Second message , sau đó chờ 5 giây rồi mới in ra Final message after 5 seconds . Nhưng khi chạy đoạn code trên thì hoàn toàn không giống mong đợi:

RAISERROR không có tùy chọn

SSMS đợi hết 5 giây rồi mới in ra cả 3 nội dung. Sở dĩ có hành vi này là do SSMS sử dụng buffer cho nội dung trả về từ SQL Server. Cho đến khi truy vấn kết thúc hoặc buffer đầy (khoảng 8KB – xem thêm) thì SSMS mới in kết quả ra cho chúng ta. Điều này cũng áp dụng cho nội dung in ra từ câu lệnh PRINT .

May thay, RAISERROR cho phép chúng ta bật tùy chọn WITH NOWAIT để ngay lập tức in ra nội dung mà không cần phải đợi truy vấn kết thúc hay buffer đầy nữa. Hãy xem thử script của chúng ta có hành xử đúng như mong muốn sau khi thêm tùy chọn này hay không:

RAISERROR(N’First message’, 0, 0) WITH NOWAIT; PRINT ‘—‘; RAISERROR(N’Second message’, 0, 0) WITH NOWAIT; PRINT ‘—‘; WAITFOR DELAY ’00:00:05′; RAISERROR(N’Final message after 5 seconds’, 0, 0) WITH NOWAIT; PRINT ‘—‘; RAISERROR với tùy chọn WITH NOWAIT

RAISERROR với tùy chọn WITH NOWAIT

Tada. Ngay lập tức chúng ta nhận ra sự khác biệt. First message và Second message đều được in ra như mong đợi. Ngoài ra chúng ta cũng có thể thấy — của câu lệnh PRINT đầu tiên được in ra theo đúng thứ tự, nhưng — tiếp theo lại không được in ra. Điều này là do như đã nói ở trên, PRINT phải đợi truy vấn kết thúc hoặc khi buffer được giải phóng do đầy hoặc RAISERROR … WITH NOWAIT thì mới được in ra.

Chính vì cách hành xử của RAISERROR … WITH NOWAIT giống với mong đợi của mình nên mình luôn sử dụng tùy chọn này mỗi khi dùng RAISERROR .

Lời kết

Trên đây là toàn bộ những kiến thức cơ bản về câu lệnh RAISERROR mà mình tổng hợp lại. Hy vọng bài này có thể giúp các bạn biết và hiểu thêm về câu lệnh này, cũng như có thể áp dụng được RAISERROR (hay nói cách khác, RAISERROR … WITH NOWAIT ) vào công việc của các bạn.

Nếu có vấn đề gì thắc mắc liên quan đến chủ đề này, các bạn có thể liên hệ mình thông qua Facebook Messenger. Chúc các bạn một ngày làm việc vui vẻ ./.

An Essential Guide to SQL Server RAISERROR Statement

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.

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.

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(); 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, 16, 1, N’2001′ ); 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.

block to the associated block. Return error information from the CATCH block to the callers, either calling batch or application.

So you have finished reading the mssql raiserror topic article, if you find this article useful, please share it. Thank you very much. See more: SQL RAISERROR stored procedure, IF…ELSE in function SQL Server, Error number in sql server, THROW SQL Server, Sql server raiserror does not stop execution, RAISERROR 16 1, Raiserror state sql, Sql server raiserror datetime

Leave a Comment