只是要额外“防御性”,以下版本生成一个类型转换错误占可能性(但不太可能)的> 1匹配Schema
与验证代码经常故意相似抛出异常是因为我相信它是好的,我相信这是''最佳实践'“来说明所有可能的返回结果,但不太可能,并且即使它只是产生致命异常,因为停止处理的已知效果通常优于未捕获错误的未知级联效应。因为这是不太可能的,我不认为这是值得的一个单独的Count
支票+ Throw
或Try
- Catch
-Throw
的麻烦,以产生更人性化的致命错误,但仍然致命的错误。
SS 2005-:
declare @HasSchemaX bit
set @HasSchemaX = case (select count(1) from sys.schemas where lower(name) = lower('SchemaX')) when 1 then 1 when 0 then 0 else 'ERROR' end
SS 2008+:
declare @HasSchemaX bit = case (select count(1) from sys.schemas where lower(name) = lower('SchemaX')) when 1 then 1 when 0 then 0 else 'ERROR' end
然后:
if @HasSchemaX = 1
begin
...
end -- if @HasSchemaX = 1
来源
2017-06-22 19:36:02
Tom
请考虑改变接受的答案。您所接受的答案实际上不适合您写作的情况。 – 2014-09-05 00:53:40