Click here to Skip to main content
15,896,153 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi

i have a stored procedure as below

SQL
CREATE PROC TEST1
@valueList varchar(8000)

AS

BEGIN

DECLARE @pos INT
DECLARE @len INT
DECLARE @value varchar(8000)

set @pos = 0
set @len = 0



WHILE CHARINDEX(',', @valueList, @pos+1)>0
BEGIN
    set @len = CHARINDEX(',', @valueList, @pos+1) - @pos
    set @value = SUBSTRING(@valueList, @pos, @len)
     
       print @value
        

    set @pos = CHARINDEX(',', @valueList, @pos+@len) +1
END



END


But when i input @valueList='A,B,C' it print only A AND B. why?
i want to print as below

A
B
C

THANKS
Posted
Updated 22-Jul-13 1:06am
v2

Because there are only two commas in your string - so the WHILE test fails when you have processed the second one, and printed the second value.

The easiest way round this is to do what I did with a similar problem: Using comma separated value parameter strings in SQL IN clauses[^]

What it does is add an extra comma to the end of the string, then replace all double commas with a single comma - this has the advantage of getting rid of empty entries as well.
 
Share this answer
 
Comments
hasbina 22-Jul-13 7:13am    
@OriginalGriff

thank you sir...thanks a lotsss
OriginalGriff 22-Jul-13 7:34am    
You're welcome!
It does not print the 'C' element of the list because the C is not followed by a comma, and after processing the B element, the while loop ends because it does not find another comma.

There are 2 simple solutions
1) As shown below : after the end of the while loop, print any remaining text
2) Add another 'dummy' comma separator at the end of the string before processing. This will ensure that the last element is processed by the code in the loop

DECLARE @pos INT
DECLARE @len INT

DECLARE @value nvarchar(4000)
 
set @pos = 0
set @len = 0
  
WHILE CHARINDEX(',', @valueList, @pos+1)>0
BEGIN
	set @len = CHARINDEX(',', @valueList, @pos+1) - @pos
	set @value = SUBSTRING(@valueList, @pos, @len)
	print @value

	set @pos = CHARINDEX(',', @valueList, @pos+@len) +1
END
print SUBSTRING(@valueList, @pos, @len)


Hope this helps
Ali.
 
Share this answer
 
Because your loop is executing twice. If you input @valueList='A,B,C,' rather than @valueList='A,B,C' (a comma extra at end) then the result appears actually what you want. So change your input or change as it execute one extra (add a comma at end if no comma exist at end) or using loop counter + 1 (count comma first and add +1 with it in a variable).
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900