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)
 Dynamic Comma Seperated values to rows

Author  Topic 

Kalaiselvan
Posting Yak Master

112 Posts

Posted - 2011-08-05 : 10:25:40
Table1:

[Name] [Values]
Brand1 A,B,C,D
Categ1 A,B,C
Brand2 E,F,G

Need a Query with Output as:

[Brand1] [Brand2] [Categ1]
A E A
B F B
C G C
D NULL NULL


Please Help me in this ASAP.. Its urgent...

Regards,
Kalaiselvan R
Love Yourself First....

Transact Charlie
Master Smack Fu Yak Hacker

3451 Posts

Posted - 2011-08-05 : 11:40:27
It's not urgent -- I'm sure your server is not on fire.

Reccomendations:
1) Don't store data like this. Don't keep multiple values in the same row. Split them into multiple rows.
2) Don't do this in the db. It's a lot easier in the display layer.

Here's the kind of crazy you have to do to dynamically pivot this. As you can see it's pretty horrible.

-- Arnold Fribble's splitter
CREATE FUNCTION test.AFSplit (@sep char(1), @s varchar(512))
RETURNS table
AS
RETURN (
WITH Pieces(pn, start, stop) AS (
SELECT 1, 1, CHARINDEX(@sep, @s)
UNION ALL
SELECT pn + 1, stop + 1, CHARINDEX(@sep, @s, stop + 1)
FROM Pieces
WHERE stop > 0
)
SELECT pn,
SUBSTRING(@s, start, CASE WHEN stop > 0 THEN stop-start ELSE 512 END) AS s
FROM Pieces
)
GO

IF OBJECT_ID('tempDb..#sample') IS NOT NULL DROP TABLE #sample
CREATE TABLE #sample ([Name] VARCHAR(10), [Value] VARCHAR(8000))
INSERT #sample VALUES
('Brand1', 'A,B,C,D')
, ('Categ1', 'A,B,C')
, ('Brand2', 'E,F,G')
, ('ExtraRowA', 'HI THERE')

DECLARE @sql NVARCHAR(MAX)

SET @sql = N'
SELECT
[RowInd]'
SELECT @sql = @sql + N'
, MAX(CASE WHEN [Name] = ''' + [Name] + ''' THEN [splitValue] ELSE NULL END) AS [' + [Name] + ']'

FROM
(
SELECT DISTINCT [Name] FROM #Sample
)
AS s
ORDER BY
s.[Name]

SET @sql = @sql + '
FROM
(
SELECT
s.[Name] AS [Name]
, t.[s] AS [SplitValue]
, ROW_NUMBER() OVER ( PARTITION BY s.[Name] ORDER BY t.[s] ) AS [RowInd]
FROM
#sample AS s
CROSS APPLY test.AFSplit ( '','', s.[Value] ) AS t
)
AS piv
GROUP BY
piv.[RowInd]'

PRINT @sql
EXEC sp_executeSql @sql

GO

DROP FUNCTION test.AFSplit


Results:


RowInd Brand1 Brand2 Categ1 ExtraRowA
-------------------- ------- ------- ------- ----------
1 A E A HI THERE
2 B F B NULL
3 C G C NULL
4 D NULL NULL NULL

[/code]

Charlie
===============================================================
Msg 3903, Level 16, State 1, Line 1736
The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION
Go to Top of Page
   

- Advertisement -