SQL statement for batch data deletion during the Stored Procedure

Source: Internet
Author: User
The SQL stored procedure deletes data in batches. For more information, see

The SQL stored procedure deletes data in batches. For more information, see

The Code is as follows:
Create PROCEDURE Batch_Delete
@ TableName nvarchar (100), -- table name
@ FieldName nvarchar (100), -- delete the field name
@ DelCharIndexID nvarchar (1000)
As
DECLARE @ PointerPrev int
DECLARE @ PointerCurr int
DECLARE @ TId NVARCHAR (50), @ SQL NVARCHAR (1000)

Set @ PointerPrev = 1
While (@ PointerPrev <LEN (@ DelCharIndexID ))
Begin
Set @ PointerCurr = CharIndex (',', @ DelCharIndexID, @ PointerPrev)
If (@ PointerCurr> 0)
Begin
SET @ TId = cast (SUBSTRING (@ DelCharIndexID, @ PointerPrev, @ PointerCurr-@ PointerPrev) As NVARCHAR (50 ))
SET @ SQL = 'delete from' + @ TableName + 'where' + @ FieldName + '= ''' + @ TID + ''''
Exec (@ SQL)
Print ('========' + @ TId +' ====== SQL '+ @ SQL)
SET @ PointerPrev = @ PointerCurr + 1
Print (@ PointerPrev)
End
Else
Begin
Print ('Break ')
Break
End
End
-- Delete the last one. Because there is no comma after the last one, it jumps out of the loop and needs to be deleted again.
SET @ TId = cast (SUBSTRING (@ DelCharIndexID, @ PointerPrev, LEN (@ DelCharIndexID)-@ PointerPrev + 1) As NVARCHAR (50 ))
SET @ SQL = 'delete from' + @ TableName + 'where' + @ FieldName + '= ''' + @ TID + ''''
Exec (@ SQL)
Print ('========' + @ TId +' ====== SQL '+ @ SQL)
GO

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.