我有一个事件表,它有一个作者字段和一个演示者字段。person表中的人可以是同一事件的作者和演示者,也可以是演示者或作者。我需要根据他们的个人ID和他们选择的类型或过滤器对结果集应用过滤器。我的过滤器是:
All:返回他们是作者或展示者的所有记录。
AllPresenter:所有记录作为presenter。
AllAuthor:所有记录作为作者。
presentonly:只记录为演示者而不记录为作者。
AuthorOnly:只记录作者,不记录演示者。
PresenterAndAuthorOnly:他们是演示者和作者的所有记录。
我目前有一个使用外部if的存储过程,如下所示,我试图找到一种方法将所有这些类似的选择语句组合成一个。我没有找到更好的解决方案,我想知道我是否错过了一项技术。
If (@filter = 'PandAOnly' or @filter = 'AllP' or @filter = 'AllA')
begin
Select * from Event
Where
PresenterId = Case @personId is null then PresenterId else @personId end
and
AuthorId = Case @personId is null then AuthorId else @personId end
end
else if (@filter = 'All')
begin
Select * from Event
Where
PresenterId = @personId
Or
AuthorId = @personId
end
else if (@fitler = 'POnly')
begin
Select * from Event
Where
PresenterId = @personId
and
AuthorId <> @personId
end
else
begin
Select * from Event
Where
AuthorId = @personId
and
PresenterId <> @personId
end
Select * from Event
Where
(
((@personId is null) OR (PresenterId =@personId ))
and
((@personId is null) OR (AuthorId = @personId))
AND
(@filter = 'PandAOnly' or @filter = 'AllP' or @filter = 'AllA')
)
OR
(
(PresenterId = @personId
Or
AuthorId = @personId )
AND (@filter = 'All')
)
OR
(
PresenterId = @personId
and
AuthorId <> @personId
and
@fitler = 'POnly'
)
OR
(
AuthorId = @personId
and
PresenterId <> @personId
and
@fitler = 'AOnly'
)
注意
我宁愿坚持使用存储过程,上面查询的执行计划将是可怕的:)