like运算符在sql中使用索引
我正在使用SP根据位置和名称筛选数据。我不熟悉索引部件。我编写了一个如下所示的SP来从表中获取数据like运算符在sql中使用索引,sql,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 +'*"' s
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+'%'
这是一个查询版本
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
索引通常只在锚定到起始位置的类似条件下工作,例如“FOO%”。添加“%FOO”后,琐碎索引将被删除。所以我无法使用索引进行类似的搜索?或者我必须喜欢下面@nihat的答案这是正确的,不会使用Group_name index假设有人告诉你从电话簿中查找姓名包含“al”的人的列表,你将无法使用字母顺序,换句话说,电话簿的索引,你将不得不扫描所有内容,索引将以类似的方式工作,您可以使用我下面描述的任何一个。Thanq我将使用它。感谢重播,我可以这样做,就像我希望在1行或2行中查询的条件一样。