Although I found answers for the individual parts of this question, I am posting this because I did not find an answer that consolidated these into one solution. Thought I would post my solution in case anyone else had the same question.
This is my first post and I am new to SQL-Server, so any comments or recommendations greatly appreciated.
The function below returns
1) A table that contains a row for each line of a string,
2) If string is empty or null, returns an empty table, and
3) If delimiter is null or empty returns single row table containing string.
I made it generic, so I could use it to brake up CSV into rows.
USAGE
@Delimiter: Value used to determine where to break up string for placement in table rows
@Remove_Delimiters: Determines whether @Delimiter kept in strings placed in table rows
@String: String to be split up and placed into table rows.
TO SPLIT STRING INTO LINES: Set @Delimiter CHAR(13)+CHAR(10)
TO SPLIT STRING INTO CSV Values: Set @Delimiter ','
NOTE: Another function required to remove extra white space
CREATE FUNCTION [dbo].[QaAuto_STRING_2TABLE]
(
@Remove_Delimiters BIT
, @Delimiter NVARCHAR(4000)
, @String NVARCHAR(4000)
)
RETURNS @Table TABLE
(
Row INT NOT NULL
, Value NVARCHAR(MAX)
)
AS
BEGIN
IF NOT (@String IS NULL OR @String = '')
BEGIN
WITH Cte AS
(
SELECT StartIndex = 0, EndIndex = 1
UNION ALL
SELECT EndIndex ,CHARINDEX(@Delimiter, @String, EndIndex) + LEN(@Delimiter)
FROM Cte WHERE EndIndex > StartIndex
)
INSERT INTO @Table SELECT
Row = ROW_NUMBER() OVER(ORDER BY(SELECT 1))
,Value =
CASE
WHEN @Delimiter IS NULL OR @Delimiter = '' THEN @String
ELSE SUBSTRING(@String, StartIndex,
CASE
WHEN EndIndex > LEN(@Delimiter)
THEN EndIndex-StartIndex - (LEN(@Delimiter)*@Remove_Delimiters)
ELSE LEN(@String) - StartIndex + LEN(@Delimiter)
END)
END
FROM Cte
WHERE StartIndex > 0
END
RETURN
END