SQL子查询基于外部查询选择表

时间:2011-06-15 16:30:02

标签: sql-server sql-server-2005 conditional subquery

我有一个通用查询,如下所示:

SELECT DISTINCT pb.id, pb.last, pb.first, pb.middle, pb.sex, pb.phone, pb.type, 
specialties = substring(
    SELECT ('|' + cs.specialty )
    FROM CertSpecialty AS cs 
    INNER JOIN CertSpecialtyIndex AS csi on cs.specialty = csi.specialty
    WHERE cs.id = pb.id
    ORDER BY cs.sequence_no
    FOR XML path(''),2,500)
FROM table AS pb 
WHERE etc etc etc

问题在于:

我选择的“type”列是一个整数 - 类型1-4。

在子查询中,请立即查看我从CertSpecialty表中查询的位置。

我真正需要做的是,如果类型字段以1或3的形式返回,那就是我需要查询的表。但是如果行的结果是类型2或4(即ELSE),我需要查询表CertSpecialtyOther中的相同列。

所以它需要看起来像这样(虽然这个obv不起作用):

SELECT DISTINCT pb.id, pb.last, pb.first, pb.middle, pb.sex, pb.phone, pb.type, 
specialties = 
IF type in (1,3)

    substring((SELECT ('|' + cs.specialty )
    FROM CertSpecialty AS cs 
    INNER JOIN CertSpecialtyIndex AS csi on cs.specialty = csi.specialty
    WHERE cs.id = pb.id
    ORDER BY cs.sequence_no
    FOR XML path(''),2,500)

ELSE

    substring((SELECT ('|' + cs.specialty )
    FROM CertSpecialtyOther AS cs 
    INNER JOIN CertSpecialtyIndex AS csi on cs.specialty = csi.specialty
    WHERE cs.id = pb.id
    ORDER BY cs.sequence_no
    FOR XML path(''),2,500)    

end
FROM table AS pb
WHERE etc etc etc

这可能吗?如果是这样,那么正确的语法是什么?有没有更简单的方法来编写它,我在切换哪个表我查询而不完全复制子查询?

此外,是否有人有一个很好的资源,他们可以链接我这样的事情,以了解更多?

提前致谢。

1 个答案:

答案 0 :(得分:1)

使用CTE。

;WITH cs AS
(
    SELECT 'A' SpecialtyCategory, phy_key, specialty
    FROM CertSpecialty

    UNION ALL

    SELECT 'B' SpecialtyCategory, phy_key, specialty
    FROM CertSpecialtyOther
)
SELECT csi.id, cs.specialty
FROM cs 
INNER JOIN CertSpecialtyIndex AS csi on cs.specialty = csi.specialty
WHERE cs.phy_key = pb.phy_key
AND cs.SpecialtyCategory = (CASE WHEN type in (1,3) THEN 'A' ELSE 'B' END)