Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print statement not executing while using in cursor in SQL Server 2012

I am using SQL Server 2012: This is the query using cursors.

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

But in the result set it doesn't display results, but gets successfully executed.

Expected result

1,a
2,b
3,c
like image 905
Hare Rama Hare Krishna Avatar asked May 23 '26 14:05

Hare Rama Hare Krishna


1 Answers

@@CURSOR_ROWS is returning -1 that's why it's not printing.

Try this:

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

Read more about @@CURSOR_ROWS.

like image 163
Felix Pamittan Avatar answered May 25 '26 13:05

Felix Pamittan