如何查询存储过程到父表和子表?

时间:2019-05-30 10:16:12

标签: sql-server stored-procedures

我有一个作业表和一个存储过程,以显示每个用户的作业。 但是现在,我需要对同一列使用不同的查询。

现在我明白了:

SELECT 
    extrajobs.ExtraJobsID, prof.ProfileName, 
    functscope.Name AS functionscope1, 
    functscope.Name AS functionscope2, 
    extrajobs.FunctionScopeID, 
    users.UserID, extrajobs.CreateDate, 
    users.Username, extrajobs.LastUpdate, 
    prof.ProfileName, 
    extrajobs.Description, extrajobs.Day, extrajobs.Hours, 
    extrajobs.Remaining, extrajobs.Coordinator, 
    extrajobs.Feedback__On_Coordinator, extrajobs.Status_Coordinator, 
    extrajobs.Director, extrajobs.Status_Director, 
    extrajobs.Feedback__On_Director
    --SELECT DISTINCT(users.Username), prof.ProfileName
FROM 
    TBL_User AS users
JOIN 
    TBL_ExtraJobs AS extrajobs ON extrajobs.UserID = users.UserID
JOIN
    TBL_UserFunctionScope AS functscope ON extrajobs.FunctionScopeID= functscope.FunctionScopeID
JOIN
    REL_ProfileUser AS relprofileuser ON users.UserID = relprofileuser.UserID
JOIN
    TBL_Profile AS prof ON prof.ProfileID = relprofileuser.ProfileID
JOIN
    TBL_UserFunction AS funct ON funct.FunctionID = relprofileuser.FunctionID
WHERE 
    funct.Name = 'Extra-jobs'

Stored procedure result set

这是工作表:

TBL_FunctionScope

现在,在存储过程的结果中,我想将int functioscope1放置为funtionscope2的父级,例如TBL_FunctionScope

我该怎么做?

1 个答案:

答案 0 :(得分:0)

您需要将JOIN包含在TBL_FunctionScope和TBL_UserFunctionScope中,如下所示:

SELECT 
    extrajobs.ExtraJobsID, prof.ProfileName, 
    functscope.Name AS functionscope1, 
    functscope.Name AS functionscope2, 
    parentfunctscope.Name as parentfunction,
    extrajobs.FunctionScopeID, 
    users.UserID, extrajobs.CreateDate, 
    users.Username, extrajobs.LastUpdate, 
    prof.ProfileName, 
    extrajobs.Description, extrajobs.Day, extrajobs.Hours, 
    extrajobs.Remaining, extrajobs.Coordinator, 
    extrajobs.Feedback__On_Coordinator, extrajobs.Status_Coordinator, 
    extrajobs.Director, extrajobs.Status_Director, 
    extrajobs.Feedback__On_Director
    --SELECT DISTINCT(users.Username), prof.ProfileName
FROM 
    TBL_User AS users
JOIN 
    TBL_ExtraJobs AS extrajobs ON extrajobs.UserID = users.UserID
JOIN
    TBL_UserFunctionScope AS functscope ON extrajobs.FunctionScopeID= functscope.FunctionScopeID
JOIN
    TBL_FunctionScope as func ON extrajobs.FunctionScopeID= func.FunctionScopeID
LEFT JOIN
    TBL_UserFunctionScope AS parentfunctscope ON func.ParentScopeID = parentfunctscope.FunctionScopeID
JOIN
    REL_ProfileUser AS relprofileuser ON users.UserID = relprofileuser.UserID
JOIN
    TBL_Profile AS prof ON prof.ProfileID = relprofileuser.ProfileID
JOIN
    TBL_UserFunction AS funct ON funct.FunctionID = relprofileuser.FunctionID
WHERE 
    funct.Name = 'Extra-jobs'