SQL存储过程加入问题

时间:2010-10-13 11:50:55

标签: sql-server-2005 stored-procedures join

目前,存储过程根据作为参数传递的employee_number返回一条记录。如果surpervisor_id为NULL,则不返回任何记录。如果我想返回包含所有其他字段的记录,并且在supervisor_id字段中有一个NULL,我该如何配置?

SELECT DISTINCT 
    tblPeople.PERSON_ID, tblPeople.FIRST_NAME, tblPeople.LAST_NAME, 
    tblPeople.EMPLOYEE_NUMBER, tblPeople.EMAIL_ADDRESS, 
    tblAddress.ADDRESS_LINE1, tblAddress.ADDRESS_LINE2, tblAddress.ADDRESS_LINE3, 
    tblAddress.TOWN_OR_CITY, tblAddress.STATE, tblAddress.COUNTRY, 
    tblAddress.POSTAL_CODE, tblPeople.PHONE_NUMBER, 
    tblPeople.EFFECTIVE_START_DATE, tblPeople.EFFECTIVE_END_DATE, 
    tblLocation.LOC_CODE, 
    pp2.FIRST_NAME AS Expr1, pp2.LAST_NAME AS Expr2, 
    pp2.EMPLOYEE_NUMBER AS Expr3, tblAssignment.SUPERVISOR_ID, 
    tblAssignment.ATTRIBUTE2, tblAssignment.ATTRIBUTE3, 
    tblPeople.INSTANCE_ID, tblAssignment.LOC_ID
FROM
    tblPeople AS tblPeople 
RIGHT OUTER JOIN
    tblAddress AS tblAddress ON tblPeople.PERSON_ID = tblAddress.PERSON_ID 
                             AND tblPeople.INSTANCE_ID = tblAddress.INSTANCE_ID 
INNER JOIN
    tblAssignments AS tblAssignment ON tblPeople.PERSON_ID = tblAssignment.PERSON_ID 
                                    AND tblPeople.INSTANCE_ID = tblAssignment.INSTANCE_ID 
INNER JOIN
    Locations AS Location ON Location.LOC_ID = tblAssignment.LOC_ID
                          AND Location.INSTANCE_ID = tblAssignment.INSTANCE_ID 
INNER JOIN 
    tblPeople AS pp2 ON pp2.PERSON_ID = tblAssignment.SUPERVISOR_ID
                     AND pp2.INSTANCE_ID = tblAssignment.INSTANCE_ID
WHERE     
    tblPeople.EMPLOYEE_NUMBER = '3298'
    AND tblPeople.INSTANCE_ID = 1
    AND tblAssignment.Assignment_Status = 'Current'

1 个答案:

答案 0 :(得分:2)

最有可能的是,您只需要更改此JOIN

INNER JOIN 
    tblPeople AS pp2 ON pp2.PERSON_ID = tblAssignment.SUPERVISOR_ID
                     AND pp2.INSTANCE_ID = tblAssignment.INSTANCE_ID

到LEFT OUTER JOIN

LEFT OUTER JOIN 
    tblPeople AS pp2 ON pp2.PERSON_ID = tblAssignment.SUPERVISOR_ID
                     AND pp2.INSTANCE_ID = tblAssignment.INSTANCE_ID

如果SUPERVISOR_ID为空,那么pp2表中的列将为NULL,但您仍应获取所有其他列的数据。