问题
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