DECLARE @source as NVARCHAR(MAX) = (SELECT md.[source] FROM sports_service.meet.meet_detail md WHERE md.meet_id = #{meetId})
WHERE reg.is_waitlist = 0 AND reg.cancelled_dt IS NULL
AND NOT EXISTS (
SELECT 1 FROM sports_service.meet.meet_invitations i
WHERE i.meet_id = pmm.meet_id AND i.sports_person_id = reg.sports_person_id)
IF @source != 'MANUAL'
AND EXISTS (
SELECT 1
FROM sports_service.meet.session session
INNER JOIN sports_service.meet.event event ON event.session_id = session.id
WHERE pmm.meet_id = session.meet_id
AND sports_service.dbo.fnGetMeetAge(p.birth_dt, detail.age_up_date, detail.id_format) <![CDATA[>=]]> event.low_age
AND sports_service.dbo.fnGetMeetAge(p.birth_dt, detail.age_up_date, detail.id_format) <![CDATA[<=]]> event.high_age
AND (event.eligible_gender IS NULL OR event.eligible_gender = p.gender))
答案 0 :(得分:2)
如果您仅在满足其他条件(源为AND EXISTS ...
)并且要在一个查询中而不是:
MANUAL
子句),
WHERE (...some condition ...) AND (.. some other condition ... )
IF @source != 'MANUAL'
AND EXISTS (
SELECT 1 ... )
不支持,因为它不是正确的sql语法,您可以执行以下操作:
WHERE (...some condition ...) AND (.. some other condition ... )
AND (
(
(SELECT md.[source]
FROM sports_service.meet.meet_detail md
WHERE md.meet_id = #{meetId}
) = 'MANUAL'
)
OR EXISTS (
SELECT 1
FROM ...
)
)
您需要检查结果查询的性能是否令人满意。
最好执行先获取source
的查询,然后再根据附加条件source
执行带有附加条件或不附加条件的查询。为此,您可以使用dynamic SQL(包括或排除此附加条件)在mybatis中生成查询。
答案 1 :(得分:1)
由于不能使用If表达式,因此可以这样编写sql:
DECLARE @source as NVARCHAR(MAX) = (SELECT md.[source] FROM sports_service.meet.meet_detail md WHERE md.meet_id = #{meetId})
WHERE reg.is_waitlist = 0 AND reg.cancelled_dt IS NULL
AND NOT EXISTS (
SELECT
1
FROM
sports_service.meet.meet_invitations i
WHERE
i.meet_id = pmm.meet_id
AND i.sports_person_id = reg.sports_person_id)
AND ( @source <> 'MANUAL'
AND
EXISTS ( SELECT 1 FROM
sports_service.meet.session session
INNER JOIN sports_service.meet.event event ON
event.session_id = session.id
WHERE
pmm.meet_id = session.meet_id
AND sports_service.dbo.fnGetMeetAge(p.birth_dt,
detail.age_up_date,
detail.id_format) >= event.low_age
AND sports_service.dbo.fnGetMeetAge(p.birth_dt,
detail.age_up_date,
detail.id_format) <= event.high_age
AND (event.eligible_gender IS NULL
OR event.eligible_gender = p.gender)))
答案 2 :(得分:0)
您不能在表达式内使用IF
。