sql - 给出所选成本中心的名称 例如:
问题描述
CostCenterNo | CostCenterName | ParentCostCenterNo | |
--------------|-------------------|--------------------|-----|-----
761 | Power Plant | null | |
762 | Turbine | | 761 |
763 | Coolent | | 762 |
764 | Plant & Machinery | null | |
765 | Roller Machine | 764 | |
766 | Vehicle & Motors | null | |
767 | Hywa | | | 766
declare @CostCenterNo int
select @CostCenterNo = 763
with CostCen as(Select * from @table where CostCenterNo=@CostCenterNo
union all
select one.* from @Table as one
inner join CostCen cc on one.ParentCostCenterNo= cc.CostCenterNo)
select * from Costcen where CostcenterNo = @CostcenterNo
Select funcCostCenter(767) then it will Give Output- Vehicle & Motors
解决方案
看起来你想要
with CostCen as(
Select *
from costCenters
where CostCenterNo=@CostCenterNo
union all
select one.*
from costCenters as one
inner join CostCen cc on cc.ParentCostCenterNo = one.CostCenterNo
)
select *
from Costcen
where ParentCostCenterNo is null
编辑
标量函数使用上述查询从表中获取CostCenterName
给定的顶级:CostCenterNo
costCenters
create function funcCostCenter(@CostCenterNo int)
returns varchar(2000)
as
begin
declare @res varchar(2000);
with CostCen as(
select *
from costCenters
where CostCenterNo=@CostCenterNo
union all
select one.*
from costCenters as one
inner join CostCen cc on cc.ParentCostCenterNo = one.CostCenterNo
)
select @res = CostCenterName
from Costcen
where ParentCostCenterNo is null;
return @res;
end;
推荐阅读
- python - 熊猫:功能转变:“模棱两可的真值”
- python - 如何使用数据框将这些嵌套的 for 循环压缩为 python 中的列表理解?
- r - 在R中将表与一些重叠的行名组合起来
- python - 使用 elasticsearch_dsl 将 json 转换为 python 类
- ios - 主细节项目 - 从细节中删除主单元格
- css - Prettier 不适用于 CSS
- python - 根据所选窗口聚合数据框
- python - 从二维数组python中删除引号
- excel-formula - 如果单元格 U2 在 H2 中低于 25% 复制 E2,如果其 >25% 将 E2 复制到 I2 中?
- oracle - Oracle join 子句 where varchar2(4 byte) 导致问题