-- starting with the variables you will need in the processing part
declare @id int
declare @name sysname
declare @l nvarchar(max)
-- here comes the part for the cursor definition, which includes the SQL you want to run actually
-- if your process requires some "order" in the processing, put the corresponding ORDER BY in this SQL
declare c cursor for
select id, name from sysobjects;
open c;
--- get the first record, you need to specify a variable for each field in the cursor's SQL
fetch next from c into @id, @name;
-- continue to execute as long as the previous fetch succeeds (first one above or the fetch in the loop).
WHILE @@FETCH_STATUS = 0
BEGIN
-- process the data, this is the part you can modify as needed to your real needs
set @l = cast(@id as sysname) + ' ' + @name
print @l
-- now, get the next record
fetch next from c into @id, @name;
END
-- cleaning up the cursor resources
close c;
deallocate c;
The code is straightforward, nothing really tricky or complex, as by the book
-- starting with the variables you will need in the processing part
declare @id int
declare @name sysname
declare @l nvarchar(max)
-- here is the table variable definition, which lives only for the duration of the run and is cleaned up automatically
-- for "small" results, it will stay purely in memory; larger sets may be "stored" in the temp database
declare @c table ( id int , name sysname )
-- fill the table with data, update your select as you need it
-- if your process requires some "order" in the processing, still an ORDER BY here will be useless (unless you also use and need a TOP X clause) see below on where you have to put the ORDER BY
set nocount on
insert into @c (id, name) select id, name from sysobjects;
-- process, either if the above insert did at least 1 row, or if the below "delete" did indeed
while @@ROWCOUNT <> 0
begin
-- fetch 1 record from the table.
-- if your process requires some "order" in the processing, put the corresponding ORDER BY here
select top 1 @id = id, @name = name from @c
if @@ROWCOUNT <> 0
begin
-- process the data here, exactly the same as with the cursor example.
set @l = cast(@id as sysname) + ' ' + @name
print @l
end
-- here we delete the row from the temp table , which is nothing else than a processing queue table, hence
delete @c where id = @id
END
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (0)