I have the following slash-delimited example strings and need to split them:
Record---String
1--------ABC
2--------DEF/123
3--------GHI/456/XYZ
The strings will always have 1 - 3 parts; no more, no less.
To split them I have been using this function:
CREATE FUNCTION [dbo].[Split] (
@chunk VARCHAR(4000)
,@delimiter CHAR(1)
,@index INT
)
RETURNS VARCHAR(1000)
AS
BEGIN
DECLARE @curIndex INT = 0
,@pos INT = 1
,@prevPos INT = 0
,@result VARCHAR(1000)
WHILE @pos > 0
BEGIN
SET @pos = CHARINDEX(@delimiter, @chunk, @prevPos);
IF (@pos > 0)
BEGIN -- Characters between position and previous position
SET @result = SUBSTRING(@chunk, @prevPos, @pos - @prevPos)
END
ELSE
BEGIN -- Last Delim
SET @result = SUBSTRING(@chunk, @prevPos, LEN(@chunk))
END
IF (@index = @curIndex)
BEGIN
RETURN @result
END
SET @prevPos = @pos + 1
SET @curIndex = @curIndex + 1;
END
RETURN '' -- Else Empty
END
To split the strings, I call this function like so:
MyField1 = dbo.Split(MyInputString, '/', 0),
MyField2 = dbo.Split(MyInputString, '/', 1),
MyField3 = dbo.Split(MyInputString, '/', 2)
The expected results would be
Record 1:
MyField1 = ABC
MyField2 = NULL
MyField3 = NULL
Record 2:
MyField1 = DEF
MyField2 = 123
MyField3 = NULL
Record 3:
MyField1 = GHI
MyField2 = 456
MyField3 = XYZ
It is almost doing what I had hoped, except the last character of MyField1 for Record 1 is being truncated resulting in "AB" instead of "ABC". I believe this is because there is no slash delimiter for this one-part string.
Unfortunately, I did not write this function and my SQL skills are a bit weak. What should I change to make this function return proper results when there is no delimiter in the string?
Aucun commentaire:
Enregistrer un commentaire