2012-04-25 17 views
5

Làm thế nào để có được kết quả trong WITH table AS vào vòng lặp CURSOR? Tôi đã từng hỏi về làm thế nào để có được kết quả đệ quy từ bàn của tôiLàm thế nào để sử dụng VỚI bảng AS kết quả trong vòng lặp con trỏ để chạy thủ tục được lưu trữ

How to read all records recursively and show by level depth TSQL

;with C as 
(
    definition ... 
) 

Tôi đã tạo ra vòng lặp CURSOR nơi tôi muốn chạy thủ tục lưu trữ cụ thể cho tất cả các kết quả trong table

declare @id int, @parent int 
declare cur cursor local fast_forward 
for 
    select id, parent from C 
open cur 
fetch next from cur into @id, @parent 
while @@fetch_status = 0 
    begin 
    exec storedProcedure @[email protected], @[email protected] 
fetch next from cur into @id, @parent 
end 
close cur 
deallocate cur 

Vấn đề là CURSOR không biết table từ WITH AS.

Invalid object name 'C'. 

Trả lời

3

Bạn có thể tạo một bảng temp hoặc một biến bảng để giữ hàng trả lại do bạn CTE truy vấn và sau đó bạn sử dụng bảng đó như là nguồn cho con trỏ.

declare @T table 
(
    id int, 
    parent int 
) 

;with C as 
(
    select 1 as id, 2 as parent 
) 
insert into @T 
select id, parent 
from C 

declare cur cursor for select id, parent from @T 
Các vấn đề liên quan