天天看點

SQL SERVER 把逗号隔開的字元串拆分成行,有效哦!

例如:比如 産品字段protest有逗号組合,現在把這些分割開來。

SQL SERVER 把逗号隔開的字元串拆分成行,有效哦!

變成如下:

SQL SERVER 把逗号隔開的字元串拆分成行,有效哦!

方法如下:

create table dbo.test_name(
id int null
,name varchar(10) null
,protest varchar(500) null 
);


insert into dbo.test_name values ('1','張三','電腦,電視機,掃地機');
insert into dbo.test_name values ('2','李四','掃地機');
insert into dbo.test_name values ('3','王五','');
insert into dbo.test_name values ('4','宋小','筆記本電腦,手機');



select a.id
      ,a.name
      ,a.protest
	  ,SUBSTRING(a.protest,number,CHARINDEX(',',a.protest+',',number)-number) as protestxx
  from test_name a  with(nolock) ,master..spt_values  with(nolock) 
  where type='p'
   and SUBSTRING(','+a.protest,number,1)=','
           

如果查詢出剔除空的資料如下:

select a.id
      ,a.name
      ,a.protest
	  ,SUBSTRING(a.protest,number,CHARINDEX(',',a.protest+',',number)-number) as protestxx
  from test_name a  with(nolock) ,master..spt_values  with(nolock) 
  where number >= 1 and number < len(a.protest)
   and type='p'
   and SUBSTRING(','+a.protest,number,1)=','
           
SQL SERVER 把逗号隔開的字元串拆分成行,有效哦!

繼續閱讀