Function: insert all qualified data in Table A into Table B, and a field in Table B increments according to a certain rule.
Example: Table t_org_org (ID, upid, downid );
Table temp (ID, upid, downid );
Result: The upid = 1 data in the t_org_org table is inserted into the temp table, and the IDs of the temp table increase progressively according to the rules (x1001, x1002. .., x9999.
Principle: insert the Qualified Data in the t_org_org table into the temp table, and then update the IDs in the temp table according to the rule.
Code :
-- Step 1: insert data
Insert IntoTemp (ID, upid, downid)SelectID, upid, downidFromT_org_orgWhereUpid = 1
-- Step 2: update data
/**
* ID: auto-Increment Variable (INT)
* Currentid: The current cursor value (varchar (100) corresponds to the ID field of the t_org_org table)
*/
Declare@ IDInt, @ CurrentidVarchar(100)
Set@ ID = 1001 -- Id increases progressively from 1001
/**
* Declare the cursor variable: mycursor
*/
DeclareMycursorCursor
SelectIDFromTempOrderDownid
OpenMycursor
/**
* Move the cursor down a row and place the returned value into the variable currentid.
*/
Fetch next fromMycursor
Into@ Currentid
/**
* While loop: the condition is that the cursor moves down normally
*/
While @ Fetch_status= 0
Begin
/**
* Update the records currently referred to by the cursor
*/
UpdateTempSetId ='X'+Cast(@ IDAs varchar)Where Id = @ currentid
/**
* The cursor moves down a row and places the returned value into the variable currentid.
*/
Fetch next fromMycursor
Into@ Currentid
/**
* Auto Increment
*/
Set@ ID = @ ID + 1
End -- While loop ends
/**
* Close the cursor and release the resource.
*/
CloseMycursor
DeallocateMycursor