如何最小化存储过程
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方法。那么有什么方法可以简化这段代码吗?
答案 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