if exists statement between a case when condition sql

断了今生、忘了曾经 提交于 2019-12-11 09:04:33

问题


In the middle of my stored procedure, I have the following snippet of code:

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

however, the final condition, wherein i have to select from the table Waitlisthousehold, has an issue. Not all databases has that table. so I want that last condition to be included when the table exists. But i'm getting errors when i try to do this:

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

So how do i do it correctly?

This snippet is inside a from statement(from table1 a join table2 b on a.id=b.id and case when..)


回答1:


you can have another case when clause inside your one to check if the table exist or not

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



回答2:


you can't add an if inside the select statement like that. you could do this:

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


来源:https://stackoverflow.com/questions/16074287/if-exists-statement-between-a-case-when-condition-sql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!