Sqlserver2000 Stored Procedure

Source: Internet
Author: User

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

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.