Statistics

Total Posts: 34
This Year: 0
This Month: 0
This Week: 0
Comments: 174


RSS 2.0   SocialTwist Tell-a-Friend


Admin

Sign In

Navigation


Recent Posts


On this page....

Converting a comma separated string having IDs to row result

Archives

 Full Archives By Category
 2007 Calendar View
<February 2009>
SunMonTueWedThuFriSat
25262728293031
1234567
891011121314
15161718192021
22232425262728
1234567

Categories

CDOSYS (1) Classic ASP (10) Command Line (2) Databases (16) Excel (1) HTML (1) IIS (10) Indexing Service (1) Internet Explorer (7) Media Streaming (1) MS.Net (2) SQA (7) SQL Server (16) Windows OS (2)

Blogroll - Fav Blogs


Acknowledgments

DasBlog Theme Design by: Tom Watts
E-mail: Send mail to the author(s)
Theme Image by: dreamLogic

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

Technology Blog

This post is in continuation to my previous post on “Converting Row Data as Comma Separated String”, which is to demonstrate exactly the opposite process “Converting a Comma Separated String Having IDs to Row Result”.

Example Requirement Case:

There is a table by name tbl_CityList (as in the snapshot below) with two columns, RecID which is an identity column and CityIDList which is VarChar(100) holding the RecID separated by comma from the table tbl_CityState (as explained in my previous post). 

The task is to convert the list of City IDs separated by comma into row result (as in the snapshot below)


Solution:

User Defined Function (UDF): The UDF func_CityByRow

CREATE FUNCTION dbo.func_CityByRow
(
@CityIDList VarChar(5000)
)
RETURNS @RtnValue TABLE
(
RecID INT identity(1,1),
StateName VarChar(50),
CityName VarChar(50)
)
AS
BEGIN
DECLARE @SplitOn as VarChar(10)
SET @SplitOn = ','

WHILE (Charindex(@SplitOn,@CityIDList)>0)
BEGIN
INSERT INTO
@RtnValue (StateName, CityName)
Select top 1 StateName,CityName from tbl_CityState
Where RecID=ltrim(rtrim(Substring(@CityIDList,1,Charindex(@SplitOn,@CityIDList)-1)))

SET @CityIDList = Substring(@CityIDList,Charindex(@SplitOn,@CityIDList)+len(@SplitOn),len(@CityIDList))
END

INSERT INTO @RtnValue (StateName, CityName)
Select top 1 StateName,CityName from tbl_CityState
Where RecID=ltrim(rtrim(@CityIDList))

RETURN

END


The function above takes the CityIDList as input parameter and returns table. The CityIDList is read item by item by eliminating comma and a new record is inserted in the return variable of table type.

DECLARE @cityIDList as varchar(500)
Select @cityIDList=CityIDList from tbl_CityList where RecID=1
SELECT a.StateName, a.CityName FROM dbo.func_CityByRow(@cityIDList) as a


Run the above code to get results as shown below.