2013-08-05 76 views
0

我有以下SQL函數如何從SQL函數,如果沒有找到記錄

ALTER FUNCTION FunctionTEST (@itemID bigint) RETURNS table AS RETURN 
(
    (SELECT top 1 Pic_Path from PictureDetails WHERE PictureDetails.Item_ID = @itemID) 
) 

如果發現針對指定的參數時,該函數將返回首行返回空行。如果在參數中找不到記錄,我希望此函數返回空行。我認爲這應該是一個簡單的任務,但我不熟悉SQL函數。下面是我用來調用函數的實際查詢。

SELECT 
NewClientTB.FirstName, NewClientTB.LastName, NewClientTB.EMail, NewClientTB.ContactNo, 

ADDetails.AD_ID, ADDetails.AD_EXactAddress, 
ADDetails.AD_PostingTime, ADDetails.AD_Description, ADDetails.AD_Title, 

ItemDetails.Item_ID, ItemDetails.Item_Price, 

Regions.R_Description, 

Cities.C_Name, 

GCategories.GC_Description, 

SCategories.SC_Description, 
PictureDetails.Pic_Path 

FROM NewClientTB, ADDetails,ItemDetails, Regions, Cities, GCategories, 
SCategories,  PictureDetails 
WHERE FREETEXT (ADDetails.AD_Title, 'selling') 
AND FREETEXT (ADDetails.AD_Description, 'selling') 
AND ADDetails.AD_PosterID = NewClientTB.UserID 
AND ADDetails.AD_ID = ItemDetails.AD_ID 
AND Regions.R_ID = ADDetails.AD_Region 
AND Cities.R_ID = ADDetails.AD_Region AND Cities.C_ID = ADDetails.AD_City 

AND ItemDetails.Item_GCategory = GCategories.GC_ID 
AND ItemDetails.Item_SCategory = SCategories.SC_ID AND ItemDetails.Item_GCategory = 
SCategories.GC_ID 
AND PictureDetails.Pic_Path = (select * from dbo.FunctionTEST(ADDetails.AD_ID)) 
+3

爲什麼你想要它返回一個空行?正如所寫,它返回一個沒有行的表,這是有道理的。鑑於你只返回最多一個值,你確定你想要一個表值函數而不是標量函數嗎? –

+0

我正在修改上述問題,請稍後再查看 – user2599269

+0

空行是什麼意思?所有列值設置爲空的行?這個函數返回一個空表,你可以把它看作「空行」並且有意義 –

回答

2

如果您需要在項目存在不返回行,但沒有Pic_Path

ALTER FUNCTION FunctionTEST (@itemID bigint) 
RETURNS table AS RETURN 
(
    SELECT top 1 Pic_Path 
    from PictureDetails 
    WHERE PictureDetails.Item_ID = @itemID and Pic_Path is not NULL 
) 

以上功能應與cross apply,如果你在結果和與outer apply想沒有行的項目,而不Pic_Path被稱爲如果你想包含這樣的行結果:

SELECT 
    nctb.FirstName, nctb.LastName, nctb.EMail, nctb.ContactNo, 
    addet.AD_ID, addet.AD_EXactAddress, addet.AD_PostingTime, 
    addet.AD_Description, addet.AD_Title, 
    idet.Item_ID, idet.Item_Price, 
    r.R_Description, 
    c.C_Name, 
    gcat.GC_Description, 
    scat.SC_Description, 
    pdet.Pic_Path 
FROM 
    NewClientTB nctb 
    join ADDetails addet on addet.AD_PosterID = nctb.UserID 
    join ItemDetails idet on idet.AD_ID = addet.AD_ID 
    join Regions r on r.R_ID = addet.AD_Region 
    join Cities c on c.R_ID = addet.AD_Region AND c.C_ID = addet.AD_City 
    join GCategories gcat on gcat.GC_ID = idet.Item_GCategory 
    join SCategories scat on scat.SC_ID = idet.Item_SCategory 
    cross apply dbo.FunctionTEST(addet.AD_ID) ft 
    join PictureDetails pdet on pdet.Pic_Path = ft.Pic_Path 
WHERE FREETEXT (addet.AD_Title, 'selling') AND FREETEXT (addet.AD_Description, 'selling') 
+0

它給出相同的輸出兩種方式,謝謝你,雖然你的幫助 – user2599269

+0

我認爲它應該工作,雖然我的呼叫查詢將需要作出一些修改。謝謝 – user2599269

+0

是的,我檢查過它的工作。謝謝 – user2599269

相關問題