如何在SQL Server 2005中捕获截断错误?

cha*_*ama 5 sql error-handling sql-server-2005 insert

我正在尝试将数据插入表中.比如说这是我的表:

CREATE TABLE firstTable (first_name VARCHAR(5), last_name VARCHAR(10))
Run Code Online (Sandbox Code Playgroud)

当我尝试插入此表时,first_name字段中超过5个字符的任何数据都会导致以下错误.

消息8152,级别16,状态14,行1字符串或二进制数据将被截断.该语句已终止.

有没有办法让我在存储过程中捕获此错误?我尝试if @@ERROR <> 0在insert语句之后放置一个权限,但是该过程永远不会进入错误检查,因为该语句已被终止!

有任何想法吗?

TIA!

Mar*_*ith 5

您可以使用 TRY ... CATCH

BEGIN TRY

INSERT INTO firstTable VALUES ('long string','foo')

END TRY
BEGIN CATCH

SELECT ERROR_NUMBER(), ERROR_MESSAGE()
/*The error will not be propagated to the client. You need
 to use RAISERROR if you want this to happen*/

END CATCH
Run Code Online (Sandbox Code Playgroud)