存储过程 - 查询问题

时间:2015-10-25 11:56:37

标签: sql sql-server tsql stored-procedures conditional

我根本无法找到此存储过程查询的解决方案。

我有PersonStudent表。在Person表中,我存储了一个bool值isFootballPlayer,而Student表有一个FK PersonId,将其链接到Person表。

我有一个网络应用,其中有一个搜索功能,包括学生,人和足球运动员的复选框,以便过滤结果。因此,当只选择Person时,它将返回所有玩家和学生。

我的存储过程如下所示:

"SP stuff"
@IncludePerson bit,
@IncludePlayer bit,
@IncludeStudent bit
AS
BEGIN
    WITH i (Id)
    SELECT 
        p.PersonId as Id
    FROM 
        Person p
    LEFT OUTER JOIN 
        Student s ON s.PersonId = p.PersonId
    WHERE
        (s.PersonId IS NULL OR @IncludeStudent = 1) AND
        (p.IsFootballPlayer = 0 OR @IncludePlayer = 1) AND
        ((s.PersonId > 0) OR @IncludePerson = 1)
    )
    SELECT i.Id
    FROM i
    GROUP BY i.Id
END

这里的问题是一些学生也可能是足球运动员,因此当只选中学生复选框时,结果将排除同时也是足球运动员的学生,除非选中这两个复选框。

任何人都可以帮助我朝着正确的方向前进,并给我一些提示,告诉我如何修改存储过程以管理向足球运动员展示学生,而无需同时选中这两个复选框?

由于

2 个答案:

答案 0 :(得分:0)

"SP stuff"
@IncludePerson bit,
@IncludePlayer bit,
@IncludeStudent bit
AS
BEGIN
    Declare @Sql NVARCHAR(MAX);

SET @Sql = N'SELECT DISTINCT p.PersonId as Id 
            FROM  Person p
            WHERE 1 = 1 '

          -- When only Person checkbox is checked  
          + CASE WHEN (@IncludePerson = 1 AND @IncludeStudent = 0 AND @IncludePlayer = 0)
          THEN N' AND p.IsFootballPlayer = 0  
                  AND NOT EXISTS (SELECT 1 FROM Student s
                                  WHERE s.PersonId = p.PersonId)' ELSE N'' END
          -- When only Student checkbox is checked  
          + CASE WHEN (@IncludePerson = 0 AND @IncludeStudent = 1 AND @IncludePlayer = 0)
          THEN N' AND  EXISTS (SELECT 1 FROM Student s
                               WHERE s.PersonId = p.PersonId)' ELSE N'' END
          -- When only Player checkbox is checked  
          + CASE WHEN (@IncludePerson = 0 AND @IncludeStudent = 0 AND @IncludePlayer = 1)
          THEN N' AND p.IsFootballPlayer = 1 ' ELSE N'' END
          -- And you can add as many as combinations you want 

-- Finally execute the dynamically built sql query 

  Exec sp_executesql @Sql

END

答案 1 :(得分:0)

为什么不在@IncludeStudent = 1的情况下在存储过程中设置变量@IncludePlayervalue = 1,如下所述 -

"SP stuff"
@IncludePerson bit,
@IncludePlayer bit,
@IncludeStudent bit
AS
BEGIN
if @IncludeStudent = 1
   begin
     set @IncludePlayer = 1
   end
    WITH i (Id)
    SELECT 
        p.PersonId as Id
    FROM 
        Person p
    LEFT OUTER JOIN 
        Student s ON s.PersonId = p.PersonId
    WHERE
        (s.PersonId IS NULL OR @IncludeStudent = 1) AND
        (p.IsFootballPlayer = 0 OR @IncludePlayer = 1) AND
        ((s.PersonId > 0) OR @IncludePerson = 1)
    )
    SELECT i.Id
    FROM i
    GROUP BY i.Id
END