MS SQL条件存储过程在所有情况下都返回值

时间:2014-01-29 11:54:17

标签: sql sql-server database stored-procedures

我有MS SQL存储过程,它返回3个简单表中的值,如下所示,需要它在所有情况下为产品返回一行。 我想知道是否可以在(T3)中获得BrandID的值,如果没有产品记录的行,则返回值为#34; BrandID"

T3就像

ProductID --- BrandID

@iCategoryID int
AS
Begin
SELECT P.ProductID,P.CategoryID, C.ParentID, PC.BrandID FROM T1 P
JOIN T2 C ON P.CategoryID = C.CategoryID
JOIN T3 PC ON P.ProductID=PC.ProductID
WHERE P.CategoryID=@iCategoryID 
ORDER by P.ProductID Asc
End
GO

1 个答案:

答案 0 :(得分:1)

您想要left outer join

SELECT P.ProductID,P.CategoryID, C.ParentID, PC.BrandID
FROM T1 P LEFT JOIN
     T2 C
     ON P.CategoryID = C.CategoryID  LEFT JOIN
     T3 PC
     ON P.ProductID = PC.ProductID
WHERE P.CategoryID = @iCategoryID
ORDER by P.ProductID Asc;

如果品牌不匹配,则会返回NULL。如果您想改为0

SELECT P.ProductID,P.CategoryID, C.ParentID, coalesce(PC.BrandID, 0) as BrandID
FROM T1 P LEFT JOIN
     T2 C
     ON P.CategoryID = C.CategoryID  LEFT JOIN
     T3 PC
     ON P.ProductID = PC.ProductID
WHERE P.CategoryID = @iCategoryID
ORDER by P.ProductID Asc;