如何加入第一行(存储过程)

时间:2013-07-18 22:39:09

标签: sql-server tsql stored-procedures

您好我有以下存储过程,它返回多个照片名称。我想回到第一排。我试过TOP 1,但我确定我会犯一些语法错误。请帮忙

CREATE PROCEDURE getProductsBySubCategoryName
    @SubCategoryName nvarchar(50)
AS
BEGIN
SELECT Products.productName, subCategory.subcategoryName, Photos.photoName
    FROM subCategory INNER JOIN Products ON
    subCategory.subcategory_id = Products.subcategory_id
    INNER JOIN Photos ON
    Products.product_id = Photos.product_id
    WHERE (subcategoryName = @SubCategoryName) 
END

还有一个问题。如何在photoName为null时选择或为null photo选择指定的记录 -

2 个答案:

答案 0 :(得分:0)

您应该能够通过在SELECT之后添加“TOP 1”来访问最高记录。请查看此网址以获得澄清:http://www.w3schools.com/sql/sql_top.asp。你还可以指出你得到的确切错误吗?

答案 1 :(得分:0)

如果您需要每张产品的第一张照片,请尝试以下操作:

CREATE PROCEDURE getProductsBySubCategoryName
    @SubCategoryName nvarchar(50)
AS
BEGIN
    set nocount on;

    ;with ph as (
        select product_id, photoName, row_number() over (partition by product_id order by photoName) pNum
        from Photos
    )   
    SELECT p.productName, sc.subcategoryName, ph.photoName
    FROM subCategory sc
        INNER JOIN Products p ON sc.subcategory_id = p.subcategory_id
        INNER JOIN ph ON p.product_id = ph.product_id and ph.pNum = 1
        WHERE (sc.subcategoryName = @SubCategoryName);
END