求SQL遍历截取字符串
本帖最后由 xxaiwho 于 2013-11-20 18:28:54 编辑 从数据库中读取某一张表(数据若干),然后将某一字段进行截取
比如
字段A 字段B
a/a/c x
a/b/c x
切出来就变成
字段1 字段2 字段3 字段B
a a c x
b b c x
数据不止一条 ,是遍历切取,求完整sql(从读取到遍历到截取到输出),本人小白,求教
[解决办法]
呵呵,写的有点复杂,你看看是这样吗:
if object_id('[tb]') is not null drop table [tb]
go
create table [tb](A varchar(40),B varchar(10))
insert [tb]
select 'a/a/c','x' union all
select 'a/b/c','x'
go
if OBJECT_ID('tempdb..#temp1') is not null
drop table #temp1
if OBJECT_ID('tempdb..#temp2') is not null
drop table #temp2
select *,IDENTITY(int,1,1) id into #temp1
from tb
declare @sql nvarchar(4000)
set @sql = '';
;with t
as
(
select ID,
SUBSTRING(t.A, number ,CHARINDEX('/',t.a+'/',number)-number) as v,
b,
row_number() over(partition by id order by @@servername) as rownum
from #temp1 t,master..spt_values s
where s.number >=1
and s.type = 'P'
and SUBSTRING('/'+t.A,s.number,1) = '/'
)
select * into #temp2
from t
select @sql = @sql + ',max(case when rownum = '+CAST(rownum as varchar)+
' then v else null end) as 列'+CAST(rownum as varchar)
from #temp2
group by rownum
set @sql = 'select '+STUFF(@sql,1,1,'')+ ',b' +
' from #temp2 group by id,b'
--select @sql
exec(@sql)
/*
列1列2列3b
aacx
abcx
*/