2011-08-18 57 views
1

我想引用#temptable的第n行(在第二個SQL註釋如下)。什麼樣的表達可以讓我這麼做?在T-SQL/SQL Server 2000中,引用結果集的特定行

DECLARE @counter INT 
SET @counter = 0 
WHILE (@counter<count(#temptable)) 
--#temptable has one column and 0 or more rows 
BEGIN 
DECLARE @variab INT 
EXEC @variab = get_next_ticket 3906, 'n', 1 

INSERT INTO Student_Course_List 
       SELECT @student_id, 
       -- nth result set row in #temptable, where n is @count+1 
       @variab 

SET @counter = @counter +1 
END 

光標(將這項工作?):

for record in (select id from #temptable) loop 
--For statements, use record.id 
end loop; 

回答

0

而不是使用while循環(與反像你正在做的)來遍歷表,你應該使用cursor

語法應該是:

DECLARE @id int 
DECLARE c cursor for select id from #temptable 
begin 
    open c 
    fetch next from c into @id 
    WHILE (@@FETCH_STATUS = 0) 
    BEGIN 
     --Do stuff here 
     fetch next from c into @id 
    END 
    close c 
    deallocate c 
end 
+0

基於什麼邏輯? – JNK

+0

遍歷#temptable行。以下語法是否適用於SQL Server 2000? 用於記錄(從#temptable中選擇col_1)循環 /*語句,使用record.col_1 */ end loop; – ppecher

+0

@ppecher是Cursor適用於每個循環(但語法稍微複雜一些,請參閱我的msdn文檔鏈接)。他們使用SQL 2000. – Magnus

2

通常在像SQL Server這樣的關係數據庫中, fer做集操作。因此,即使對於非常複雜的查詢,最好也只需要INSERT INTO tbl SOMECOMPLEXQUERY。這比行處理要好得多。在一個複雜的系統中,使用遊標應該比較少見。

就你而言,看起來get_next_ticket過程執行一些重要的邏輯,無法以面向集合的方式完成。如果你不能以另一種面向集合的方式執行它的功能,那麼你會使用CURSOR

你會在你設定的SELECT whatever FROM #temptableOPEN它,FETCH從遊標聲明CURSOR成每列變量,然後在插入使用它們。

+0

+1我是一個基於系列的傢伙! –

+0

感謝您的光標總結。 – ppecher

-1

假設#TempTable有列富:

select Foo 
    from (select Row_Number() over (order by Foo) as Row, Foo from #TempTable) as Voot 
    where Row = @RowNumberIWant 

注意,這將適用於一個以#TempTable。

+1

不兼容SQL 2000 – Magnus

+0

(Whacks自己的鼻子)。我真的需要更加關注原始問題中明確指出的軟件版本。我的錯。 – HABO

相關問題