强制sql查询返回结果

时间:2012-05-01 21:53:28

标签: sql tsql

这是我的SQL:

-- Order information
SELECT ISNULL(p.PaymentAmt, 0) AS PaymentAmt, o.TaxAmt, o.PostAmount, o.OrderDate, o.PublicNotes, u.userid, PostAmount + TaxAmt AS Total, PostAmount - PaymentAmt AS Due
FROM Orders o 
INNER JOIN Payment p ON p.OrderID = o.OrderID
INNER JOIN Users u  ON o.EnteredBy = u.UserKey
Where o.OrderID = 5267

现在对于这个特定的OrderID,它只返回列标题的0行。有没有办法强制它为值返回0,为其余值返回空字符串?

2 个答案:

答案 0 :(得分:5)

我认为它应该能给你带来理想的结果:

WITH CTE1 AS (SELECT ISNULL(p.PaymentAmt, 0) AS PaymentAmt, o.TaxAmt, o.PostAmount,  
   o.OrderDate, o.PublicNotes, u.userid, PostAmount + TaxAmt AS Total, PostAmount -    
    PaymentAmt AS Due 
    FROM Orders o  
    INNER JOIN Payment p ON p.OrderID = o.OrderID 
    INNER JOIN Users u  ON o.EnteredBy = u.UserKey 
    Where o.OrderID = 5267 
    AND o.EnteredBy = u.UserKey )
SELECT CTE1.*
FROM CTE1
UNION ALL
SELECT 0,0, NULL,NULL,NULL,NULL,NULL
WHERE NOT EXISTS (SELECT 1 FROM CTE1)

答案 1 :(得分:2)

另一种方式:

SELECT ISNULL(p.PaymentAmt, 0) AS PaymentAmt, o.TaxAmt, o.PostAmount, 
       o.OrderDate, o.PublicNotes, u.userid, 
       PostAmount + TaxAmt AS Total, PostAmount - PaymentAmt AS Due
FROM Orders o 
  INNER JOIN Payment p ON  p.OrderID = o.OrderID
                       AND o.OrderID = 5267        --- condition moved here
  INNER JOIN Users u  ON o.EnteredBy = u.UserKey
  RIGHT JOIN (SELECT 1 dummy) trick ON 1=1         --- this line was added

---  AND o.EnteredBy = u.UserKey                   --- this is redundant