2

我正在尝试传入一个参数,如果该参数为空,我想将县 ID 设置为自身。如果县 ID 不为空,那么我想带回县协作中所有县的记录。

我收到不正确的语法错误。关于如何做到这一点的任何想法?

    DECLARE @pCountyId as int;

    select  p.Id, p.LastName, p.FirstName, c.Id, c.Description
    FROM Participant as p
    INNER JOIN Application as a on p.Id = a.ParticipantId
    INNER JOIN Dictionary.Counties as c on a.CountyId = c.Id
    WHERE 

    If @pCountyId is null 
        BEGIN
            c.Id = c.Id
        END
    ELSE
            c.Id in (SELECT cc.CountyId 
                    FROM CountyCollaboration as cc
                    WHERE cc.CollaborationId = (SELECT cc1.CollaborationId 
                                       FROM CountyCollaboration as cc1
                                       WHERE cc1.CountyId = @pCountyId))
4

3 回答 3

5

尝试:

WHERE 

(@pCountyId is null) OR 

c.Id in (SELECT cc.CountyId 
                    FROM CountyCollaboration as cc
                    WHERE cc.CollaborationId = (SELECT cc1.CollaborationId 
                                       FROM CountyCollaboration as cc1
                                       WHERE cc1.CountyId = @pCountyId))

但是请重新考虑您的条件,它的子查询太多了。

于 2013-11-07T21:05:24.413 回答
0

As far as I understand, you cannot add an if-statement in the way you are within the query - no syntax for that kind of querying. You could do exactly what you're doing with two separate queries in each block (duplicate the SELECT/INNER JOIN), but it is not the most ideal solution.

于 2013-11-07T21:07:13.273 回答
0

你应该这样做:

select  p.Id        ,
        p.LastName  ,
        p.FirstName ,
        c.Id ,
        c.Description
from Participant         p
join Application         a on a.ParticipantId = p.Id
join Dictionary.Counties c on c.Id            = a.CountyId
where       @pCountyId is     null
   OR (     @pCountyID is not null
        and c.Id in ( select cc.CountyId 
                      from CountyCollaboration cc
                      join CountyCollaboration cc1 on cc1.CollaborationId = cc.CollaborationId
                                                  and cc1.CountID = @pCountyId
                    )
      )
于 2013-11-07T21:15:09.397 回答