我正在尝试传入参数,如果参数为null,我想将县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))
答案 0 :(得分: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))
但是要重新考虑你的情况,这是太多的子查询。
答案 1 :(得分:0)
据我所知,你不能以你在查询中的方式添加if语句 - 没有这种查询的语法。您可以使用每个块中的两个单独查询完成您正在执行的操作(复制SELECT / INNER JOIN),但它不是最理想的解决方案。
答案 2 :(得分: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
)
)