Cursor Action Without a Cursor
2
When you need to perform an action on a single row of data, many people turn to cursors. Cursors come with a lot of overhead in the database engine and can be confusing. Here's a way to get the same results without the overhead in a much simplier way.
-- Declare counter variables
-- @min will be the "current" record being examined
-- @max is the highest record.
declare @min int,
@max int
-- Declare a variable to hold the name of the table:
declare @tablename sysname
-- Set the initial values for the counter variables
-- @min is the lowest record meeting our condition,
-- @max is the highest:
SELECT @min = min(id),
@max = max(id)
FROM sysobjects
WHERE type = 'u'
-- Establish loop conditions:
-- Continue running until @min is equal to @max
while @min <= @max
begin
-- Populate the tablename variable based on
-- the current value of @min
SELECT @tablename = name
FROM sysobjects
WHERE id = @min
-- Execute the DBCC (or other operation)
dbcc checktable (@tablename)
-- Advance the counter.
-- Note the where condition is identical to the
-- initial loop condition with one additional
-- bit: "and id > @min"
SELECT @min = min(id)
FROM sysobjects
WHERE type = 'u'
AND id > @min
-- Exit the loop
end






There are currently no comments for this snippet.