SQL Server 2008 Beginner Script Question On: Delimited Strings with Substrings and case statements
I am trying to take a data string from one column and split it into several different columns. The question is I need to use a space (' ') as a delimiter and I'm not sure how? Also, I would need to incor开发者_运维问答porate case statements (I'm assumeing) in order to split with a substring in other areas.
Eample: Name Account 445566 0010020056893010445478008 AFD 369 I can use space as delimiter up to the point of the 001002... data string. That has to be futher broken down. Also, If I'm using space as a delimiter when I hit an area with multiple spaces how do I avoid empty columns?
Here's a split table-function:
CREATE FUNCTION [dbo].[Split]
(
@String varchar(max)
,@Delimiter char
)
RETURNS @Results table
(
Ordinal int
,StringValue varchar(max)
)
as
begin
set @String = isnull(@String,'')
set @Delimiter = isnull(@Delimiter,'')
declare
@TempString varchar(max) = @String
,@Ordinal int = 0
,@CharIndex int = 0
set @CharIndex = charindex(@Delimiter, @TempString)
while @CharIndex != 0 begin
set @Ordinal += 1
insert @Results values
(
@Ordinal
,substring(@TempString, 0, @CharIndex)
)
set @TempString = substring(@TempString, @CharIndex + 1, len(@TempString) - @CharIndex)
set @CharIndex = charindex(@Delimiter, @TempString)
end
if @TempString != '' begin
set @Ordinal += 1
insert @Results values
(
@Ordinal
,@TempString
)
end
return
end
Usage:
select
s.*
from dbo.Split('445566 0010020056893010445478008 AFD 369', ' ') as s
where s.StringValue != '' -- this condition will drop your extra spaces
Yields:
Ordinal StringValue 1 445566 11 0010020056893010445478008 12 AFD 13 369
Which you can break down further if necessary.
精彩评论