避免重复的存储过程逻辑

laawzig2  于 2022-10-22  发布在  其他
关注(0)|答案(1)|浏览(135)

我正在尝试编写一个带有WHERE子句的存储过程,该子句根据传递的参数而变化。
如果传递了@categoryId,我需要这个过程:

CREATE PROCEDURE dbo.spCourses_GetCoursesByCategory
    @categoryId int, 
    @courseId varchar
AS
BEGIN
    SET NOCOUNT ON;

    SELECT CoursesUsersReviews.*, CoursesUsersJoin.*
    FROM
        (SELECT 
             Courses.Id, 
             COUNT(Reviews.Text) AS ReviewsCount, 
             COUNT(UserCourses.CourseId) AS EnrollmentCount
         FROM 
             Courses
         INNER JOIN 
             Reviews ON (Courses.Id = Reviews.CourseId)
         INNER JOIN 
             UserCourses ON (Courses.Id = UserCourses.CourseId)
         GROUP BY Courses.Id) CoursesUsersReviews
    INNER JOIN
        (SELECT 
             Courses.Id AS Id, Courses.Name AS CourseName, 
             Courses.Image AS CourseImage, Courses.Url AS CourseURL,
             Courses.Price AS CoursePrice, Courses.Featured AS Featured, 
             Courses.Rating AS Rating, 
             AspNetUsers.Name AS AuthorName, AspNetUsers.Avatar AS AuthorImage, 
             AspNetUsers.About AS AuthorProfile, AspNetUsers.Url AS AuthorURL
         FROM 
             dbo.Courses
         INNER JOIN 
             dbo.AspNetUsers ON (Courses.OwnerId = AspNetUsers.Id)
         WHERE 
             Courses.CategoryId = @categoryId) CoursesUsersJoin ON (CoursesUsersReviews.Id = CoursesUsersJoin.Id)
END
GO

如果传递了@courseName,那么我希望在我的过程中使用WHERE子句:

WHERE Courses.Name = @courseName

如何在不重写整个过程的情况下做到这一点?

ws51t4hk

ws51t4hk1#

好吧,天真的方式是:

WHERE 
  (@categoryId IS NULL OR Courses.CategoryId = @categoryId)
  AND
  (@courseName IS NULL OR Courses.Name = @courseName)

天真是因为,在规模上,它表现不好(因为您将得到一个只支持其中一个参数的特定值的单一执行计划)。

相关问题