Dan*_*her 4 t-sql sql-server exception sql-server-2008
我有一个存储过程spMyProc。该过程被传递一个表名作为参数@TableName。在进入过程主体之前验证该表是否存在很重要。
如果表名无效,如何创建自定义异常以引发错误?
我知道的TRY和CATCH,但我不能确定如何把这个加上自定义异常。
问候。
查看 RAISERROR() 函数。
尝试.. CATCH 的工作原理与在任何其他编程语言中的工作原理相同
BEGIN TRY
-- do your checks
IF NOT EXISTS(SELECT 1 FROM sys.tables WHERE NAME = @TableName)
BEGIN
RAISERROR('Table does not exist', 16,1)
END
-- rest of the code if checks are passed
-- if above checks are not passed and you riase an error
-- control will skip any code in TRY Block after the error has been
-- Raised and staright jump to Catch block.
END TRY
BEGIN CATCH
-- Do your error logging
-- Other stuff
-- you have access to ERROR_ functions here to get detailed info about errors
END CATCH
Run Code Online (Sandbox Code Playgroud)