When we process data, there is often a need to process data in a loop. If we can use CTE or other statements to process it, there is no problem, but sometimes it is difficult to process. At this time, we can choose to use cursor processing, choose Which form to use depends on efficiency. Generally, cursors are not efficient, but there are also suitable scenarios.
The cursor is divided into static cursor and dynamic cursor. The data of the static cursor is fixed and will not change due to the change of the data table; the data of the dynamic cursor changes with the change of the data table. The cursor is a dynamic cursor by default STATIC settings, OK, on the test data:
--Test Data if not object_id(N'Tempdb..#T') is null drop table #T Go Create table #T([id] int,[name] nvarchar(22)) Insert #T select 1,N'Zhang San' union all select 2,N'Li Si' union all select 3,N'Wang Wu' union all select 4,N'Zhao Liu' Go -- end of test data
Let's first look at the use of static cursors:
DECLARE @id INT , @name NVARCHAR(50) -- declare variables, data to be read DECLARE cur CURSOR STATIC -- declare a static cursor FOR SELECT * FROM #T OPEN cur -- open the cursor FETCH NEXT FROM cur INTO @id, @name --fetch data WHILE ( @@fetch_status = 0 ) -- determine if there is still data BEGIN SELECT 'Data: ' + RTRIM(@id) + @name UPDATE #T SET name='test' WHERE id=4 -- test static and dynamic FETCH NEXT FROM cur INTO @id, @name -- must write the next piece of data here END CLOSE cur -- close the cursor DEALLOCATE cur
The results are as follows, we can see that the data whose ID is 4 has not changed, it is still Zhao Liu, not the test after UPDATE:
Let's take a look at the dynamic cursor, just remove the STATIC keyword:
DECLARE @id INT , @name NVARCHAR(50) -- declare variables, data to be read DECLARE cur CURSOR -- remove the STATIC keyword FOR SELECT * FROM #T OPEN cur -- open the cursor FETCH NEXT FROM cur INTO @id, @name --fetch data WHILE ( @@fetch_status = 0 ) -- determine if there is still data BEGIN SELECT 'Data: ' + RTRIM(@id) + @name UPDATE #T SET name='test' WHERE id=4 -- test static and dynamic FETCH NEXT FROM cur INTO @id, @name -- must write the next piece of data here END CLOSE cur -- close the cursor DEALLOCATE cur
We look at the results and we can see that the data with ID 4 has been changed to test:
The above is the usage of cursors, as well as the introduction and use of dynamic and static cursors.