使用控制器的名称中选择查找表名

问题描述 投票:-2回答:1

我想从IDUser_ID表之一提取CompaniesContract价值,取决于ContorollerName值。

select P.TitleProject, P.StartDateProject, P.EndDateProject,P.ControllerID,P.RecordID,P.IsAllocated,P.ProjectStatus_ID,
CN.ControllerName,CN.PersianName,
PU.ProjectID,PU.UserID,PU.RoleID,
    CASE
        WHEN CN.ControllerName = 'Company' THEN 
            Companies.Id,Companies.[User_Id]
        WHEN CN.ControllerName = 'Contract' THEN 
            Contracts.Id,Contracts.[User_Id]
        END
from Projects P
    left outer join Controllers CN ON P.ControllerID = CN.Id
    left outer join ProjectUsers PU ON P.Id = PU.ProjectID
where P.IsAllocated = 1

例如,如果是ContorollerName“公司”,则select命令如下:

select P.TitleProject, P.StartDateProject, P.EndDateProject,P.ControllerID,P.RecordID,P.IsAllocated,P.ProjectStatus_ID,
CN.ControllerName,CN.PersianName,
PU.ProjectID,PU.UserID,PU.RoleID,
Companies.Id,Companies.[User_Id]
sql sql-server tsql
1个回答
1
投票

你是在正确的轨道上 - 使用left join。但是,你需要将表添加到from条款与适当的逻辑。

对于加盟的逻辑是很清楚。查询看起来是这样的:

select . . .,
       coalesce(c.id, co.id) as id,
       coalesce(c.user_id, co.user_id) as user_id
from Projects P left join
     Controllers CN 
     on P.ControllerID = CN.Id left join
     ProjectUsers PU
     on P.Id = PU.ProjectID left join
     companies c
     on c.? = ? and   -- no idea what the right join conditions are
        c.ControllerName = 'Company' left join
     contracts co
     on co.? = ? and  -- no idea what the right join conditions are
        co.ControllerName = 'Contract' 
where P.IsAllocated = 1
© www.soinside.com 2019 - 2024. All rights reserved.