D. 与 @@ROWCOUNT 一同使用 @@ERROR 下面的示例用 @@ERROR 和 @@ROWCOUNT 验证一条 UPDATE 语句的操作。为任何可能出现的错误而检验 @@ERROR 的值,而用 @@ROWCOUNT 保证更新已成功应用于表中的某行。USE pubs GO CREATE PROCEDURE change_publisher @title_id tid, @new_pub_id char(4) AS-- Declare variables used in error checking. DECLARE @error_var int, @rowcount_var int-- Execute the UPDATE statement. UPDATE titles SET pub_id = @new_pub_id WHERE title_id = @title_id -- Save the @@ERROR and @@ROWCOUNT values in local -- variables before they are cleared. SELECT @error_var = @@ERROR, @rowcount_var = @@ROWCOUNT-- Check for errors. If an invalid @new_pub_id was specified -- the UPDATE statement returns a foreign-key violation error #547. IF @error_var <> 0 BEGIN IF @error_var = 547 BEGIN PRINT "ERROR: Invalid ID specified for new publisher" RETURN(1) END ELSE BEGIN PRINT "ERROR: Unhandled error occurred" RETURN(2) END END-- Check the rowcount. @rowcount_var is set to 0 -- if an invalid @title_id was specified. IF @rowcount_var = 0 BEGIN PRINT "Warning: The title_id specified is not valid" RETURN(1) END ELSE BEGIN PRINT "The book has been updated with the new publisher" RETURN(0) END GO
declare @s nvarchar(100),@i int set @s= 'select 1'exec @i = sp_executesql @sselect @i--0(成功)或 1(失败)
set @s= 'select 1'exec @i = sp_executesql @sselect @i--0(成功)或 1(失败)
--0(成功)或非零(失败) 【联机文档】继续学习...
declare @s nvarchar(100),@i int
set @s= 'select a+ 1'exec @i = sp_executesql @sselect @i
服务器: 消息 207,级别 16,状态 3,行 1
列名 'a' 无效。
END TRY
SQL 2005的TRY Catch试试
下面的示例用 @@ERROR 和 @@ROWCOUNT 验证一条 UPDATE 语句的操作。为任何可能出现的错误而检验 @@ERROR 的值,而用 @@ROWCOUNT 保证更新已成功应用于表中的某行。USE pubs
GO
CREATE PROCEDURE change_publisher
@title_id tid,
@new_pub_id char(4)
AS-- Declare variables used in error checking.
DECLARE @error_var int, @rowcount_var int-- Execute the UPDATE statement.
UPDATE titles SET pub_id = @new_pub_id
WHERE title_id = @title_id -- Save the @@ERROR and @@ROWCOUNT values in local
-- variables before they are cleared.
SELECT @error_var = @@ERROR, @rowcount_var = @@ROWCOUNT-- Check for errors. If an invalid @new_pub_id was specified
-- the UPDATE statement returns a foreign-key violation error #547.
IF @error_var <> 0
BEGIN
IF @error_var = 547
BEGIN
PRINT "ERROR: Invalid ID specified for new publisher"
RETURN(1)
END
ELSE
BEGIN
PRINT "ERROR: Unhandled error occurred"
RETURN(2)
END
END-- Check the rowcount. @rowcount_var is set to 0
-- if an invalid @title_id was specified.
IF @rowcount_var = 0
BEGIN
PRINT "Warning: The title_id specified is not valid"
RETURN(1)
END
ELSE
BEGIN
PRINT "The book has been updated with the new publisher"
RETURN(0)
END
GO
set @s= 'select 1'exec @i = sp_executesql @sselect @i--0(成功)或 1(失败)
执行后查看@@error变量如果>0表示出错