1

在我的存储过程的中间,我有以下代码片段:

case
  when l.codeleasestatuscode = '5' and priorleaseid is null 
  and l.leaid in(select col1 from Waitlisthousehold)
then '2'
else l.codeleasestatuscode
end

但是,我必须从 Waitlisthousehold 表中进行选择的最终条件存在问题。并非所有数据库都有该表。所以我希望在表存在时包含最后一个条件。但是当我尝试这样做时出现错误:

case
when l.codeleasestatuscode = '5' and priorleaseid is null
IF EXISTS(select * from information_schema.tables where table_name='WaitlistHousehold')
  begin
    and l.leaid in(select col1 from Waitlisthousehold)
  end
then '2'
else l.codeleasestatuscode
end

那么我该如何正确地做到这一点呢?

此代码段位于 from 语句中(从 table1 a join table2 b on a.id=b.id and case when..)

4

2 回答 2

3

您可以在您的子句中使用另一种情况来检查表是否存在

CASE
WHEN l.codeleasestatuscode = '5' and priorleaseid is null
    CASE WHEN EXISTS(SELECT * FROM information_schema.tables WHERE table_name='WaitlistHousehold')
        THEN
            CASE WHEN l.leaid in(select col1 from Waitlisthousehold) THEN '2' 
            ELSE l.codeleasestatuscode END
        ELSE '2' END          
    THEN '2'END
ELSE l.codeleasestatuscode
END
于 2013-04-18T04:39:29.730 回答
0

您不能像这样在 select 语句中添加 if 。你可以这样做:

IF EXISTS(select * from information_schema.tables where table_name='WaitlistHousehold')
  BEGIN
  SELECT whatever,
  case
  when l.codeleasestatuscode = '5' and priorleaseid is null
    and l.leaid in(select col1 from Waitlisthousehold)
  then '2'
  else l.codeleasestatuscode
  end AS whatever1
  FROM wherever
  END
ELSE
  BEGIN
  SELECT whatever,
  case
  when l.codeleasestatuscode = '5' and priorleaseid is null
  then '2'
  else l.codeleasestatuscode
  end AS whatever1
  FROM wherever
  END
于 2013-04-18T04:17:59.247 回答