替換Cursors和While Loops

來源:互聯網
上載者:User

一般在處理迴圈問題的時候,大家都會選擇Cursor,因為使用起來非常方便,代碼也很好實現,但是使用Cursor肯能會產生效能問題。那麼有什麼好的替代方法嗎?從網上看到的一篇文章很有借鑒意義(ReplacingCursors
and While Loops),改寫Cursor效能提高了幾倍.

 

所以我們在設計代碼的時候可以多考慮考慮是否不用Cursor也可以實現。 原始碼和改寫後的代碼如下:

 

--原始碼先查詢r查詢@tmp_id然後跟據@tmp_id獲得tmp_values然後更新表OutPut_tbl的值

             

            DECLARE temp_cursor
CURSOR FOR

            SELECT column_data

            FROM DB.dbo.many_tbl

            WHERE id
= @tmp_id  -- key data

            ORDER BY column_data

 

            OPEN temp_cursor

 

            FETCH NEXT
FROM temp_cursor

 

            INTO @tmp_data

 

            WHILE
@@FETCH_STATUS = 0

 

            BEGIN

   

            SELECT @tmp_values
= @tmp_values +
convert(varchar(20), @tmp_data)
+ ','

 

            FETCH NEXT
FROM temp_cursor

            INTO @tmp_data

            END

 

            CLOSE temp_cursor

            DEALLOCATE temp_cursor

 

            UPDATE DB.dbo.OutPut_tbl

            SET column_out
= @tmp_values

            WHERE id
= @tmp_id

 

--替換代碼(速度變快而且代碼簡潔)

 

CREATE function dbo.ufn_data_pivot(@id
as int)

      Returns varchar(20)

      AS

      BEGIN

          DECLARE @value
varchar(20)

          SET @value
= ''

          SELECT  @value
=  @value + convert(varchar(20), column_data)
+ ','

          FROM DB.dbo.many_tbl

          WHERE id = @id

          ORDER BY column_data

 

          Return @value

      END

 

UPDATE DB.dbo.OutPut_tbl

SET column_out= dbo.ufn_data_pivot(key_column)

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.