I wrote a function that takes a comma-separated string, parses out the individual values, places quotations around each value and a comma in-between each value so that they can be processed in a query. This is my function:
This is how it works when utilized:
However, if I try executing the following query using the function I get zero results:
But if I execute the query as such I get results:
I am at a loss as to why it's not working. Any help is much appreciated!
Code:
CREATE FUNCTION dbo.fnParseCSV
(
@ExcludedCourses varchar(255)
)
RETURNS varchar(255)
AS
BEGIN
DECLARE @ParsedExcludedCourses varchar(255)
DECLARE @ExcludedCourse varchar(10)
DECLARE @Pos int
WHILE LEN(@ExcludedCourses) > 0
BEGIN
SET @Pos = CHARINDEX(',',@ExcludedCourses)
IF @Pos = 0
BEGIN
SET @ParsedExcludedCourses = ISNULL(@ParsedExcludedCourses,'') + '''' + LTRIM(@ExcludedCourses) + ''''
END
ELSE
BEGIN
SET @ExcludedCourse = '''' + SUBSTRING(@ExcludedCourses, 1, @Pos - 1) + ''''
SET @ParsedExcludedCourses = @ExcludedCourse + ',' + ISNULL(@ParsedExcludedCourses,'')
END
IF @Pos = 0
BEGIN
SET @ExcludedCourses = ''
END
ELSE
BEGIN
SET @ExcludedCourses = LTRIM(SUBSTRING(@ExcludedCourses, @Pos + 1, LEN(@ExcludedCourses) - @Pos))
END
END
RETURN @ParsedExcludedCourses
END
GO
Code:
DECLARE @courses varchar(255) SET @courses = 'COL 100,COM 100,MAT 100' SELECT dbo.fnParseCSV(@courses) Results: 'COL 100','COM 100','MAT 100'
Code:
DECLARE @courses varchar(255) SET @courses = 'COL 100,COM 100,MAT 100' SET @courses = dbo.fnParseCSV(@courses) SELECT * FROM Courses WHERE CourseId IN (@courses)
Code:
SELECT *
FROM Courses
WHERE CourseId IN ('COL 100','COM 100','MAT 100')
Comment