Friday, 17 December 2010

Similar sort of Cursor, but slightly different

Got fed up of modifying the previous cursor to do this simpler event.

Basically finds every table in a database and then returns the first row, prefixing the information returned for each table with the tablename.

Saves time running a select statement for each table and useful for finding a table that you know must exist, but isnt clearly named on the database.


declare @command varchar(255)
declare @tablename sysname
declare @count int
DECLARE StatusCursor CURSOR FOR

select a.name from sysobjects a where a.type ='U' order by a.name

Open StatusCursor
Fetch next from StatusCursor into @tablename
WHILE @@FETCH_STATUS = 0
BEGIN
exec ('select top 1 ' + '''' + @tablename + ''', * from ' + @tablename + '')
Fetch next from StatusCursor into @tablename
END
CLOSE StatusCursor
Deallocate StatusCursor

No comments:

Post a Comment