Search code examples
sqlsql-serversql-server-2014

Get related data of string values in variable


I have variable @Projects which has string data of names like 'Project1;Project2;Project3'

I have this result by query:

SELECT 
    @Projects = (SELECT Project_Title+';'
                 FROM Table20
                 FOR XML PATH(''))

I need to get name of related projects of projects in the variable by taking the ID of these projects in Table 1 to compare it with Table 2.ID for getting Table 2.RelatedProject_ID to compare it again with Table 1.

 Table_1                    Table_2

 Project  | ID  |          | ID  |  RelatedProject_ID  | 
 ---------+-----+          +-----+---------------------+
 Project1 | 001 |          | 001 |      015            |  
 Project2 | 002 |          | 002 |      020            | 
 Project3 | 003 |          | 003 |      031            | 
 Project4 | 004 |          | 004 |      032            | 
 Project5 | 005 |          | 005 |      017            |   

What is the correct way to get name of related projects in this case?


Solution

  • Join table_1 to table20 to get the IDs of projects. Then join table_2 to get the IDs of the related projects. Finally join table_1 again to get the names of the related projects.

    SELECT @RelatedProjects = (SELECT t1b.project + ';'
                                      FROM table20 t20
                                           LEFT JOIN table_1 t1a
                                                     ON t1a.project = t20.project_title
                                           LEFT JOIN table_2 t2
                                                     ON t2.id = t1a.id
                                           LEFT JOIN table_1 t1b
                                                     ON t1b.id = t2.related_project
                               FOR XML PATH(''));
    

    (Only works reliable if table_1.project is unique. Consider to store the projects in table20 by their IDs not by their name.)