【问题标题】:Finding objectid that faced with an error in a SQL Server try/catch block在 SQL Server try/catch 块中查找遇到错误的 objectid
【发布时间】:2012-08-27 00:02:24
【问题描述】:

我正在使用 try...catch 指令来处理 SQL Server 中的错误,我需要识别对象(例如,遇到错误的字段的代码),以便我可以显示自己的消息而不是默认消息系统错误信息。

这是我的存储过程:

USE [ArbitraryDB]    
GO
SET ANSI_NULLS ON    
GO    
SET QUOTED_IDENTIFIER ON    
GO

ALTER PROCEDURE [dbo].[CTInsert_UserSkills]    
(    
@UserID_int int, @SkillSN_int int, @Ordering_tinyint tinyint,     
@SkillLevelSN_tinyint tinyint, @SkillYearcount_tinyint tinyint    
)    
AS    
BEGIN    
SET NOCOUNT ON;

DECLARE @ErrorMessage varchar(200), @ErrorCode int    
BEGIN TRY

INSERT INTO CT_UserSkills (UserID_int, SkillSN_int, Ordering_tinyint,     
SkillLevelSN_tinyint, SkillYearcount_tinyint)    
VALUES (@UserID_int, @SkillSN_int, @Ordering_tinyint, @SkillLevelSN_tinyint,     
@SkillYearcount_tinyint)    
END TRY

BEGIN CATCH    
SELECT ERROR_MESSAGE()    
END CATCH

END 

这是输出:

Cannot insert duplicate key row in object 'dbo.CT_UserSkills' with unique index 'IX_CT_UserSkills'. The duplicate key value is (4, 1). 

但实际上我希望在以下错误消息的模式中找到 '%.*ls',系统消息中的代码为 2601:

Cannot insert duplicate key row in object '%.*ls' with unique index '%.*ls'. 
The duplicate key value is %ls. 

您能指导我找到那个 ('%.*ls') 吗?

【问题讨论】:

    标签: sql-server exception-handling try-catch sysobjects


    【解决方案1】:

    在存储过程中添加另一个 OUTPUT 参数:

    ALTER PROCEDURE [dbo].[CTInsert_UserSkills]    
    (    
    @UserID_int int, @SkillSN_int int, @Ordering_tinyint tinyint,     
    @SkillLevelSN_tinyint tinyint, @SkillYearcount_tinyint tinyint,    
    @ObjectID int OUTPUT
    ) 
    

    然后在您的 catch 块中,将此变量设置为您需要发送回调用程序的任何值。

    【讨论】:

    • 亲爱的Sam,这不是说如何向外界发送变量值,而是如何找到%.*ls.
    • 这就是“您需要发回的任何价值”。这是一个具体的事情,问题在于如何找到这个价值。
    • 你知道,仅仅因为你不明白答案就拒绝那些试图帮助你的人是非常粗鲁的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多