获取变量中字符串值的相关数据

时间:2018-07-13 10:34:35

标签: sql sql-server sql-server-2014

我有一个变量@Projects,它的字符串数据的名称类似于'Project1;Project2;Project3'

我通过查询得到了这个结果:

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

我需要通过将ID中的这些项目中的Table 1进行比较,来获得变量中与项目相关的项目的名称。与Table 2.ID一起使用,以使Table 2.RelatedProject_IDTable 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            |   

在这种情况下,获得相关项目名称的正确方法是什么?

3 个答案:

答案 0 :(得分:1)

加入table_1table20以获取项目的ID。然后加入table_2以获取相关项目的ID。最后,再次加入table_1以获取相关项目的名称。

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(''));

(仅在table_1.project是唯一的情况下才能可靠工作。请考虑通过ID而不是名称将项目存储在table20中。)

答案 1 :(得分:1)

在下面检查此示例:

declare @projects varchar(max) = 'Project1;Project2;Project3'

Declare @table_1 table
     (Id int ,
      project varchar(15))

Insert @table_1 values (001, 'project1')
Insert @table_1 values (002, 'project2')
Insert @table_1 values (003, 'project3')
Insert @table_1 values (035, 'project35')
Insert @table_1 values (036, 'project36')
Insert @table_1 values (037, 'project37')

Declare @table_2 table
     (Id int ,
      RelatedProject_ID  int)

Insert @table_2 values (001, 035)
Insert @table_2 values (002, 036)
Insert @table_2 values (003, 037)
Insert @table_2 values (004, 038)
Insert @table_2 values (005, 039)

;with cte as (
    SELECT LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS projects
    FROM
    (
    SELECT CAST('<XMLRoot><RowData>' + REPLACE(@projects,';','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
    )t
    CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)
 )


 select t1m.project
 from @table_1 t1
 join @table_2 t2 on t2.id=t1.id
 join @table_1 t1m on t1m.id=t2.RelatedProject_ID
 join cte cte on t1.project=cte.projects

DEMO

答案 2 :(得分:0)

我想这就是你想要的

Select p.Project, p1.Project as RelatedProject
from Table_1 p 
join Table_2 a on p.Id = a.id
join Table_1 p1 on p1.Id = a.RelatedProject_ID