TSQL连接可能为空值

时间:2014-05-28 18:40:28

标签: sql sql-server tsql stored-procedures

我有一个小的存储过程,它正在拉入记录。目前该表中有2条记录。其中一个的值为A.[managerApproval]而另一个则没有。由于连接,如果列没有值,则整个记录不会显示而不仅仅是空值。

无论其加入的列是否具有值,仍然显示数据的好方法是什么?

SELECT A.[id],
       A.[empID],
       A.[firstName],
       A.[lastName],
       A.[emailAddress],
       B.[FirstName] + ' ' +B.[LastName] + ' (' +B.[ntid]+ ')' as managerApproval
FROM   tuitionSubmissions as A
JOIN empTable AS B
ON B.[empID] = A.[managerApproval]
FOR    XML PATH ('data'), TYPE, ELEMENTS, ROOT ('root');

2 个答案:

答案 0 :(得分:2)

使用LEFT OUTER JOIN - 如果第二个表格中存在值,它会将值加入表格,否则它会返回NULLSELECT中的任何值第二桌。

SELECT A.[id],
       A.[empID],
       A.[firstName],
       A.[lastName],
       A.[emailAddress],
       B.[FirstName] + ' ' +B.[LastName] + ' (' +B.[ntid]+ ')' as managerApproval
FROM   tuitionSubmissions as A
LEFT OUTER JOIN empTable AS B
ON B.[empID] = A.[managerApproval]
FOR    XML PATH ('data'), TYPE, ELEMENTS, ROOT ('root');

对于这些记录,managerApproval将为NULL

答案 1 :(得分:1)

好像你需要一个左连接:

  SELECT A.[id],
       A.[empID],
       A.[firstName],
       A.[lastName],
       A.[emailAddress],
       B.[FirstName] + ' ' +B.[LastName] + ' (' +B.[ntid]+ ')' as managerApproval
    FROM   tuitionSubmissions as A
    Left JOIN empTable AS B
    ON B.[empID] = A.[managerApproval]
   FOR    XML PATH ('data'), TYPE, ELEMENTS, ROOT ('root');