尝试 - 捕获SQL

时间:2016-01-21 15:01:35

标签: sql-server tsql

我不能强迫我的错误悲伤的脸来提出这段代码。有人可以帮助我,我只是得到一个正常的错误信息而不是捕获中的那个。我只是拿出一些代码强制错误是正确的

declare @Color Table
(color char(12))

insert @Color 
Values('white'),
('Red'),
('black'),
('yellow');

Declare @make Table 
(make char(12))

insert @make
Values('Polo'),
('Golf'),
('A1'),
('Metro');

Begin try   
Select *
  From @Color Cross Join @make ;   
End Try    
Begin Catch
   PRINT ';('   
end catch
  Print 'Done'

1 个答案:

答案 0 :(得分:0)

我在SQL Server 2012中运行了您的摘录,它根本没有产生错误。我得到了16行的结果集。

以下是一些可以捕获错误并告诉您出错的代码:

DECLARE @Color TABLE
(color char(12));

INSERT @Color 
VALUES('white'),
('Red'),
('black'),
('yellow');

BEGIN TRY;
    SELECT CAST(color AS int)
        FROM @Color;
END TRY
BEGIN CATCH
    SELECT ERROR_NUMBER() AS ErrorNumber,
            ERROR_SEVERITY() AS ErrorSeverity,
            ERROR_STATE() AS ErrorState,
            ERROR_PROCEDURE() AS ErrorProcedure,
            ERROR_LINE() AS ErrorLine,
            ERROR_MESSAGE() AS ErrorMessage;
END CATCH;

输出结果为:

Output of error handler