0

一種の再帰ループを実行する SQL Server 2008 R2 UDF があります。つまり、Employees というテーブルがあり、列の 1 つに別の Employee ID (彼の上司) を格納しています。

従業員IDを取得すると、彼の下の部門全体を知ることができなければなりません. 例: 従業員 Joe (ID:1) は Robert (ID:2) で働いています。従業員 Robert (ID:2) は Michelle (ID:3) で働いています。

Michelle の下にあるすべての従業員、つまり Robert と Joe の給与を数えることができなければなりません (同じテーブルにあるとしましょう)。

これまで、Michelle より下のすべての従業員 ID を含むテーブルを返す UDF を作成し、クエリの where で EXISTS 句を使用しましたが、パフォーマンスは非常に低かったです。

皆さん、別のアイデアはありますか?

ありがとうございました!

4

1 に答える 1

1

すべての従業員を検索するには、ループではなく再帰的なCTEを使用する必要があります。WHILE私はあなたのテーブルやデータを持っていないので、私はいくつかを作りました:

create table Employees (
    ID int not null primary key,
    Name varchar(20) not null,
    BigBossID int null foreign key references Employees(ID),
    Salary decimal(18,4) not null
)
go
insert into Employees (ID,Name,BigBossID,Salary) values
(1,'Joe',2,2.50),
(2,'Robert',3,19000.75),
(3,'Michelle',null,1234567890.00)

次に、このクエリを使用して、Michelle より下のすべての従業員を検索できます。

declare @RootID int
set @RootID = 3
;With EmployeesBelowRoot as (
    select ID from Employees where BigBossID = @RootID
    union all
    select e.ID from Employees e inner join EmployeesBelowRoot ebr on e.BigBossID = ebr.ID
)
select SUM(Salary) from Employees where ID in (select ID from EmployeesBelowRoot)

(価値があると思われる場合) CTE ( EmployeesBelowRoot) を UDF に@RootID配置し、それをパラメーターとして呼び出すこともできますが、今のところクエリに直接入れただけです。

于 2013-08-30T07:01:32.820 に答える