我正在尝试学习高级sql以及如何使用系统查询(sql server).以下查询有点令人困惑.
CREATE PROC dbo.ShowHierarchy ( @Root int ) AS BEGIN SET NOCOUNT ON DECLARE @EmpID int, @EmpName varchar(30) SET @EmpName = (SELECT EmpName FROM dbo.Emp WHERE EmpID = @Root) PRINT REPLICATE('-', @@NESTLEVEL * 4) + @EmpName SET @EmpID = (SELECT MIN(EmpID) FROM dbo.Emp WHERE MgrID = @Root) WHILE @EmpID IS NOT NULL BEGIN EXEC dbo.ShowHierarchy @EmpID SET @EmpID = (SELECT MIN(EmpID) FROM dbo.Emp WHERE MgrID = @Root AND EmpID > @EmpID) END END GO
取自这里:
http://vyaskn.tripod.com/hierarchies_in_sql_server_databases.htm
每次运行查询时,@ EmpId参数如何递增?它会自己做吗?另外,每次递归都会增加@root吗?例如CEO是root,直接下属,直接下属现在是@root等.
谢谢
每次运行查询时,@ EmpId参数如何递增?它会自己做吗?
这个:
SET @EmpID = (SELECT MIN(EmpID) FROM dbo.Emp WHERE MgrID = @Root AND EmpID > @EmpID)
选择EmpID
大于已选择的最小值,并将其分配给@EmpID
.
当然,如果有的话,新的@EmpID
将比旧的更大,这意味着@EmpID
增加.