0

我有 2 张桌子。一个具有管理器名称和一个空列,我想将数据从表 1(具有层次结构)插入到该列中。我想出了我们的插入片段,但我不想使用确切的名称,而是想使用变量将名称从表 2 传递到表 1,因此它是动态的。请让我知道这是否可以做到以及如何做到这一点。

UPDATE direct_manager_report 
Set Manager_level_number = 
(Select 'Manager_Level_0' from manager_hierarchy where level_0_manager_name = 'ABC'
UNION
Select 'Manager_Level_1' from manager_hierarchy where level_0_manager_name < > 'ABC' AND level_1_manager_name = 'ABC'
UNION
Select 'Manager_Level_2' from manager_hierarchy where level_1_manager_name < > 'ABC' AND level_2_manager_name = 'ABC'
UNION
Select 'Manager_Level_3' from manager_hierarchy where level_2_manager_name < > 'ABC' AND level_3_manager_name = 'ABC'
)
Where full_name = 'ABC'
4

1 回答 1

0

我相信如果您只想在一个地方放置经理的名字,这应该可行,假设查询返回所需的结果,除了必须在任何地方硬编码“ABC”:

DECLARE @man_name AS VARCHAR(50) = 'ABC'
UPDATE direct_manager_report 
Set Manager_level_number = 
(Select 'Manager_Level_0' from manager_hierarchy where level_0_manager_name = @man_name
UNION
Select 'Manager_Level_1' from manager_hierarchy where level_0_manager_name < > @man_name AND level_1_manager_name = @man_name
UNION
Select 'Manager_Level_2' from manager_hierarchy where level_1_manager_name < > @man_name AND level_2_manager_name = @man_name
UNION
Select 'Manager_Level_3' from manager_hierarchy where level_2_manager_name < > @man_name AND level_3_manager_name = @man_name
)
Where full_name = @man_name

您可以通过 select 语句填充 @man_name 变量: DECLARE @man_name AS VARCHAR(50) SET @man_name = (SELECT FROM)

如果您想遍历多个名称,您可以使用游标,或者您可以忘记变量并在更新中使用 JOIN。

于 2013-06-04T19:20:40.687 回答