我想进行搜索查询 查询来自asp.net Web应用程序的接受参数
当@firstName正确搜索但不使用between子句时
create proc test
@From Datetime,
@to Datetime,
@firstName varchar(50)
as
begin
select * from Employee
where Empfname=(case when @firstName != '' then @firstName else Empfname end)
and 1=(case when @From != null and @From != '' and @to != null and @to != ''
then EmpJoinDate between @From and @to else 1 end) end
答案 0 :(得分:1)
首先,我鼓励您在使用"通配符"时保持一致。您的代码似乎混淆了空字符串和NULL
。只需使用NULL
值表示允许任何内容的约定。
然后,从case
子句中删除where
并明确列出逻辑。这是一种方法:
create proc test (
@From Datetime,
@to Datetime,
@firstName varchar(50)
) as
begin
select e.*
from Employee e
where (Empfname = @firstName or @firstname is null) and
((@from is null and @to is null) or
(@from is null and EmpJoinDate <= @to) or
(@to is null and EmpJoinDate >= @from) or
(EmpJoinDate >= @from and EmpJoinDate <= @to)
);
end;
然后,您应该重新考虑存储过程的需要。你拥有的东西更适合表值函数。
答案 1 :(得分:0)
取代基于案例的比较。而不是
Empfname=(case when @firstName != '' then @firstName else Empfname end)
写
(@firstName='' OR Empfname=@firstName)
而不是
1=(case when @From != null ...
写
(@From='' OR @To='' OR EmpJoinDate BETWEEN convert(datetime, @From)
AND convert(datetime, @To))
注意:如果您使用参数的NULL
值代替空字符串''
,请不要应用=
和!=
操作员给他们,因为他们不工作。相反,请使用IS NULL
和IS NOT NULL
运算符。
答案 2 :(得分:0)
我的语法不完全正确,因为我不知道您要定位的数据库。一般情况下,我会将参数更改为not null(必需),测试任何一个或多个空字符串,如果这样,则执行参数化SQL。
create proc test
@From Datetime not null,
@to Datetime not null,
@firstName varchar(50) not null
as
begin
If @From != '' or @To != '' or @FirstName != ''
select * from Employee
where Empfname= @firstName
and EmpJoinDate between @From and @to
end if
end
答案 3 :(得分:0)
尝试修复您的程序:
-- test '20160101','20160810', 'z'
alter proc test
@From Datetime,
@to Datetime,
@firstName varchar(50)
as
DECLARE @DateCondition varchar(100),
@FNameCondition VARCHAR(200),
@SQLStr VARCHAR(2000)
begin
IF @From <> '' AND @To <> ''
SET @DateCondition = ' EmpJoinDate between ''' + CONVERT(VARCHAR(20),@From) + ''' and ''' + CONVERT(VARCHAR(20),@To) + ''''
IF @firstName != ''
SET @FNameCondition = '''' + @firstName + ''''
ELSE
SET @FNameCondition = ' Empfname '
SET @SQLStr = '
select * from Employee
where Empfname= ' + @FNameCondition + '
and ' + @DateCondition
PRINT (@SQLStr)
EXEC (@SQLStr)
END
Go