如果没有找到记录,如何从sql函数返回空行

时间:2013-08-05 22:02:46

标签: sql database sql-server-2008

我有以下SQL函数

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

如果根据指定的参数找到,此函数将返回第一行。如果没有找到针对Parameter的记录,我希望此函数返回空行。我认为这应该是一个简单的任务,但我不熟悉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))

1 个答案:

答案 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的项目没有行,则应使用Pic_Path调用上面的函数;如果您希望在结果中包含此类行,则应使用outer apply

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')