In a sqlserver table of 200,000 plus records, i need help with faster concat of some columns data grouped by other columns. For example, sample data and expected results is shown below.
Here i need to concat the last columns ColumnA, ColumnB, ColumnC as pipe-delimited string, for the combination of these four like :
where KeyNumber=@strKeyNumber and Action=@strAction and Type=@strType and Code=@strCode
These four are the distinct combination.
I coded for this using t-sql STUFF function, but it is too slow. I also coded differently with while loop, but even that is too slow.
So i need help with getting a faster result.
The data in those columns A, B, C are long strings, so the concatenated string should be of type nvarchar(max).
Original data in table (duplicates can be there in some columns):
ID KeyNumber Action Type Code ColumnA ColumnB ColumnC
1 1111111111 AC1 TYPE1 CODE1 ValueA1 ValueB1 ValueC1
2 1111111111 AC1 TYPE1 CODE1 ValueA2 ValueB2 ValueC2
3 1111111111 AC1 TYPE1 CODE1 ValueA2 ValueB2 ValueC3
4 1111111111 AC1 TYPE1 CODE1 ValueA3 ValueB3 ValueC4
5 2222222222 AC2 TYPE2 CODE2 ValA1 ValB1 ValC1
6 2222222222 AC2 TYPE2 CODE2 ValA2 ValB2 ValC2
7 2222222222 AC2 TYPE2 CODE2 ValA3 ValB3 ValC3
8 2222222222 AC2 TYPE2 CODE2 ValA4 ValB4 ValC4
9 2222222222 AC2 TYPE2 CODE2 ValA4 ValB5 ValC4
Need the result data into a new table like below (duplicate values in above table should not be repeated here):
ID KeyNumber Action Type Code ColumnA ColumnB ColumnC
1 1111111111 AC1 TYPE1 CODE1 ValueA1|ValueA2|ValueA3 ValueB1|ValueB2|ValueB3 ValueC1|ValueC2|ValueC3|ValueC4
2 2222222222 AC2 TYPE2 CODE2 ValA1|ValA2|ValA3|ValA4 ValB1|ValB2|ValB3|ValB4|ValB5 ValC1|ValC2|ValC3|ValC4
You can check this one:
Also, I am not sure what method of string concatenation you are using. You can check this site for other techniques:
http://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/