Use SQL Cursor cursor

Contents

Use SQL Cursor cursor

In the past two days to do data migration between the old and new systems, access to sql cursor, record summary.

Our demand is to require map multiple tables, and the results are updated to a target table, the old and new systems do A / B Testing, so when the old table there are any updates, such as add, delete, change, we must updates to the new table.

I had chosen solution is to use a batch Insert, but encountered a need to insert the table map relationships, where a field is another table id just insert the data, it can only be solved by recycling. Looked around SQL for loop, to implement a bit laborious. Of course, a useful while door temporary tables and other solutions are welcome to explore the e-mail, use the cursor here to share the experience.

As I understand it, the cursor can be thought of as a pointer to a pointer to use when we need to do:

  • Statement Pointer
  • A pointer to the address
  • Get a pointer to content
  • Moving the pointer to the new address

Thus it appreciated that the cursor is more convenient, the following example to illustrate a method using the cursor:

      
      
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
      
      
DECLARE @vm_bucket_id bigint, @ group_id bigint, @ name varchar( 50)
- Declare the cursor
DECLARE MyCursor CURSOR
- check out the results of data collection, the cursor will point to this collection
FOR ( SELECT id, group_id, name FROM dbo.vm_bucket WHERE id NOT IN(
SELECT object_id from dbo.resource_group_map where object= 29)) ORDER BY id
- Open the cursor
OPEN MyCursor
--从游标中取出内容放到声明好的变量中
FETCH NEXT FROM MyCursor INTO @vm_bucket_id, @ group_id, @ name
--对取出的数据进行判断和处理
WHILE @@FETCH_STATUS = 0
BEGIN
--插入数据
INSERT INTO dbo.resource_group
( name, group_id, user_id, created_date)
VALUES (@ name, @ group_id, 0, getutcdate())
--把刚刚插入数据的id作为结果插入到另一张表
INSERT INTO dbo.resource_group_map
(resource_group_id, object, object_id)
VALUES (@@ identity, 29, @vm_bucket_id)
- reads the next line
FETCH NEXT FROM MyCursor INTO @vm_bucket_id, @ group_id, @ name
END
- Close the cursor
CLOSE MyCursor
- release the cursor
DEALLOCATE MyCursor



Summary: The cursor is a model for writing programs easier to understand and easy to read, but if used improperly, it is easy to stifle the performance, with caution.

Original: Large column  SQL Cursor usage Cursor


Guess you like

Origin www.cnblogs.com/petewell/p/11615048.html