ASP前台搜索页面有两个输入框,一个是文本型company,一个是数字型mytype,两者都可为空,
存储过程如下
CREATE procedure Search
@Company varchar(100),
@mytype int
as
select * from [job]
where
company like %+@company+%
and mytype=@mytype
order by id desc
GO
如果只有
company like +%+isnull(@company,company)+%
这样的话,前台页面不输入关键字,可以找出所有信息,再加上一句
and mytype = +isnull(@mytype,mytype) ,如果前台mytype不填写为空的话,理论上要客户可以找到所有类别的数据记录,但实际无法找到任何数据,如果前台填写mytype的值,才可以找到表joblist里mytype字段=输入值的记录,现在想问,这种变量可为空且要判断变量等于的情况,以我上面的代码为例,要怎么写?谢谢大家!!!
--不是这样写吧?!!
--我帮你改了下,你试试
CREATE procedure Search
@Company varchar(100),
@mytype int
as
Declare @SQL varchar(255)
Set @SQL = select * from [job] where company like %+isnull(@company,)+%
if @mytype is not Null or @mytype<> Begin
Set @SQL = @SQL + and mytype=+cast(@mytype as varchar)
end
Set @SQL = @SQL + order by id desc
Execute @SQL
GO
其实问题很简单,
不应该是你这样的思路,你可以在前台程序中做SQL语句连接,判断,而在存储过程中不要做无谓的判断,
比如这样
ASP中:(简写)
dim sql as string
sql = "select * from job"
if Company <>"" then
sql = sql & " where company like %"&company&"%"
end if
if mytype <>"" then
这个你自己写下
end if
sql = sql & " order by id desc"
这样给存储传值的时候就传一个变量SQL就可以了,然后在存储过程中执行查询,我感觉这样比较合理,
你的那种做法也是可以的,你只要把我上面的思路带到存储过程中就OK了~~
明白了吧!
CREATE procedure Search
@Company varchar(100),
@mytype int
as
select * from [job]
where company like %+@company+%
and mytype=isnull(@mytype,mytype) --如果传入null则查出所有的mytype
--and mytype=(case @mytype when 0 then mytype else @mytype end) --如果传入0则查出所有的mytype。
order by id desc
GO