DECLARE @TypeVar nvarchar(4000), @sql nvarchar(4000) DECLARE Typer CURSOR FOR SELECT Distinct Type FROM temp_data FETCH Typer INTO @TypeVar while @@fetch_status <> 0 select @sql = 'count(*) from temp_data where Type = ' + @TypeVar PRINT @sql FETCH NEXT FROM Typer Into @TypeVar