Looping a comma seperated list in SQL Server
I had answered a question recently in
dev-exchange forums about the looping through the comma separated list
values in SQL server. I thought to publish this here so that it is
useful others as well.
It uses charindex() to find poisition of comma within a string and then extract the values from it.
Here is the code:
have a good programming!
It uses charindex() to find poisition of comma within a string and then extract the values from it.
Here is the code:
| Code: |
| DECLARE @id INT
,@position INT , @idlist varchar(8000); SET @position=0; SET @idlist='1,2,3,4,5,6,7'; -- add a comma in the end to make the list loopable if (right(@idlist,1)<>',') SET @idlist=@idlist+','; WHILE charindex(',',@idlist)>0 BEGIN SET @id = cast(substring(@idlist,0, charindex(',',@idlist)) as int) print @id; SET @idlist = substring(@idlist, charindex(',',@idlist)+1, LEN(@idlist) - @position); END |
have a good programming!
Commentaires
Enregistrer un commentaire