SQL字符串分割
Create function [dbo].[SplitString]
(
@Input nvarchar(max),
@Separator nvarchar(max)=',',
@RemoveEmptyEntries bit=1
)
returns @TABLE table
(
[Id] int identity(1,1),
[Value] nvarchar(max)
)
as
begin
declare @Index int, @Entry nvarchar(max)
set @Index = charindex(@Separator,@Input)
declare @count int
set @count = 0
while (@Index>0)
begin
set @Entry=ltrim(rtrim(substring(@Input, 1, @Index-1)))
if (@RemoveEmptyEntries=0) or (@RemoveEmptyEntries=1 and @Entry<>'')
begin
if @count=1
begin
insert into @TABLE([Value]) Values(@Entry)
end
end
set @Input = substring(@Input, @Index+datalength(@Separator)/2, len(@Input))
set @Index = charindex(@Separator, @Input)
set @count = @count + 1;
end
--set @Entry=ltrim(rtrim(@Input))
--if (@RemoveEmptyEntries=0) or (@RemoveEmptyEntries=1 and @Entry<>'')
-- begin
-- insert into @TABLE([Value]) Values(@Entry)
-- end
return
end
--只打印12
declare @years nchar(10);
select @years = [Value] from [dbo].[SplitString2]('2012-12-45', '-', 1);
print @years