lenlenya
3/22/2018 - 9:18 AM

在 Transact-SQL 中使用 TRY...CATCH

在 Transact-SQL 中使用 TRY...CATCH

## 在 Transact-SQL 中使用 TRY...CATCH

```sql
create table #t(ErrorMessage varchar(100))
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;
GO

BEGIN TRY
-- Generate divide-by-zero error.
raiserror('主动抛出错误信息。', 16, 1)
SELECT 1/0;
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;

insert into #t values(ERROR_MESSAGE())
END CATCH;
GO

select * from #t
```
>http://technet.microsoft.com/zh-cn/library/ms179296(v=sql.105).aspx