如何使用try,throw和catch在错误处理中打印消息

时间:2012-09-07 11:51:00

标签: sql-server-2008 error-handling

我想在我的查询中打印一条消息(“雇主在数据库中不存在”)。

我的查询是:

create proc sp_emprecord
as 
begin
    select * from employe
end

begin try
    execute sp_emprecord
end try

begin catch
    select
    error_message() as errormessage,
    error_number() as erronumber,
    error_state() as errorstate,
    error_procedure() as errorprocedure,
    error_line() as errorline;
 end catch

1 个答案:

答案 0 :(得分:9)

试试这个:

create proc sp_emprecord
as 
begin
    select * from employe
end
go
begin try
    execute sp_emprecord
end try

begin catch
    if(ERROR_NUMBER() = 208)
        RAISERROR ('The table employe is not exist in database', 0, 1) WITH NOWAIT;
    else
        select
        error_message() as errormessage,
        error_number() as erronumber,
        error_state() as errorstate,
        error_procedure() as errorprocedure,
        error_line() as errorline;
 end catch