2011-08-18 51 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

相关问题