I currently have a view in SQL Server, something like this:
Table1:
Id
Desc
Mex
Table2:
Id
IdTab1
Desc
The view select everything from Table1 left joined on Table2 on Id - IdTab1
Now I have a table 3 joined with Table2 that has like these fields:
Table3:
Id
IdTab2
Code (VarChar(3))
I would like to have in the select of the view a new field Code that contains every code in table 3 concatenated with the char ' ' without changing the record displayed from the old query (so like doing a group by concat) every Code that matches the join.
I saw some other posts but neither of them used this kind of approach. For example using this:
declare @result varchar(500)
set @result = ''
select @result = @result + ModuleValue + ', '
from TableX where ModuleId = @ModuleId
But I have faced two problems. I could not use declare in the view (probably because of wrong syntax), and also I have to do this group by and I can't figure out how.
Example result basic view
ID | IDTAB2 | DESC1 | DESC2 | MEX
1 | 2 | aa | bb | 4
2 | 1 | ab | cc | 2
2 | 2 | bb | bc | 2
Example result joined Table3
ID | IDTAB2 | DESC1 | DESC2 | MEX | CODE
1 | 2 | aa | bb | 4 | CS
1 | 2 | aa | bb | 4 | NN
2 | 1 | ab | cc | 2 | AF
2 | 2 | bb | bc | 2 | DC
2 | 2 | bb | bc | 2 | KK
2 | 2 | bb | bc | 2 | JD
Example result needed
ID | IDTAB2 | DESC1 | DESC2 | MEX | CODENEW
1 | 2 | aa | bb | 4 | CS NN
2 | 1 | ab | cc | 2 | AF
2 | 2 | bb | bc | 2 | DC KK JD