473,543 Members | 2,001 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to Pass Comma-Separated String into Query

124 New Member
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
4 5247
gpl
152 New Member
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,563 Recognized Expert Moderator MVP
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 New Member
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,563 Recognized Expert Moderator MVP
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
1742
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 textbox_b. I then split the comma separated list that gets posted: textbox_a = split(Request.Form("textbox_a"),",") for i = ubound(textbox_a)...
3
8283
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 display it as 1200 suppose %%Raw_Number%% is read off some database, and contains a number with thousand separator and we want to display the same...
2
4686
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 process the value of each. Did not think it was very efficient to loop through the contents of the list finding delimiters. TIA Alex
4
1953
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 better of two evils? Nick
7
12588
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 instances has a comma - eg building a list of arguments for a function. MattyWix
13
3180
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(); order02=myarray.sort(function1); but instead of 0.1 I use 0,1 (with comma) not work;
6
2599
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) ? sizeof (STR) - 1 : 0)
15
2612
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 sizeof." I think this rule is easy to understand. Because I can find the contexts of applying the rule as follows. (1) int* p = 0; int b1 =...
3
2212
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 if the file testfile.txt contains the following; 5,Tuesday,"May is a spring month",Father's Day 1,Saturday,"June,July and August",Independance Day
18
2876
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 = "AnotherASPpage.asp?p1=" + allFields1 + "&p2=" + allFields2 + "&p3=" + bVar; document.Form1.submit(); allFields1 represents all the fields in...
0
7412
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7355
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
5892
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5285
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
4900
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3395
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1830
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
979
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
648
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.