SQL Server 中 RAISERROR 的用法详细介绍 |
|
SQL Server 中 RAISERROR 的用法 raiserror 的作用: raiserror 是用于抛出一个错误 。[ 以下资料来源于sql server 2005的帮助 ] 其语法如下:
RAISERROR ( { msg_id | msg_str | @local_variable }
{ ,severity ,state }
[ ,argument [ ,...n ] ]
)
[ WITH option [ ,...n ] ]
简要说明一下: 第一个参数:{ msg_id | msg_str | @local_variable } msg_id:表示可以是一个sys.messages表中定义的消息代号; msg_str:表示也可以是一个用户定义消息,该错误消息最长可以有 2047 个字符; @local_variable:表示也可以是按照 msg_str 方式的格式化字符串变量 。 第二个参数:severity 用户定义的与该消息关联的严重级别 。(这个很重要) 第三个参数:state 如果在多个位置引发相同的用户定义错误, 第四个参数:argument 用于代替 msg_str 或对应于 msg_id 的消息中的定义的变量的参数 。 第五个参数:option 错误的自定义选项,可以是下表中的任一值: [SQL]代码示例 --示例1
DECLARE @raiseErrorCode nvarchar(50)
SET @raiseErrorCode = CONVERT(nvarchar(50), YOUR UNIQUEIDENTIFIER KEY)
RAISERROR('%s INVALID ID. There is no record in table',16,1, @raiseErrorCode)
--示例2
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
--示例3
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
--示例4
RAISERROR (N'<<%7.3s>>', -- Message text.
10, -- Severity,
1, -- State,
N'abcde'); -- First argument supplies the string.
-- The message text returned is: << abc>>.
GO
--示例5 --A. 从 CATCH 块返回错误消息 以下代码示例显示如何在 TRY 块中使用 RAISERROR 使执行跳至关联的 CATCH 块中 。
BEGIN TRY
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();
RAISERROR (@ErrorMessage, -- Message text.
@ErrorSeverity, -- Severity.
@ErrorState -- State.
);
END CATCH;
--示例6 --B. 在 sys.messages 中创建即席消息
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
--示例7 --C. 使用局部变量提供消息文本
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
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持! 您可能感兴趣的文章:
|