--
Merge two columns in multiple rows and remove duplicate columns:
Create Table TB
(Col1 varchar (10 ),
Col2 varchar (10 ),
Col3 varchar (10 ),
Col4 varchar (10 ))
Go
Insert TB select '200', '200', 'A', 1
Insert TB select '200', '200', 'A', 1
Insert TB select '200', '200', 'B', 2
Insert TB select '200', '200', 'B', 2
Go
Create Function DBO. f_str (@ col3 varchar (10 ))
Returns varchar (8000)
As
Begin
Declare @ STR varchar (8000)
Set @ STR =''
Select @ STR = @ STR +
Case
When charindex (',' + col1 + '-', ',' + @ STR + '-') = 0 then col1 + '-'
Else''
End +
Case
When charindex ('-' + col2 + ',', '-' + @ STR + ',') = 0 then col2 + ','
Else''
End
From TB
Where col3 = @ col3
Return
Left (@ STR, Len (@ Str)-1)
End
Go
Select distinct newcol = DBO. f_str (col3), col3, col4 from TB
Drop table TB
Drop function f_str
/*
Newcol col3 col4
--------------------------------------
11111-222,1111-333 A 1
2222-999,3333-111 B 2
*/