ALTER FUNCTION [dbo].[fnt_SplitString]
(
@p1 varchar(Max),
@p3 varchar(255)
)
RETURNS
@Table_Var TABLE
(
c1 varchar(max)
)
AS
BEGIN
declare @p2 varchar(max)
set @p2=rtrim(ltrim(@p1))
declare @pos1 int
declare @pos2 int
set @pos1=1
set @pos2=1
while (@pos1<len(@p2))
begin
set @pos1=charindex(@p3,@p2)
if (@pos1=0)
begin
insert into @table_var values(@p2)
set @pos1=len(@p2)
end
else
begin
insert into @table_var values(left(@p2,@pos1-1))
set @p2=right(@p2,len(@p2)-@pos1)
set @pos1=0
end
end
RETURN
END
'调用方式
Select C1,(Row_Number() Over(Order By @@Cursor_Rows)) As C2 From dbo.Fnt_SplitString('ID,WBS,Quantity,MPSNO,Attribute,FileContent,MaterielName,MaterielCode,ExportAccount',',')
方法二:
1 ALTER function [dbo].[SplitString]
(
@Input nvarchar(max),
@Separator nvarchar(max)=',',
@RemoveEmptyEntries bit=
)
returns @TABLE table
(
[Id] int identity(,),
[Value] nvarchar(max)
)
as
begin
declare @Index int, @Entry nvarchar(max)
set @Index = charindex(@Separator,@Input)
while (@Index>)
begin
set @Entry=ltrim(rtrim(substring(@Input, , @Index-)))
if (@RemoveEmptyEntries=) or (@RemoveEmptyEntries= and @Entry<>'')
begin
insert into @TABLE([Value]) Values(@Entry)
end
set @Input = substring(@Input, @Index+datalength(@Separator)/, len(@Input))
set @Index = charindex(@Separator, @Input)
end
set @Entry=ltrim(rtrim(@Input))
if (@RemoveEmptyEntries=) or (@RemoveEmptyEntries= and @Entry<>'')
begin
insert into @TABLE([Value]) Values(@Entry)
end
return
end
Select * From [dbo].[SplitString]('ID,WBS,Quantity,MPSNO,Attribute,FileContent,MaterielName,MaterielCode,ExportAccount',',',)