0

我有以下 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))
4

1 回答 1

2

如果您需要在 item 存在但没有时返回任何行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')
于 2013-08-05T22:09:45.353 回答