2

我有以下两个查询,第一个按您的预期工作。第二个引发一个异常,说无效的列名 ISDELETED。但是我已经精确地添加了 if else 结构以避免该错误,在第二个查询中我做错了什么

IF COL_LENGTH('vwAs', 'IsActive') IS NOT NULL  
select  1  
ELSE IF COL_LENGTH('vwABCs', 'IsDeleted') IS NOT NULL
  select 0   
ELSE SELECT -1

IF COL_LENGTH('vwAs', 'IsActive') IS NOT NULL  
select   Count(*) [vwB] from [vwAs] WHERE ISACTIVE = 1 
ELSE IF COL_LENGTH('vwABCs', 'IsDeleted') IS NOT NULL
  select Count(*) [vwABCsActive] from [vwABCs] WHERE ISDELETED = 0      
ELSE SELECT -1
4

1 回答 1

4

在运行查询数据库引擎之前尝试验证您的代码,但不验证您的逻辑。如果您的表没有ISDELETED列 DB,则会向您显示错误。所以你必须从数据库引擎中隐藏你的错误代码作为动态 sql。动态 sql 将不会被验证。

IF COL_LENGTH('vwAs', 'IsActive') IS NOT NULL  
select   Count(*) [vwB] from [vwAs] WHERE ISACTIVE = 1 
ELSE IF COL_LENGTH('vwABCs', 'IsDeleted') IS NOT NULL
  exec('select Count(*) [vwABCsActive] from [vwABCs] WHERE ISDELETED = 0')
ELSE SELECT -1
于 2013-07-29T08:49:52.583 回答