问题关于“错误处理”的问题

whulph 2007-04-29 04:07:15
例子A:
创建如下的存储过程:
use tempdb
go
create procedure p_testPrint
@s varchar(20)=null
as
declare @tempInt int
set @tempInt = @s
-- Test the error value.
IF @@ERROR <> 0
BEGIN
-- Return 99 to the calling program to indicate failure.
select getdate()
PRINT 'An error occurred loading the new author information'
RETURN(99)
END
ELSE
BEGIN
-- Return 0 to the calling program to indicate success.
PRINT 'The new author information has been loaded'
RETURN(0)
END

在查询分析器中输入以下批处理:
use tempdb
go
exec p_testPrint 'abc'
go
在“网格”窗口没有任何内容,在“消息”窗口出现以下信息:
服务器: 消息 245,级别 16,状态 1,过程 p_testPrint,行 8
将 varchar 值 'abc' 转换为数据类型为 int 的列时发生语法错误。
------------------------------------------------------------------------
例子B:
创建如下的存储过程(联机帮助中的一个例子,稍微改了一下)
USE pubs
GO

-- Create the procedure.
CREATE PROCEDURE add_author
@au_id varchar(11),@au_lname varchar(40),
@au_fname varchar(20),@phone char(12),
@address varchar(40) = NULL,@city varchar(20) = NULL,
@state char(2) = NULL,@zip char(5) = NULL,
@contract bit = NULL
AS

-- Execute the INSERT statement.
INSERT INTO authors
(au_id, au_lname, au_fname, phone, address,
city, state, zip, contract) values
(@au_id,@au_lname,@au_fname,@phone,@address,
@city,@state,@zip,@contract)

-- Test the error value.
IF @@ERROR <> 0
BEGIN
-- Return 99 to the calling program to indicate failure.
select getdate()
PRINT 'An error occurred loading the new author information'
RETURN(99)
END
ELSE
BEGIN
-- Return 0 to the calling program to indicate success.
PRINT 'The new author information has been loaded'
RETURN(0)
END
GO
然后运行以下批处理语句
exec add_author @au_id=3433,@au_lname=eer,@au_fname=dfdf,@phone=555
go
在“网格”窗口显示“ select getdate()”语句的结果,在“消息”窗口出现以下信息:
服务器: 消息 515,级别 16,状态 2,过程 add_author,行 12
无法将 NULL 值插入列 'contract',表 'Pubs.dbo.authors';该列不允许空值。INSERT 失败。
语句已终止。

(所影响的行数为 1 行)

An error occurred loading the new author information

-------------------------------------------------------------------------
我的问题是为什么例子A不能运行到“IF @@ERROR <> 0”而例子B可以?

谢谢!

...全文
159 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
wantop 2007-04-29
  • 打赏
  • 举报
回复
关注中
"...."

34,587

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧