3.4w+
社区成员
--测试数据
if not object_id(N'Tempdb..#T') is null
drop table #T
Go
Create table #T([id] int,[name] nvarchar(22),[content] nvarchar(29))
Insert #T
select 1,N'张三',N'电脑,打印机,手机' union all
select 2,N'李四',N'电脑,手机'
Go
--测试数据结束
Select id,name,value from #T CROSS APPLY(SELECT * FROM STRING_SPLIT(#T.content,','))t
--测试数据
if not object_id(N'Tempdb..#T') is null
drop table #T
Go
Create table #T([id] int,[name] nvarchar(22),[content] nvarchar(29))
Insert #T
select 1,N'张三',N'电脑,打印机,手机' union all
select 2,N'李四',N'电脑,手机'
Go
--测试数据结束
Select id,name,value from #T CROSS APPLY(SELECT * FROM STRING_SPLIT(#T.content,','))t
--建立数据
create table test21(id int,name nvarchar(50),content nvarchar(max))
insert into test21 values(1,'张三','电脑,打印机,手机'),(2,'李四','电脑,手机'),(3,'王五','')
--建立自定义函数
CREATE function [dbo].[Split]
(
@SourceSql varchar(max),
@StrSeprate varchar(10)
)
returns @temp table(value varchar(200))
as
begin
declare @i int
set @SourceSql=rtrim(ltrim(@SourceSql))
set @i=charindex(@StrSeprate,@SourceSql)
while @i>=1
begin
insert @temp values(left(@SourceSql,@i-1))
set @SourceSql=substring(@SourceSql,@i+1,len(@SourceSql)-@i)
set @i=charindex(@StrSeprate,@SourceSql)
end
if @SourceSql<>''
insert @temp values(@SourceSql)
return
end
--查询
select a1.id,a1.name,T1.value as content2 from test21 as a1
outer apply(select value from Split(a1.content,',')) T1