我的问题是如何以智能方式改进查询字符串?
我想在参数为null时使用来自DB的参数查询数据,它将被删除。
我的查询字符串如下所示:
ALTER procedure [dbo].[spQueryDataFromCPREFROM]
@CompanyName varchar(50),
@TestDDL varchar(20),
@TesterName varchar(50),
@DatepickerForTestDate datetime,
@ApplyDate datetime,
@TestTypeDDL varchar(1),
@QueryString nvarchar(max)
as
begin
if @CompanyName is not null
and @TestDDL is not null
and @TesterName is not null
and @DatepickerForTestDate is not null
and @ApplyDate is not null
and @TestTypeDDL is not null
and @QueryString is not null
begin
select @QueryString = 'select * from [dbo].[CPREFROM] as CF where CF.[UNIT_TID] ='+ @CompanyName
+'and CF.[ELIGIBLE_RATING] ='+ @TestDDL
+'and CF.[Name] =' + @TesterName
+'and CF.[CHECKDATE] ='+ @DatepickerForTestDate
+'and CF.[APPLYDATE] =' + @ApplyDate
+'and CF.[A_S] =' + @TestTypeDDL
end
else if @CompanyName is null
and @TestDDL is not null
and @TesterName is not null
and @DatepickerForTestDate is not null
and @ApplyDate is not null
and @TestTypeDDL is not null
and @QueryString is not null
begin
select @QueryString = 'select * from [dbo].[CPREFROM] as CF where CF.[ELIGIBLE_RATING] ='+ @TestDDL
+'and CF.[Name] =' + @TesterName
+'and CF.[CHECKDATE] ='+ @DatepickerForTestDate
+'and CF.[APPLYDATE] =' + @ApplyDate
+'and CF.[A_S] =' + @TestTypeDDL
end
...
答案 0 :(得分:0)
以下可以为您提供帮助吗? 例如:
" CF [UNIT_TID] = CF [UNIT_TID]&#34。与1 = 1相同
select @QueryString = 'select * from [dbo].[CPREFROM] as CF where CF.[UNIT_TID] ='+ ISNULL(@CompanyName,'CF.[UNIT_TID]')
+'and CF.[ELIGIBLE_RATING] ='+ ISNULL(@TestDDL,'CF.[ELIGIBLE_RATING]')
+'and CF.[Name] =' + ISNULL(@TesterName,'CF.[Name]')
+'and CF.[CHECKDATE] ='+ ISNULL(@DatepickerForTestDate,'CF.[CHECKDATE]')
+'and CF.[APPLYDATE] =' + ISNULL(@ApplyDate,'CF.[APPLYDATE]')
+'and CF.[A_S] =' + ISNULL(@TestTypeDDL,'CF.[A_S]')
但是如果可能的值为null,则需要使用ISNULL来处理该值 因为" NULL = NULL"不是真的。
样品:
+'and ISNULL(CF.[Name],'''') =' + ISNULL(@TesterName,'ISNULL(CF.[Name],'''')')