Tuesday, November 10, 2009

Concatenate values in multiple columns into a single cell (SQL server 2005 and Oracle)

There are many instanc es wherein one is required to club values from different columns and rows into a condensed 1-cell format. Lets take an example:
Table - Tab_Emp :
NAME EMPLOYEE_CODE DESIGNATION
Ron 1 E
Paul 2 S
Maria 3 M
Rosy 4 R
The intended result is :
UNIFIED_INFORMATION
Name : Ron Code:1 Designation:E Name : Paul Code:2 Designation:S Name : Maria Code:3 Designation:M Name : Rosy Code:4 Designation:R

In SQL server 2005, we can create a cursor which reads through the table Tab_Emp and does the job for you. i have created a user defined function to do the same :

CREATE FUNCTION [Unify_Records]
RETURNS VARCHAR(8000)
AS
BEGIN --1
DECLARE @name VARCHAR(100)
DECLARE @code VARCHAR(100)
DECLARE @desig VARCHAR(100)
DECLARE @oneCELL varchar(8000)
SET @oneCELL = ''
Declare UNIFY_CURSOR Cursor For
SELECT * FROM Tab_Emp
BEGIN --2
OPEN UNIFY_CURSOR;
FETCH NEXT FROM UNIFY_CURSOR INTO @name,@code,@desig
WHILE (@@FETCH_STATUS = 0)
BEGIN -- 3
SET @oneCELL = @oneCELL +'NAME: '+ @name+', Code: '+ @code +', Desig: '+ @desig +''
FETCH NEXT FROM UNIFY_CURSOR INTO @name,@code,@desig
END --3
END --2
CLOSE UNIFY_CURSOR
DEALLOCATE UNIFY_CURSOR
return @oneCELL
END --1



  • For ORACLE , here is the generalised code :
    SELECT [Column1],
    SUBSTR(MAX(REPLACE(SYS_CONNECT_BY_PATH([Column2], '/'),'/','')),2) Concatenated_String
    FROM (select A.*,
    row_number() OVER (Partition by [Column1] order by [Column1]) ROW#
    from [Table_Name] A where [Column1] = ‘Ron’
    )
    START WITH ROW#=1
    CONNECT BY PRIOR [Column1]=[Column1] AND PRIOR row# = row# -1
    GROUP BY [Column1]
    Here all the values in [Column2] pertaining to [Column1] will be concatenated and the end result will be:
    [Column1]
    ∑[Column2]

No comments: