PDA

View Full Version : جمله این الگو چی میشه؟



shahab_ksh
دوشنبه 25 تیر 1386, 17:17 عصر
دو جدول tbl_dir,tbl_file را در نظر بگیرید

در جدول tbl_dir فیلد های زیر را داریم

fld_id
fld_name
fld_ref

و سه سطر داده زیر را به ترتیب برای فیلدهای بالا داریم

1
windows
root
------------------------
2
program files
root
------------------------
3
system32
1
------------------------




در جدول tbl_file فیلد های زیر را داریم

fld_id
fld_name
fld_ref


1
boot.ini
1
----------------------
2
xp.dll
1
----------------------
3
kerd.dll
1
----------------------

چطور جمله ای بنویسم که مثلا نام فایلها و دایرکتوری های زیر مجموعه windows رو برام برگردونه
یعنی
system32
boot.ini
xp.dll
سوال دومم آیا روش ساده تری برای این نوع الگوها وجود دارد

AminSobati
دوشنبه 25 تیر 1386, 23:14 عصر
دوست عزیزم،
برای پیمایش ساختار درختی، روشهای متنوعی وجود داره. من این مثال رو برای دیتابیس Northwind میزنم. فرضا قصد داریم تمام افراد زیر مجموعه کارمند شماره 2 رو بدست بیاریم (ضمنا هر کارمند بوسیله فیلد ReportsTo کارمند رده بالای خودش رو معرفی میکنه)


DECLARE @ManagerID int
SET @ManagerID =2

--holds the output treelevel lets us isolate a level in the looped query
DECLARE @outTable table (employeeId int, ManagerID int, treeLevel int, processed bit)

--used to hold the level of the tree we are currently at in the loop
DECLARE @treeLevel as int
SET @treelevel = 1

--get the top level
INSERT into @outTable
SELECT employeeId, ReportsTo, @treelevel as treelevel, 0
FROM dbo.employees as employees
WHERE (employees.ReportsTo = @ManagerID)

WHILE (1 = 1) --imitates do...until construct
BEGIN

INSERT INTO @outTable
SELECT employees.employeeId, employees.ReportsTo,
ht.treelevel + 1 as treelevel,0
FROM dbo.employees as employees
JOIN @outTable as ht
ON employees.ReportsTo = ht.employeeId
--this where isolates a given level of the tree
WHERE ht.processed=0

IF @@rowcount = 0 BREAK


UPDATE @outTable SET processed=1
WHERE treeLevel-1<@treelevel

SET @treelevel = @treelevel + 1
END

--now look at the data in context of the employees we have inserted.
select * from @outTable