简体   繁体   中英

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

I'm attempting 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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM