开发者

How can I catch a truncation error in SQL Server 2005?

I'm attem开发者_如何学JAVApting to insert data into a table. Say for example that this is my table:

CREATE TABLE firstTable (first_name VARCHAR(5), last_name VARCHAR(10))

When I try to insert into this table, any data in the first_name field that exceeds 5 characters causes the following error.

Msg 8152, Level 16, State 14, Line 1 String or binary data would be truncated. The statement has been terminated.

Is there any way for me to catch this error in a stored procedure? I tried putting an if @@ERROR <> 0 right after the insert statement, but the procedure never gets to the error check because the statement has been terminated!

Any ideas?

TIA!


You can use 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


You can use the LEN function to determine if the strings are too long before you do the insert. For example, if you wanted to just insert the truncated string you could do:

IF(LEN(@firstName) > 5) SET @firstName = LEFT(@firstName, 5)
IF(LEN(@lastName) > 10) SET @lastName = LEFT(@lastName, 10)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜