473,417 Members | 1,326 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,417 software developers and data experts.

How to Pass Comma-Separated String into Query

124 100+
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:

Expand|Select|Wrap|Line Numbers
  1. CREATE FUNCTION dbo.fnParseCSV
  2. (
  3. @ExcludedCourses varchar(255)
  4. )
  5. RETURNS varchar(255)
  6. AS
  7. BEGIN
  8.     DECLARE @ParsedExcludedCourses varchar(255)
  9.     DECLARE @ExcludedCourse varchar(10)
  10.     DECLARE @Pos int
  11.  
  12.     WHILE LEN(@ExcludedCourses) > 0
  13.     BEGIN
  14.         SET @Pos = CHARINDEX(',',@ExcludedCourses)
  15.  
  16.         IF @Pos = 0
  17.             BEGIN
  18.                 SET @ParsedExcludedCourses = ISNULL(@ParsedExcludedCourses,'') + '''' + LTRIM(@ExcludedCourses) + ''''
  19.             END
  20.         ELSE
  21.             BEGIN
  22.                 SET @ExcludedCourse = '''' + SUBSTRING(@ExcludedCourses, 1, @Pos - 1) + ''''
  23.                 SET    @ParsedExcludedCourses = @ExcludedCourse + ',' + ISNULL(@ParsedExcludedCourses,'')
  24.             END
  25.  
  26.         IF @Pos = 0
  27.             BEGIN
  28.                 SET @ExcludedCourses = ''
  29.             END
  30.         ELSE
  31.             BEGIN
  32.                 SET @ExcludedCourses = LTRIM(SUBSTRING(@ExcludedCourses, @Pos + 1, LEN(@ExcludedCourses) - @Pos))
  33.             END
  34.     END
  35.  
  36. RETURN @ParsedExcludedCourses
  37. END
  38. GO
  39.  
This is how it works when utilized:

Expand|Select|Wrap|Line Numbers
  1. DECLARE @courses varchar(255)
  2. SET @courses = 'COL 100,COM 100,MAT 100'
  3.  
  4. SELECT dbo.fnParseCSV(@courses)
  5.  
  6. Results: 'COL 100','COM 100','MAT 100'
  7.  
However, if I try executing the following query using the function I get zero results:

Expand|Select|Wrap|Line Numbers
  1. DECLARE @courses varchar(255)
  2. SET @courses = 'COL 100,COM 100,MAT 100'
  3.  
  4. SET @courses = dbo.fnParseCSV(@courses)
  5.  
  6. SELECT *
  7. FROM Courses
  8. WHERE CourseId IN (@courses)
  9.  
But if I execute the query as such I get results:

Expand|Select|Wrap|Line Numbers
  1. SELECT *
  2. FROM Courses
  3. WHERE CourseId IN ('COL 100','COM 100','MAT 100')
  4.  
I am at a loss as to why it's not working. Any help is much appreciated!
Aug 10 '10 #1

✓ answered by gpl

You have to return a table value -- here is an example for returning a set of ints
Expand|Select|Wrap|Line Numbers
  1. CREATE FUNCTION dbo.CsvToTable (@Array VARCHAR(1000))
  2. RETURNS @IntTable TABLE (IntValue int)
  3. AS
  4. BEGIN
  5.     DECLARE @Separator Char(1)
  6.     DECLARE @SeparatorPos int
  7.     DECLARE @ArrayValue Varchar(1000)
  8.  
  9.     SET @Separator = ','
  10.     SET @Array = @Array + ','
  11.  
  12.     WHILE PATINDEX('%,%', @Array) <> 0
  13.     BEGIN
  14.         SET @SeparatorPos = PATINDEX('%,%', @Array)
  15.         SET @ArrayValue = LEFT(@Array, @SeparatorPos -1)
  16.  
  17.         INSERT @IntTable VALUES(
  18.             CAST(@ArrayValue AS INT))
  19.  
  20.         SET @Array = STUFF(@Array, 1, @SeparatorPos, '')
  21.     END
  22.  
  23.     RETURN
  24. END
  25.  

4 5237
gpl
152 100+
You have to return a table value -- here is an example for returning a set of ints
Expand|Select|Wrap|Line Numbers
  1. CREATE FUNCTION dbo.CsvToTable (@Array VARCHAR(1000))
  2. RETURNS @IntTable TABLE (IntValue int)
  3. AS
  4. BEGIN
  5.     DECLARE @Separator Char(1)
  6.     DECLARE @SeparatorPos int
  7.     DECLARE @ArrayValue Varchar(1000)
  8.  
  9.     SET @Separator = ','
  10.     SET @Array = @Array + ','
  11.  
  12.     WHILE PATINDEX('%,%', @Array) <> 0
  13.     BEGIN
  14.         SET @SeparatorPos = PATINDEX('%,%', @Array)
  15.         SET @ArrayValue = LEFT(@Array, @SeparatorPos -1)
  16.  
  17.         INSERT @IntTable VALUES(
  18.             CAST(@ArrayValue AS INT))
  19.  
  20.         SET @Array = STUFF(@Array, 1, @SeparatorPos, '')
  21.     END
  22.  
  23.     RETURN
  24. END
  25.  
Aug 10 '10 #2
NeoPa
32,556 Expert Mod 16PB
As gpl says, the IN() structure takes either a list of items, or a table/cursor. To help understand, what you are trying to do is equivalent to :
Expand|Select|Wrap|Line Numbers
  1. SELECT *
  2. FROM   [States]
  3. WHERE  [StateAbb] IN('''IN'',''OH'',''NY''')
but you are really looking for a last line of :
Expand|Select|Wrap|Line Numbers
  1. WHERE  [StateAbb] IN('IN','OH','NY')
Multiple (list of) strings rather than a string formulated to contain strings.

Does that clarify?
Aug 11 '10 #3
bullfrog83
124 100+
OK, I understand now. The table function works very well and I like it better than what I had.
Aug 11 '10 #4
NeoPa
32,556 Expert Mod 16PB
Glad that helped :)

I agree about the table thingy too. I'm just getting into SQL Server myself from many years in Access. This is very much a server style thing (returning tables etc) and something I have to consider more going forward. I'm enjoying the extra scope and learning about capabilities just not available to Access work.
Aug 11 '10 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: Morris | last post by:
This may not be possible on the server side, so apologies if this is the wrong group for this post. My form consists of an unknown number of pairs of text boxes. They are named textbox_a and...
3
by: Carmen Z. | last post by:
do you know how to write a script so that the number that is coming from database with thousand separator (comma) will be eliminated and shown to a web page? so if the value is 1,200, i wanto...
2
by: A E | last post by:
Hi, I was wondering if there was a function that handles list elements of a comma delimited list? I need to be able to pass values as a comma delimited list, count the number of values, and...
4
by: newsprofile | last post by:
Can anyone point me in the right direction on how to deal with an xls flie. Sorry to be basic in my request, but the only other file I have to work with is pdf. I'm not sure, is xls the...
7
by: MattyWix | last post by:
Hi, How can I pass a semicolon or a comma as a macro argument. I wish to build an expression that in some cases has a comma - eg building a list of members for a structure, but in other...
13
by: artev | last post by:
If sort this work: var myarray= new Array(10,16,35,"0.1",8,4,22,19,1,22,35,9,26,38,40); with code function function1(a,b) {return a - b} var order02=new Array();...
6
by: pedroalves | last post by:
Hi all, This is not a question about how to #define COMMA , Please keep reading. Recently in binutils, we introduced a macro like this: #define STRING_COMMA_LEN(STR) \ (STR), ((STR) ?...
15
by: Lighter | last post by:
In 5.3.3.4 of the standard, the standard provides that "The lvalue-to- rvalue(4.1), array-to-pointer(4.2),and function-to-pointer(4.3) standard conversions are not applied to the operand of...
3
by: Junior | last post by:
I want to open a text file for reading and delineate it by comma. I also want any data surrounded by quotation marks that has a comma in it, not to count the commas inside the quotation marks ...
18
by: pinky8 | last post by:
I have an ASP page with a button and other things. When the button is clicked, it executes a javascript function which does: document.Form1.method = 'post'; document.Form1.action =...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.