在延迟名称解析后因批量重新编译而发生的错误无法在错误发生的同一级别捕获.一种解决方法是将DDL包装在动态SQL中:
BEGIN TRY EXEC(N'ALTER TABLE [dbo].[my_table_name] ADD PRIMARY KEY ([id]);'); END TRY BEGIN CATCH IF ERROR_NUMBER() = 1779 BEGIN --handle expected errors PRINT 'Primary Key already exists. '; END ELSE BEGIN --raise other unexpected errors THROW; END; END CATCH;