我有以下查询。
declare @Prm_CourseId int
declare @Prm_SpecializationId int
set @Prm_CourseId=5
set @Prm_SpecializationId=0
declare @WhrStr varchar(500)
set @WhrStr = case @Prm_CourseId
when 0 then
'e.CourseId is null or e.CourseId is not null'
when -1 then
'e.CourseId is null or e.CourseId is not null'
when isnull(@Prm_CourseId,0) then
'e.CourseId is null or e.CourseId is not null'
else
'e.CourseId= '+Convert(varchar,@Prm_CourseId)
end
set @WhrStr = case @Prm_SpecializationId
when 0 then
'e.SpecializationId is null or e.SpecializationId is not null'
when -1 then
'e.SpecializationId is null or e.SpecializationId is not null'
when isnull(@Prm_SpecializationId,0) then
'e.SpecializationId is null or e.SpecializationId is not null'
else
'e.SpecializationId= '+Convert(varchar,@ Prm_SpecializationId)
end
print @WhrStr
exec(
'select f.EnquiryID,
e.[Name],
f.AttendedBy,
f.Remarks,
f.CreatedDate
from STD_FollowUp f
inner join
STD_Enquiry e
on f.EnquiryId=e.EnquiryId
where'+' '+@WhrStr
)
这里的问题是我希望得到@WhrStr中的第一和第二个案例语句的结果。但是WhrStr中的值是'e.SpecializationId为null或者.SpecializationId不为空'表示第一个被第二个覆盖。无论如何要追加到第二位。
答案 0 :(得分:4)
这在几个级别都不起作用。
CASE WHEN位需要在字符串分隔符“...THEN
'(e.CourseId is null or e.CourseId is not null)'...
“e.CourseId为null或e.CourseId不为null”是相同的“总是给我数据”
您只需要:
select f.EnquiryID,
e.[Name],
f.AttendedBy,
f.Remarks,
f.CreatedDate
from STD_FollowUp f
inner join
STD_Enquiry e
on f.EnquiryId=e.EnquiryId
答案 1 :(得分:1)
if (isnull(@Prm_CourseId, 0) = 0 or isnull(@Prm_CourseID, 0) = -1)
set @Prm_CourseId = null
if (isnull(@Prm_SpecializationId, 0) = 0 or isnull(@Prm_SpecializationId, 0) = -1)
set @Prm_SpecializationId = null
select f.EnquiryID,
e.[Name],
f.AttendedBy,
f.Remarks,
f.CreatedDate
from STD_FollowUp f
inner join
STD_Enquiry e
on f.EnquiryId=e.EnquiryId
where (@Prm_CourseId is null or e.CourseId = @Prm_CourseId)
or (@Prm_SpecializationId is null or e.SpecializationId = @Prm_SpecializationId)