DECLARE @TypeVar nvarchar(128), @StationVar nvarchar(128), @sql nvarchar(4000) print 'Start' DECLARE Typer CURSOR FOR SELECT Distinct Type,Station FROM temp_data OPEN Typer FETCH Typer INTO @TypeVar,@StationVar WHILE @@fetch_status <> -1 BEGIN SET @sql = N'select count(*) from temp_data where Type LIKE ''' + @TypeVar + ''' AND Station LIKE ''' + @StationVar + '''' EXEC sp_executesql @sql print @sql FETCH Typer into @TypeVar,@StationVar END CLOSE Typer DEALLOCATE Typer