replacing the cursors with set based

21 Views Asked by At

I have sql script with a lot of cursors which take too long to execute.I need to replace them with set based operations. I can't understand how can replace them and having the same results.Here is part of the code:

SET @CurAddress = Cursor static local FOR select did, isnull(StreetType.Cid,0) , isnull(StreetType.Abrev,'Street') from EntityAddress left join StreetType on EntityAddress.AddressTypeCid = StreetType.Cid where EntityDid=@entityId OPEN @CurAddress FETCH NEXT FROM @CurAddress INTO @entityAdressId, @streetTypeCid, @Street WHILE @@FETCH_STATUS = 0 BEGIN
SET @Street = @Street + ' ' + cast(@streetTypeCid as varchar(max)) + ' ' + @entityTypeAbrev + ' ' + cast(@entityNumber as nvarchar) UPDATE EntityAddress set Street=@Street where Did=@entityAdressId --print @Street + ' ' + cast(@streetTypeCid as varchar(max)) + ' ' + @entityTypeAbrev + ' ' + cast(@entityNumber as nvarchar) FETCH NEXT FROM @CurAddress INTO @entityAdressId, @streetTypeCid, @Street END CLOSE @CurAddress DEALLOCATE @CurAddress

I tried to replace the cursors by:

                    UPDATE ea
        SET 
        Street = CONCAT(st.Abrev, ' ', CAST(ea.did AS VARCHAR), ' ', et.Abrev, ' ',                     CAST(e.EntityNumber AS NVARCHAR))
        FROM EntityAddress ea
        JOIN Entity e ON ea.EntityDid = e.did
        LEFT JOIN StreetType st ON ea.AddressTypeCid = st.Cid
        JOIN EntityType et ON e.EntityTypeCid = et.Cid
        WHERE e.did = @entityId

But I think that this only does an update and nothing else...

Thanks in advance, Paulo Dias

0

There are 0 best solutions below