在我的存储过程中,我有以下代码片段:
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.id = b.id上的连接table2 b以及...时的情况)
答案 0 :(得分:3)
你可以在你的一个中有另一个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
答案 1 :(得分: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