如果表存在,则为case语句

时间:2015-02-27 09:49:56

标签: sql sql-server

我在查找来自不同数据库的表时遇到问题(如果表存在,表有时会因程序而丢失),那么条件为else,将ans作为1

选择(存在时的情况(从SysSet.INFORMATION_SCHEMA .TABLES中选择*,其中TABLE_NAME ='CHQPASS')然后(                 左边的情况(tranm.docu_no,1)<>'3'或者tranm.docu_dt< '01 / 01/2015'然后1                 when(从TRAND k中选择前1个ACHD_KEY,其中k.TRN_NO = TRANM.TRN_NO和k.DR_CR ='D')='A000100010002'THEN 1                 WHEN(从SYSSET..chqpass D中选择COUNT(*),其中D.COMP_DIR ='PSAGR'和D.DOCU_DT = TRANM.DOCU_DT和D.AMT = TRAND.TOT_AMT)<> 0                 然后1                 else cast(isnull(trand.RECONCILE,0)as int)                 结束)                 否则1
    结束)作为pend

如果表不存在则显示错误

  

消息208,级别16,状态1,行2无效的对象名称   'SYSSET..chqpass'。

表格不存在如何阻止它查看该表

2 个答案:

答案 0 :(得分:0)

替换以下行

WHEN  (select COUNT(*) from SYSSET..chqpass  D where D.COMP_DIR ='xyz' and D.DOCU_DT >'01/01/2015' and D.AMT = 2556 ) <> 0 

这一行

WHEN  EXEC('(select COUNT(*) from SYSSET..chqpass  D where D.COMP_DIR =''xyz'' and D.DOCU_DT >''01/01/2015'' and D.AMT = 2556 )') <> 0 

应该这样工作......

答案 1 :(得分:0)

尝试尝试将sys.tables替换为INformationschema,以便指定表中存在schema

SELECT 
     (
       CASE WHEN EXISTS(SELECT * FROM SYSSET.INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CHQPASS' AND TABLE_SCHEMA = 'dbo')
             THEN (
                   CASE WHEN LEFT(tranm.docu_no,1) <>'3' or tranm.docu_dt < '01/01/2015' THEN 1  
                        WHEN (SELECT TOP 1 ACHD_KEY FROM TRAND k WHERE k.TRN_NO = TRANM.TRN_NO and k.DR_CR ='D' ) = 'A000100010002' THEN 1 
                        WHEN  (select COUNT(*) from SYSSET..chqpass  D WHERE D.COMP_DIR ='PSAGR' and D.DOCU_DT = TRANM.DOCU_DT and D.AMT = TRAND.TOT_AMT ) <> 0  THEN 1 
                        ELSE cast(isnull (trand.RECONCILE,0)as int)
                   END
                  )
      ELSE 1  
      END 
     ) as pend