sql 用函数来分割字符串
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
-- =============================================
-- Description: 分割字符串
-- =============================================
CREATE function [dbo].[split]
(
@SourceSql varchar(8000),
@StrSeprate varchar(10)
)
returns @temp table(F1 varchar(400),sequence int)
as
begin
declare @i int
declare @sequence int
set @sequence = 1;
set @SourceSql=rtrim(ltrim(@SourceSql))
set @i=charindex(@StrSeprate,@SourceSql)
while @i>=1
begin
insert @temp values(left(@SourceSql,@i-1),@sequence)
set @SourceSql=substring(@SourceSql,@i+1,len(@SourceSql)-@i)
set @i=charindex(@StrSeprate,@SourceSql)
set @sequence = @sequence+1
end
if @SourceSql<>''
insert @temp values(@SourceSql,@sequence)
return
end
set QUOTED_IDENTIFIER ON
go
-- =============================================
-- Description: 分割字符串
-- =============================================
CREATE function [dbo].[split]
(
@SourceSql varchar(8000),
@StrSeprate varchar(10)
)
returns @temp table(F1 varchar(400),sequence int)
as
begin
declare @i int
declare @sequence int
set @sequence = 1;
set @SourceSql=rtrim(ltrim(@SourceSql))
set @i=charindex(@StrSeprate,@SourceSql)
while @i>=1
begin
insert @temp values(left(@SourceSql,@i-1),@sequence)
set @SourceSql=substring(@SourceSql,@i+1,len(@SourceSql)-@i)
set @i=charindex(@StrSeprate,@SourceSql)
set @sequence = @sequence+1
end
if @SourceSql<>''
insert @temp values(@SourceSql,@sequence)
return
end
上面是分割的函数,创建在函数里
使用方法
如下:
SELECT CONVERT(INT,F1) FROM dbo.split('1,2,3,4,5,6', ',')