例子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可以?谢谢!