内部加入仅在满足If条件

时间:2018-02-07 07:12:10

标签: mysql stored-procedures

如何最小化存储过程

CREATE PROCEDURE [dbo].[spGetItemCategory]
(               
    @ShopID INT
)

AS
BEGIN

    SET NOCOUNT ON;

    -- filter if shopid not equals to 0 
    if @ShopID <> 0

        BEGIN

            SELECT ItemCategory.ItemCategoryID ,CategoryName
            FROM ItemCategory       

            -- join shopitemcategory for filtering      
             inner join ShopitemCategory on             
                   ShopitemCategory.shopid = @ShopID AND            
                   ShopitemCategory.itemcategoryid = ItemCategory.ItemCategoryID

        END

     -- no filter if shopid = 0 
    else

         BEGIN

              SELECT  ItemCategoryID ,CategoryName          
              FROM ItemCategory

         END
 END

这很好用,但还有其他存储过程比这更大并且使用相同的if else方法。那么有什么方法可以简化这段代码吗?

1 个答案:

答案 0 :(得分:0)

您可以在一个查询中合并如下:

<强>解决方法1:

连接中的

OR子句

CREATE PROCEDURE [dbo].[spGetItemCategory] (@ShopID INT)
AS
BEGIN
    SET NOCOUNT ON;

    SELECT ItemCategory.ItemCategoryID
        ,CategoryName
    FROM ItemCategory
    INNER JOIN ShopitemCategory ON (
            ShopitemCategory.shopid = @ShopID
            AND ShopitemCategory.itemcategoryid = ItemCategory.ItemCategoryID
            )
        OR (@ShopID = 0)
END

<强>溶液2:

使用LEFT JOIN并添加WHERE子句:

    CREATE PROCEDURE [dbo].[spGetItemCategory] (@ShopID INT)
    AS
    BEGIN
        SET NOCOUNT ON;

        SELECT ItemCategory.ItemCategoryID
            ,CategoryName
        FROM ItemCategory
        LEFT JOIN ShopitemCategory ON
            ShopitemCategory.itemcategoryid = ItemCategory.ItemCategoryID
        WHERE ShopitemCategory.shopid = @ShopID
            OR @ShopID = 0
    END