我不知道如何将if/case
与where exists
语句结合起来。以下所有字段都位于t_phone
这是设置 - 有一个声明的电话临时变量
Declare @phone varchar(25)
`select @phone = ....`
我们需要说的是,对于给定的customer_no
,如果该customer_no存在phone_type
(来自 t_phone
),类型为 25 使用与 type = 25 关联的phone_no,否则使用类型 2。
所以例如
phone_no type customer_no
1234567890 2 4
0987654321 25 4
6537327345 2 8
基于上述客户 4 的示例,我们希望设置 @phone = 0987654321,因为存在类型 25,但对于客户编号 8,我们希望使用类型 2,因为没有替代的 25 类型。
如果 2 和 25 是唯一的类型,您可以执行如下所示的SELECT MAX()
:
Select t.phone_no
from t_phone t
where t.type = (select max(ti.type)
from t_phone ti
where ti.customer_no=t.customer_no
and ti.type in (2,25))
您可以通过引入一个名为 type_priority
的表来使其更易于实现和维护。这将有两列:type
和 priority
。对于type=25
,priority
最高,比如10,type=2
priority
是1。
然后,当您选择"与此表联接"时,按priority DESC
排序并选择top 1
。
select top 1 @phone = phone_no
from t_phone ph
join type_priority tp on tp.type = ph.type
where customer_no = @Customer
order by tp.priority desc
这种数据驱动的方法更易于维护,因为如果您引入其他类型,只需使用适当的priority
将行添加到type_priority
表中,sql 语句将继续以相同的方式工作。
请注意,对于表中缺少types
type_priority
将不会选择记录。因此,您需要确保它与所有新引入的类型保持最新。
由于您只与一个客户打交道,并且您唯一想要的值是类型 2 和 25,那么像这样简单的事情怎么样。
select top 1 phone_no
from t_phone
where customer_no = @Customer
order by
case type when 25 then 2
when 2 then 1
else 0 end
declare @phone varchar(25)
select @phone = CASE t0.[type]
WHEN 25 THEN t1.phone_no
WHEN 2 then t2.phone_no
else 0
END
from tbl t0
left outer join tbl t1 on t1.type = 25 and t1.customer_no = t0.customer_no
left outer join tbl t2 on t2.type = 2 and t2.customer_no = t0.customer_no