In the past, a buddy told me that cursor can be replaced by SQL. Why should it be replaced? It is always performance. At that time, I had limited understanding of SQL, but now I still have limited understanding. But at least I finally understood the problem.
In fact, it is very simple. After reading this example, you will know. I wrote several important performance indicators in my watch. Hope to help you
Code
Use Sql441
Go
Create table tbl_culsor2sql_pdt
(
Sn nvarchar ( 10 ) not null ,
LBL nvarchar ( 20 ) null
)
go
Create table tbl_culsor2sql_data
(
Sn nvarchar ( 10 ) not null ,
LBL nvarchar ( 20 ) null
)
go
Insert Into Tbl_culsor2sql_pdt
Values ( ' 1q2a3a4z ' , Null )
Insert Into Tbl_culsor2sql_pdt
Values ( ' 4f5d6r4f ' , Null )
Insert Into Tbl_culsor2sql_pdt
Values ( ' 9s9x3j7d ' , Null )
Insert Into Tbl_culsor2sql_pdt
Values ( ' 0x9d8k9x ' , Null )
Go
Insert Into Tbl_culsor2sql_data
Values ( ' 1q2a3a4z ' , ' Cndtd7550000001 ' )
Insert Into Tbl_culsor2sql_data
Values ( ' 4f5d6r4f ' , ' Cndtd7550000002 ' )
Insert Into Tbl_culsor2sql_data
Values ( ' 9s9x3j7d ' , ' Cndtd7550000003 ' )
Insert Into Tbl_culsor2sql_data
Values ( ' 0x9d8k9x ' , ' Cndtd7550000004 ' )
Go
SelectSN, LBLFromTbl_culsor2sql_pdt
Go
SelectSN, LBLFromTbl_culsor2sql_data
Go
/* ****** cursor ***** */
Update tbl_culsor2sql_pdt set LBL = null
-- declare a cursor
declare custom_cursor cursor
for select Sn, LBL from tbl_culsor2sql_data
-- declare a temporary various
declare @ Sn varchar ( 10 )
declare @ LBL varchar ( 20 )
--Open the cursor
OpenCustom_cursor
--Get the next record
Fetch Next FromCustom_cursorInto @ Sn,@ LBL
--Get successfully
While @ Fetch_status = 0
Begin
Update Tbl_culsor2sql_pdt
Set LBL = @ LBL
Where Sn = @ Sn
Fetch Next From Custom_cursor Into @ Sn , @ LBL
End
-- Delete the cursor
deallocate custom_cursor
/* *****
10 query plan
5 Table scan
5 Table update
5 Cluster Index insert on tempdb
*** ** */
/** ***** SQL ******/
UpdateTbl_culsor2sql_pdtSetLBL= Null
Go
Update Tbl_culsor2sql_pdt
Set LBL = Data. LBL
From Tbl_culsor2sql_pdt As PDT
Inner Join Tbl_culsor2sql_data As Data
On PDT. Sn = Data. Sn
/* *****
1 query plan
2 Table Scan
1 Table update
***** */