简体   繁体   English

如果在条件sql的情况下存在语句

[英]if exists statement between a case when condition sql

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. 然而,最后条件,其中我必须从表Waitlisthousehold中选择,有一个问题。 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..) 这段代码位于from语句中(来自table1,a.id = b.id上的连接table2 b以及..时的情况)

you can have another case when clause inside your one to check if the table exist or not 你可以在你的一个子句中有另一个case子句来检查表是否存在

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

you can't add an if inside the select statement like that. 你不能在select语句中添加if。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM