Search code examples
sqlsql-servercursor

SQL Server cursor is not looping although there are lots of records in the table


Although SELECT id, also FROM names WHERE isnull(also,'')<>''1 is returning 2000+ results, the following cursor not looping and I'm getting:

@count = 0

Code:

DECLARE @id BIGINT, @name NVARCHAR(1000)

DECLARE @aslo TABLE (id INT, name NVARCHAR(100))

DECLARE name_cur CURSOR FOR 
     (SELECT id, also 
      FROM names 
      WHERE ISNULL(also, '') <> '')

DECLARE @count INT = 0

OPEN name_cur

WHILE @@FETCH_STATUS = 0  
BEGIN  
   SET @count = @count + 1

   INSERT INTO @aslo (id, name)
       SELECT @id, * 
       FROM string_split(@name, ',')

   FETCH NEXT FROM name_cur INTO @id, @name;  
END  

CLOSE name_cur;  
DEALLOCATE name_cur;

SELECT @count
SELECT COUNT(*) FROM @aslo a

Solution

  • I think it is much simpler to do this without a cursor. This seems to be equivalent to what you want to do:

    INSERT INTO @aslo (id, name)
        SELECT n.id, ss.value as name
        FROM names n CROSS APPLY
             string_split(n.name, ',') ss;
    

    Here is a db<>fiddle.