当前位置:Gxlcms > 数据库问题 > MSSQL将逗号分隔的字符串转换成列显示

MSSQL将逗号分隔的字符串转换成列显示

时间:2021-07-01 10:21:17 帮助过:3人阅读

Select 2 a.xm,xk=substring(a.xk,b.number,charindex(,,a.xk+,,b.number)-b.number) 3 from 4 表A a join master..spt_values b 5 ON b.type=p AND b.number BETWEEN 1 AND LEN(a.xk) 6 where 7 substring(,+a.xk,b.number,1)=,

--1.将字符串转换为列显示 
if object_id(tb) is not null drop table tb 
go 
create table tb([编号] varchar(3),[产品] varchar(2),[数量] int,[单价] int,[金额] int,[序列号] varchar(8)) 
insert into tb([编号],[产品],[数量],[单价],[金额],[序列号]) 
select 001,AA,3,5,15,12,13,14 union all
select 002,BB,8,9,13,22,23,24
go 
select [编号],[产品],[数量],[单价],[金额] 
,substring([序列号],b.number,charindex(,,[序列号]+,,b.number)-b.number) as [序列号] 
from tb a with(nolock),master..spt_values b with(nolock) 
where b.number>=1 and b.number<=len(a.[序列号]) and b.type=P
and substring(,+[序列号],number,1)=,
go 
drop table tb 
go 
/** 
编号   产品   数量          单价          金额          序列号 
---- ---- ----------- ----------- ----------- -------- 
001  AA   3           5           15          12 
001  AA   3           5           15          13 
001  AA   3           5           15          14 
002  BB   8           9           13          22 
002  BB   8           9           13          23 
002  BB   8           9           13          24 
*/ 
---------- 

 

--7.将字符串显示为行列 
if object_id(tb) is not null 
  drop table tb
create table tb
(
  id int identity(1,1),
  s nvarchar(100)
)
insert into tb(s) select 车位地址1,车位状况1|车位地址2,车位状况2|车位地址n,车位状况n;

with cte as(   select substring(s,number,charindex(|,s+|,number)-number) as ss     from tb with(nolock),master..spt_values with(nolock)       where type=P and number>=1 and number<=len(s) and substring(|+s,number,1)=| )
select left(ss,charindex(,,ss)-1)as s1,substring(ss,charindex(,,ss)+1,len(ss))as s2 from cte;
drop table tb /** s1 s2 ----------- ------------ 车位地址1 车位状况1 车位地址2 车位状况2 车位地址n 车位状况n

 

MSSQL将逗号分隔的字符串转换成列显示

标签:

人气教程排行