【问题标题】:if exists statement between a case when condition sql如果条件sql的case之间存在语句
【发布时间】:2013-04-18 04:05:26
【问题描述】:

在我的存储过程中间,我有以下sn-p代码:

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

那我该怎么做呢?

这个 sn-p 在 from 语句中(从 table1 a join table2 b on a.id=b.id and case when..)

【问题讨论】:

  • 猜测 SQL Server?如果是这样,不使用动态 SQL 就无法做到这一点 - 每个查询都根据它访问的表来固定。

标签: sql case


【解决方案1】:

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

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

【讨论】:

  • 感谢 EXISTS in CASE 表达式,但是这个 sn-p 将返回错误的语法错误
  • 哈哈.. 我写的是 CASE WHERE 而不是 CASE WHEN,现在检查答案
  • 就像 Damien_The_Unbeliever 说的,这在 SQL server 中是行不通的。
【解决方案2】:

你不能像这样在 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

【讨论】:

  • 如果是 SQL Server(考虑到 OP 之前的问题似乎很可能),这将不起作用,因为它将尝试编译整个批次,并且缺少该表将阻止该编译成功.
猜你喜欢
  • 1970-01-01
  • 2012-02-07
  • 1970-01-01
  • 2014-09-21
  • 1970-01-01
  • 1970-01-01
  • 2011-08-21
  • 1970-01-01
  • 2023-01-05
相关资源
最近更新 更多