Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
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.
I am working in SQL Server Management Studio 2008 and would like to perform a SELECT statement via stored procedure. For simplification purposes let us assume that the table has only three columns (Name, Type, City). The City column can have multiple entries separated by a comma. I would like to duplicate each row with multiple cities respectively. Here is an example:Preceding SELECT:
Name Type City John Doe Owner Las Vegas, Miami, New York
Following SELECT:
Name Type City John Doe Owner Las VegasJohn Doe Owner MiamiJohn Doe Owner New York
Any help would be greatly appreciated.
madhivanan
Premature Yak Congratulator
22864 Posts
Posted - 2009-03-03 : 09:38:01
Read about UNPIVOTMadhivananFailing to plan is Planning to fail
TG
Master Smack Fu Yak Hacker
6065 Posts
Posted - 2009-03-03 : 09:40:41
UNPIVOT is for when you have multiple city columns (ie: city1, city2, etc.). In this case you need to use a split (or parsing) function. Search for that we have countless examples.Be One with the OptimizerTG
DECLARE @Sample TABLE ( Name VARCHAR(20), Type VARCHAR(20), City VARCHAR(200) )INSERT @SampleSELECT 'John Doe', 'Owner', 'Las Vegas, Miami, New York'-- BeforeSELECT *FROM @Sample-- AfterSELECT s.Name, s.Type, LTRIM(RTRIM(f.Data)) AS CityFROM @Sample AS sCROSS APPLY dbo.fnParseList(',', s.City) AS f