Replace cursors and while Loops

Source: Internet
Author: User

Generally, you will choose cursor when dealing with loop problems, because it is very convenient to use and the code is well implemented. However, Using cursor can cause performance problems. So is there any good alternative? This article is useful for reference (replacingcursors ).
And while loops), rewrite cursor performance increased several times.

 

Therefore, when designing code, we can consider whether it can be implemented without using cursor. The source code and the modified Code are as follows:

 

-- The source code first queries the r query @ tmp_id, then obtains tmp_values with the data @ tmp_id, and then updates the value of output_tbl in the table.

Declare temp_cursor
Cursor

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

 

-- Replace the code (fast and concise)

 

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_key( key_column)

 

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.