Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 query to convert spilit rows in csv

Author  Topic 

Arun.G
Yak Posting Veteran

81 Posts

Posted - 2010-07-10 : 01:05:50
Hi

I need a query to convert split rows based comma seprated


ex:

in my table one colmn, Roles is ther


Roles
2,3,5 like that


i need to spilit this roles like below:

Roles
2
3
5 like that

how to convert this?

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2010-07-10 : 02:03:21
Search for dbo.fnSplitString



N 56°04'39.26"
E 12°55'05.63"
Go to Top of Page

ms65g
Constraint Violating Yak Guru

497 Posts

Posted - 2010-07-10 : 03:55:05
My recommend is use only set-based techniques instead of multi-statement TVF.
First of all, you need to create auxiliary sequence number table and publishing some integers on it.
Second you can create a set-base approach for parsing the string.

--TVF for publishing and returning sequence numbers
CREATE FUNCTION dbo.Numbers (@N INT) RETURNS TABLE AS
RETURN (WITH RecCTE (nbr) AS
(SELECT 1
UNION ALL
SELECT nbr + 1 FROM RecCTE WHERE nbr < 100),

Nums (nbr) AS
(SELECT ROW_NUMBER() OVER(ORDER BY (SELECT 1))
FROM RecCTE AS C1
CROSS APPLY
RecCTE AS C2
CROSS APPLY
RecCTE AS C3)
SELECT nbr
FROM Nums
WHERE nbr <= @N);
GO

--Creating Number Table using TVF
SELECT n.nbr
INTO Nums
FROM dbo.Numbers(10000) AS n;
GO

--TVF for Splitting the String
CREATE FUNCTION dbo.splitter (@S VARCHAR(MAX), @D CHAR(1)) RETURNS TABLE AS
RETURN (SELECT CASE WHEN CHARINDEX(@D, @S + @D, nbr) - nbr = 0 THEN ''
ELSE SUBSTRING(@S, nbr, CHARINDEX(@D, @S + @D, nbr) - nbr)
END AS Word, nbr
FROM Nums
WHERE nbr <= LEN(@S)
AND SUBSTRING(@D + @S, nbr, 1) =@D);
GO


For using my approch just try it:

SELECT * FROM dbo.splitter ('1,2,3,4,5',',') ;

Also, an excellent article about splitting a string has written.
http://www.sqlservercentral.com/articles/Advanced+Querying/2547/

Have a nice vacation! Peso

______________________
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2010-07-10 : 05:48:42
We have gone through a number of thourough tests and found that tallytable split is ok when splitting longer words (5-6 characters and more).



N 56°04'39.26"
E 12°55'05.63"
Go to Top of Page
   

- Advertisement -