两个难点:
1、如何让Sql Server取到字符串中的数字,比如1、2、4和11、12、4虽然都是三位数字,但前者只有个位,后者含有十位和个位,用substring肯定是不行了。
2、如果取出了数字,还要依次遍历整张表,循环取ID,并去除重复ID
总得说来第一条智能取数比较折磨人。
标记一下,看有无高人进来
--------------------------------
仔细思考了下,还是做出来了,真的很折磨人。
下面的语句全部一下执行就可以看到结果了。
其中@strIn就是需要查找的字符串,如果要查看其他数据,修改这个值就可以了。
思路是把一个字段值变成多行数据,把','变为' union all'拼接语句实现。
--建立测试变量表@T,并赋值
declare @T table(id int,strnum varchar(50))
insert into @T
select 1,'1,2,4,5,8,9'
union all
select 2,'1,3,5,6,7,8,9,11'
union all
select 3,'3,4,5,6,7'
union all
select 4,'1,5,7,8,9'
union all
select 5,'3,5,6,9,11,12'
union all
select 6,'2,3,4,5,7'
union all
select 7,'3,4,5,6,7,8'
union all
select 8,'1,2,3,4,5,6,7,8,9,10'
union all
select 9,'1,7,8,9'
--@strIn查找的字符串
declare @strIn varchar(1000)
set @strIn = '1,11,12'
declare @strtable table(strSql varchar(4000))
insert into @strtable
Select 'select '''+cast(id as varchar(3))+''' as id,'''+replace(strnum,',',''' as num Union all Select ' + ''''+cast(id as varchar(3))+''' as id, ''') + ''' as num'
from @T
declare @comtable table(strSql varchar(4000))
insert into @comtable
select 'select '''+replace(@strIn,',',''' as num Union all Select ''' )+ ''' as num'
declare @textsql varchar(4000)
set @textsql = ''
Select @textsql=@textsql+strSql+' Union all ' from @strtable
set @textsql = substring(@textsql,1,len(@textsql)-10)
declare @comsql varchar(4000)
set @comsql = ''
Select @comsql=@comsql+strSql+' Union all ' from @comtable
set @comsql = substring(@comsql,1,len(@comsql)-10)
set @textsql = 'declare @Rtexttable table(id int,num varchar(3)) insert into @Rtexttable '+@textsql+
' declare @Rcomtable table(num varchar(3)) insert into @Rcomtable '+@comsql+' select distinct id from @Rtexttable a join @Rcomtable b on a.num = b.num'
exec (@textsql)
-------------------------
看了WHITE_WIN的,醍醐灌顶,豁然开朗。本人不喜欢用函数就改成存储过程了
declare @T table(id int,strnum varchar(50))
insert into @T
select 1,'1,2,4,5,8,9'
union all
select 2,'1,3,5,6,7,8,9,11'
union all
select 3,'3,4,5,6,7'
union all
select 4,'1,5,7,8,9'
union all
select 5,'3,5,6,9,11,12'
union all
select 6,'2,3,4,5,7'
union all
select 7,'3,4,5,6,7,8'
union all
select 8,'1,2,3,4,5,6,7,8,9,10'
union all
select 9,'1,7,8,9'
declare @strIn varchar(100)
set @strIn = '1,11,12'
declare @RT table (strnum varchar(30))
while charindex(',',@strIn)>0
begin
insert into @RT select left(@strIn,charindex(',',@strIn)-1)
set @strIn = substring(@strIn,charindex(',',@strIn)+1,len(@strIn))
end
If(len(@strIn)>0)
begin
insert into @RT select @strIn
end
select a.id from @T a, @RT b where ','+a.strnum+',' like '%,'+b.strnum+',%'
group by a.id
order by a.id
温馨提示:答案为网友推荐,仅供参考