在SQL Server 2012中使用游标时不执行打印语句

时间:2015-03-18 07:45:31

标签: sql-server sql-server-2012

我正在使用SQL Server 2012:这是使用游标的查询。

create table test(id varchar(10), name varchar(10))

insert into test values('1','a'),('2','b'),('3','c')

declare @id varchar(10)
declare @name varchar(10)

declare cur cursor for 
    select id, name  
    from test

open cur 

if @@CURSOR_ROWS > 0
begin 
    fetch next from cur into @id, @name

    while @@FETCH_STATUS=0
    begin
        print 'test'
        print @id+','+@name

        fetch next from cur into @id,@name
    end
end

close cur
deallocate cur

但是在结果集中它不会显示结果,但会成功执行。

预期结果

1,a
2,b
3,c

1 个答案:

答案 0 :(得分:1)

@@CURSOR_ROWS正在返回-1,这就是为什么它不会打印。

试试这个:

declare @id     varchar(10)
declare @name   varchar(10)

declare  cur cursor for 
    select id, name from test

open cur    
fetch next from cur into @id, @name

while @@FETCH_STATUS = 0
begin
    print @id+','+@name

    fetch next from cur into @id,@name
end

close cur
deallocate cur

详细了解@@CURSOR_ROWS