您的位置:首页 > 数据库

MS-SQL SERVER从字符串中搜索符合指定范围的数值--【叶子】

2011-07-09 10:01 701 查看
需求贴: http://topic.csdn.net/u/20110708/17/334a25b1-ab00-4fab-bdfa-2fcd319411a4.html 主要描述:
/*
colname
------------
12/31/75
34/67/94/113
*/
例如上表,只有一个字段nvarchar类型的。
搜索的时侯输入一个数值15,那么搜索的范围就是5-25,第一行的12符合这个范围,第一行就搜出来。
例如输入70,第一行的75,和第二行的67都符合搜索范围。

--第一种方法(借助表变量或是临时表)
set nocount on

--测试数据
declare @table table (colname nvarchar(12))
insert into @table
select '12/31/75' union all
select '34/67/94/113' union all
select '1/56/3/16' union all
select '34/23/12/24' union all
select '90/34/45/47'

--设置参数
declare @i int;set @i=70
declare @j int;set @j=@i-10

--定义表变量,做辅助表
declare @t table(id int)
while @j<=@i+10
begin
    insert into @t select @j
    set @j=@j+1
end

--根据参数进行搜索
select a.* from @table a left join @t b
on charindex('/'+ltrim(b.id)+'/','/'+a.colname+'/')>0
where b.id is not null

--运行结果
/*
colname
------------
12/31/75
34/67/94/113
*/


--第二种方法借助master..spt_values

--测试数据
declare @table table (colname nvarchar(12))
insert into @table
select '12/31/75' union all
select '34/67/94/113' union all
select '1/56/3/16' union all
select '34/23/12/24' union all
select '90/34/45/47'
select * from @table

--设置参数
declare @i int;set @i=70

--进行搜索
select a.* from @table a 
left join  master..spt_values b
on charindex('/'+ltrim(b.number)+'/','/'+a.colname+'/')>0
where b.[type]='P' and b.number is not null
and number between @i-10 and @i+10

--运行结果
/*
colname
------------
12/31/75
34/67/94/113
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: