2011-10-07 69 views
0

我正在使用SQL Server。我有3個表:在SQL Server中顯示NULL值加入

  1. tblUser
  2. tblAudit
  3. tblEnum

的tblAudit得到了4列:

nUserId,的NID:這兩列指向tblUser

vFromValue,vToValue:這兩列指向tblEnum

現在,我需要根據tblAudit表中存在的ID顯示來自tblUser和tblEnum的實際值。 我寫的查詢看起來是這樣的:

SELECT A.aEventID, 
U.tName AS MakerChecker, 
U2.tName AS OnUser, 
VLE.tDisplayName AS FromValue, 
VLE2.tDisplayName AS ToValue, 
A.dChangeTime AS Timestamp 
FROM tblAudit A INNER JOIN tblUser U ON A.nUserId = U.aUserId 
INNER JOIN tblUser U2 ON A.nID = U2.aUserId 
INNER JOIN tblEnum VLE ON A.vFromValue = VLE.nIndex OR (A.vFromValue IS NULL) 
INNER JOIN tblEnum VLE2 ON A.vToValue = VLE2.nIndex OR (A.vToValue IS NULL) 

因爲在審覈表中的值是零對於一些行的列vFromValue和vToValue,這些值都不會再爲NULL,但以前的值。 如何通過更改上述查詢來完整顯示空值?請幫忙。

回答

0

由於tblAudit.vFromValuetblAudit.vToValueNULL S,試試這個:

SELECT A.aEventID, 
     U.tName AS MakerChecker, 
     U2.tName AS OnUser, 
     VLE.tDisplayName AS FromValue, 
     VLE2.tDisplayName AS ToValue, 
     A.dChangeTime AS Timestamp 
FROM 
    (SELECT aEventID, nUserId, nID, dChangeTime 
      , COALESCE(vFromValue, -9999) AS vFromValue --- some non-existent 
      , COALESCE(vToValue, -999) AS vToValue  --- value 
     FROM tblAudit 
    ) AS A 
    INNER JOIN tblUser U 
    ON A.nUserId = U.aUserId 
    INNER JOIN tblUser U2 
    ON A.nID = U2.aUserId 
    LEFT JOIN tblEnum VLE 
    ON A.vFromValue = VLE.nIndex 
    LEFT JOIN tblEnum VLE2 
    ON A.vToValue = VLE2.nIndex 

或本:

SELECT A.aEventID, 
     U.tName AS MakerChecker, 
     U2.tName AS OnUser, 
     (SELECT VLE.tDisplayName 
     FROM tblEnum VLE 
     WHERE A.vFromValue = VLE.nIndex 
     ) AS FromValue, 
     (SELECT VLE2.tDisplayName 
     FROM tblEnum VLE2 
     WHERE A.vToValue = VLE.nIndex 
     ) AS ToValue, 
     A.dChangeTime AS Timestamp 
FROM tblAudit AS A 
    INNER JOIN tblUser U 
    ON A.nUserId = U.aUserId 
    INNER JOIN tblUser U2 
    ON A.nID = U2.aUserId 
+0

偉人!幫助完善我的解決方案。解決。 –

0

如果我理解你的問題 - 嘗試對最後兩行使用LEFT JOIN(並在OR之後刪除條件)。

+0

做了吧:)沒有幫助。然而,已經嘗試了其他方法來解決問題,但我認爲它不是一個乾淨的解決方案,而是爲了達到目的。發佈它作爲答案。如果有人遇到更好的解決方案,請將其發佈。謝謝。 –