日期:2014-05-17  浏览次数:20426 次

SQL2012中怎样一行一行 的显示出数据而不使用游标?
都说游标的性能差,建议不要用.
那么在SQL2012中怎样一行一行的显示出数据而不使用游标?例如下面的SQL

declare cData cursor for
select fno,fspec from t300km

open cData
declare @fno nvarchar(50)
declare @fspec nvarchar(50)

while @@FETCH_STATUS=0
begin
  print @fno+','+@fspec     --要做数据处理,这里print是方便测试
  fetch next from cData into @fno,@fspec
end
close cData
DEALLOCATE cData


------解决方案--------------------

declare @Rows int,
@Row int = 1,
@sPrint nvarchar(100)

declare @t table (
Row int identity(1,1) not null,
sPrint nvarchar(100)   null)
insert into @T
select isnull(fno,'')+','+isnull(fspec,'')     from t300km
set @Rows = @@ROWCOUNT
while(@Row <= @Rows)
begin
select @sPrint = sprint from @T where row = @Row
print @sPrint
set @Row = @Row + 1
end



------解决方案--------------------
用静态游标,不影响性能.

declare cData cursor static for
select fno,fspec from t300km
 
open cData
declare @fno nvarchar(50)
declare @fspec nvarchar(50)
 
while @@FETCH_STATUS=0
begin
  print @fno+','+@fspec     --要做数据处理,这里print是方便测试
  fetch next from cData into @fno,@fspec
end
close cData
DEALLOCATE cData