2013-08-01 65 views
0

我有一個報告顯示由indentor創建的一段時間內的購買縮進。這裏,@Name參數用於過濾indentor。但是,問題是,如果@Name參數爲空,那麼報告將返回空記錄。如果在@Name過濾器中沒有選擇任何內容,我想要顯示所有Indentors的報告。以下是查詢。我是SQL新手。如何返回所有記錄如果過濾器爲NULL(空)

SELECT INH.No_, INH.[Approved Date], 
INH.Indentor, INL.No_ AS ItemCode, 
INL.Description, INL.Description2, 
INL.Req_Quantity, INL.[Unit of Measure], 
PL.[Document No_], PH.[Order Date], PL.Quantity AS OrderedQuantity, PL.[Quantity Received] 
FROM [Company$Indent Header] AS INH 
INNER JOIN 
[Company$Indent Line] AS INL 
ON INH.No_ = INL.[Document No_] 
INNER JOIN 
[Company$Purchase Line] AS PL 
ON INL.[Document No_] = PL.[Indent No_] AND INL.[Line No_] = PL.[Indent Line No_] 
INNER JOIN 
[Company$Purchase Header] AS PH 
ON PL.[Document No_] = PH.No_ 
WHERE (INH.Indentor = @Name) AND (INL.No_ <> '') AND 
(INH.[Approved Date] BETWEEN @StartDate AND @EndDate) 
ORDER BY ItemCode 
+2

您是否嘗試過:WHERE(INH.Indentor = @Name或Name是NULL) – highwingers

+1

我的意思是OR @Name爲空 – highwingers

+0

也許使用存儲函數,您可以檢查參數爲null。 –

回答

1

如何構建您的查詢。通過代碼?因爲如果@Name是空的,我會簡單地從下面的WHERE (INH.Indentor = @Name) AND中省略(INH.Indentor = @Name)。 我猜在SQL中沒有條件,不管你是否想在WHERE clausule中考慮條件,如果我錯了,請糾正我。

1

使用一些這樣的事

WHERE (INH.Indentor = COALESCE(@Name,INH.Indentor) 

,並確保在存儲過程的開始後的參數檢查

if len(@Name) = 0 
set @Name = null 

因此,如果@Name是空白它將把null,則 COALESCE( @ Name,INH.Indentor)將檢查@Name是否爲空,然後用現有值檢查

0

試試這個 -

SELECT 
     INH.No_ 
    , INH.[Approved Date] 
    , INH.Indentor 
    , ItemCode = INL.No_ 
    , INL.[description] 
    , INL.Description2 
    , INL.Req_Quantity 
    , INL.[Unit of Measure] 
    , PL.[Document No_] 
    , PH.[Order Date] 
    , OrderedQuantity = PL.Quantity 
    , PL.[Quantity Received] 
FROM dbo.[Company$Indent Header] INH 
JOIN dbo.[Company$Indent Line] INL ON INH.No_ = INL.[Document No_] 
JOIN dbo.[Company$Purchase Line] PL ON INL.[Document No_] = PL.[Indent No_] AND INL.[Line No_] = PL.[Indent Line No_] 
JOIN dbo.[Company$Purchase Header] PH ON PL.[Document No_] = PH.No_ 
WHERE INH.Indentor = ISNULL(@Name, INH.Indentor) 
    AND INL.No_ != '' 
    AND INH.[Approved Date] BETWEEN @StartDate AND @EndDate 
ORDER BY ItemCode 
相關問題