2011-11-16 54 views
1

是否可以从LIKE查询的结果中获取片段字符串?Sql server LIKE从结果中获取片段

我不想尝试一些奇特的东西。我想要的只是TRIM查询字符串和左右两个字符(即50个字符)。

例如,如果像查询 “狐狸” 返回

"The quick brown fox jumps over the lazy dog" 

,我想

"brown fox jumps" 

更新,这就是我想出了。看来工作

declare @query nvarchar(100), @str nvarchar(100), @HowManyCharsToInclude int,  @startIndex int, @endIndex int, @cutfromLeft int, @cutFromRight int 
set @HowManyCharsToInclude = 10 
set @str='The quick brown fox jumps over the lazy dog'; 
set @query = 'fox' 
set @startIndex = (SELECT PATINDEX('%'+ @query+ '%', @str)) 
set @endIndex = (@startIndex + LEN(@query)) 
--set left, right cut 
if(@startIndex>@HowManyCharsToInclude) 
begin 
set @cutfromLeft = @HowManyCharsToInclude 
end 
else 
begin 
set @cutfromLeft = @startIndex 
end 
--set right cut 
if(LEN(@str) - @endIndex>@HowManyCharsToInclude) 
begin 
set @cutfromRight = @HowManyCharsToInclude 
end 
else 
begin 
set @cutfromRight = (LEN(@str) - @endIndex) 
end 

select SUBSTRING(@str, @[email protected], LEN(@query)+ @cutFromRight + @cutfromLeft) 
+0

因为它的工作原理,如果它提出你想要的响应时间,我想你有你的答案。 – xQbert

回答

0

要回答这个问题:是的,它是可能的:d

哦,等一下我应该解释

如何使用内置...字符串函数 MSFT String Functions

结合找到结果中的位置并知道结果的长度。

so psudo c颂像...

1获得启动文本的位置被搜索的字符串,如果0别的什么也不做(17)

2下获得被搜索字符串的长度(3)

3获得整个结果字符串的长度(3x)

4使用子字符串获取字符左边的子字符串(字段if(对于100 +长度的字符串,1到50的结果为1 - 50 < 1,然后为1的结果为1-50) 3)

但是,所有这些都增加了w ork会减慢你的结果,你最好在数据库层之外进行这种类型的操作。

正则表达式可能工作更快,我不得不考虑如何去做。

+0

谢谢,正在做这样的事情。请参阅我的更新 – nLL