喜欢在sql中使用索引的运算符

时间:2014-02-08 07:46:57

标签: sql

我正在使用SP根据位置和名称过滤数据。我是索引部分的新手。我写了一个如下的SP来从表中获取数据

create procedure [dbo].[Seach_University]
(
 @Search varchar(100),
 @SerLocation varchar(100)
)
as begin
declare @x varchar(100) = '"'+@search+'*"',
        @y varchar(100) = '"'+@SerLocation +'*"'

select * from tbl_Groups where contains(Group_Name ,@x ) and  contains(Location,@y)
end

当我发送给关键字时,此代码非常有用。当我只发送一个值(@SerLocation或@search)数据未来时,即出现null时,就会出现问题。

任何人都可以帮助我,即使是空值,它应该像下面的代码一样工作

select * from tbl_Groups where Group_Name like '%'+@Search+'%' and  Location like '%'+@SerLocation+'%'

1 个答案:

答案 0 :(得分:0)

这是一个查询版本

select * from tbl_Groups where 
(@search is not null and @serLocation is not null and 
    contains(Group_Name ,@x ) and  contains(Location,@y)) or 
(@search is not null and @serLocation is null and 
    contains(Group_Name ,@x ) ) or 
(@search is  null and @serLocation is not null and 
    contains(Location,@y)) 

长版:您可以将if语句添加到您的过程体中,如此

if @search is not null and @serLocation is not null 
begin 
select * from tbl_Groups where contains(Group_Name ,@x ) and  contains(Location,@y)
end 

if @search is not null and @serLocation is  null 
begin 
select * from tbl_Groups where contains(Group_Name ,@x ) 
end 

if @search is  null and @serLocation is not null 
begin 
select * from tbl_Groups where  contains(Location,@y)
end