Quick Search for:  in language:    
SQL,find,stuff,Select,Insert,There,DELETE,ide
   Code/Articles » |  Newest/Best » |  Community » |  Jobs » |  Other » |  Goto » | 
CategoriesSearch Newest CodeCoding ContestCode of the DayAsk A ProJobsUpload
SQL Stats

 Code: 44,501. lines
 Jobs: 125. postings

 How to support the site

 
Sponsored by:

 
You are in:
 
Login





Latest Code Ticker for SQL.
Beginners pack
By hardik shah on 1/11


Inline Views
By Thivya Prabakaran on 1/6


Create thousand Data Base users quickly
By N.D.I.Samantha on 1/1


Numbers from String
By Jeff Michelson on 12/30


Click here to put this ticker on your site!


Add this ticker to your desktop!


Daily Code Email
To join the 'Code of the Day' Mailing List click here!

Affiliate Sites



 
 
   

Recycle feature in MS SQL Server 2000

Print
Email
 

Submitted on: 6/12/2003 6:07:24 AM
By: Raghavendra Narayana 
Level: Advanced
User Rating: By 2 Users
Compatibility:SQL Server 2000

Users have accessed this article 3206 times.
 

(About the author)
 
     We can find a lot of stuff on SQL Select, Insert and etc. There are few articles/discussions on SQL ‘DELETE’. Here is an idea about SQL ‘DELETE’ statement. If the data is deleted from the tables without using Transactions, there is no way for Developers to retrieve it back, probably DBAs or certain tools may retrieve it back for you. Here is an effort to give a little leverage to Developers in dealing with record deletion. This Stored Procedure accepts DELETE SQL statement and comment for deletion as parameters. Copies the deleting records to another table with the same name but prefixed by “Recycle_”. Along with copying the deleting records, it stores two more information for back reference i.e. comment for deleting the record, incremental number that uniquely identifies a record or set of records that got deleted in each DELETE SQLs.

This article has accompanying files

 
 
Terms of Agreement:   
By using this article, you agree to the following terms...   
1) You may use this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.   
2) You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
3) You may link to this article from another website, but ONLY if it is not wrapped in a frame. 
4) You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.
Recycle feature in MS SQL Server 2000

Recycle feature in MS SQL Server 2000

 We can find a lot of stuff on SQL Select, Insert and etc.  There are few articles/discussions on SQL ‘DELETE’.  Here is an idea about SQL ‘DELETE’ statement.

 If the data is deleted from the tables without using Transactions, there is no way for Developers to retrieve it back, probably DBAs or certain tools may retrieve it back for you.  Here is an effort to give a little leverage to Developers in dealing with record deletion.

 This Stored Procedure accepts DELETE SQL statement and comment for deletion as parameters.  Copies the deleting records to another table with the same name but prefixed by “Recycle_”.  Along with copying the deleting records, it stores two more information for back reference i.e. comment for deleting the record, incremental number that uniquely identifies a record or set of records that got deleted in each DELETE SQLs.

 Algorithm:

·         Accept DELETE SQL Statement, Comment to be put to all the deleting records.

·         Check for the ‘DELETE ‘ key word in DELETE Sql parameter

·         Construct the Select/Insert SQL statement in order to insert the deleting rows using ‘SELECT INTO’ or ‘INSERT..SELECT’ SQLs. 

·         Execute the constructed “Insert/Select” SQL.

o        If the Recycle copy of the deleting records table does not exist then create one.

o        Insert all the deleting records to recycle copy, with Transaction Number and Comment i.e. supplied by the Developer.

·         Finally execute the actual SQL DELETE.

 

Expansion:

You can store more information about the deleting rows by adding more columns in Recycle table like Database Login ID, Deleted Date and Time, DELETE SQL Statement and etc. depending on the requirement.

 

SP Script:

CREATE PROCEDURE SP_RDELETE

(@SDELETE AS VARCHAR(2000),   --DELETE SQL STATEMENT AS PARAMETER

@SCOMMENT AS VARCHAR(1000),   --COMMENT/TITLE FOR THE DELETING RECORD(S)

@ERRORMESSAGE AS VARCHAR(2000) --ERROR MESSAGE IF ANY DURING THE SP EXECUTION

)

AS

 

--VARIABLE DECLARATION

DECLARE @SSTR AS VARCHAR(2000),     --VARIABLE TO CONSTRUCT SQL STATEMENTS

@SSELECT AS VARCHAR(2000),    --VARIABLE TO CONSTRUCT 'SELECT' SQL

@STABLE AS VARCHAR(2000),     --VARIABLE TO STORE TABLE NAME

@SPOS AS INT                  --VARIABLE TO STORE CHARACTER POSITIONS

 

--TRIMMING OF DATA

SET @SDELETE = ' '+ LTRIM(RTRIM(@SDELETE)) + ' '

 

--COPY OF @SDELETE PARAMETER TO EXECUTE 'SELECT' SQL STATEMENT

SET @SSELECT = @SDELETE

 

--CONSTRUCT 'SELECT' SQL FROM @SDELETE PARAMETER

--USING 'SELECT' SQL COPY THE DELETING RECORDS TO RECYCLE TABLE COPY

SET @SPOS = CHARINDEX(' DELETE ', @SSELECT)

 

IF @SPOS > 0

BEGIN

      IF CHARINDEX(' FROM ', @SSELECT, @SPOS) = 0

      BEGIN

            SET @STABLE = LTRIM(RTRIM(SUBSTRING(@SSELECT, @SPOS + 7, 2000)))

            SET @SSELECT = ' SELECT * FROM ' + @STABLE

      END

      ELSE

      BEGIN

            SET @SSTR = RTRIM(LTRIM(SUBSTRING(@SSELECT, CHARINDEX(' FROM ', @SSELECT) + 6, 2000)))

            IF CHARINDEX(' ', @SSTR) = 0

            BEGIN

                  SET @SSELECT = ' SELECT * FROM ' + @SSTR

                  SET @STABLE = @SSTR

            END

            ELSE

            BEGIN

                  SET @STABLE = SUBSTRING(@SSTR, 1, CHARINDEX(' ', @SSTR))

                  SET @SSELECT = REPLACE(@SSELECT, ' DELETE ', ' SELECT * ')

            END

      END

END

ELSE

BEGIN

      SET @ERRORMESSAGE = 'NO DELETE KEYWORD IN THE SDELETE PARAMETER'

      RETURN -1

END

 

--USING 'SELECT' SQL COPY THE DELETING RECORDS TO RECYCLE TABLE COPY

SET @STABLE = 'RECYCLE_' + @STABLE

--CHECK WHETHER RECYCLE TABLE FOR DELETING RECORDS TABLE ALREADY EXIST

--IF DOES NOT EXIST CREATE ONE

IF (SELECT 1 FROM INFORMATION_SCHEMA.TABLES

WHERE TABLE_NAME = @STABLE ) > 0

BEGIN      

      --TABLE ALREADY EXIST

      --BUILDING THE SQL: INSERT INTO EXISTING RECYLE TABLE

--USING 'INSERT..SELECT' SQL

      SET @SSELECT = REPLACE (@SSELECT, ' SELECT * ', ' INSERT INTO ' + @STABLE + ' SELECT *, (SELECT MAX(TRANSNO)+1 FROM ' + @STABLE + '), ''' +  @SCOMMENT + ''' ')

END

ELSE  --TABLE DOES NOT EXIST

BEGIN

      --BUILDING THE SQL: CREATE TABLE USING 'SELECT INTO' SQL

      SET @SSELECT = REPLACE (@SSELECT, ' SELECT * ', ' SELECT *, 1 TRANSNO, ''' + @SCOMMENT + ''' COMMENT INTO ' + @STABLE + ' ' )

END

 

BEGIN TRANSACTION TRANS_SP_DELETE

 

--EXECUTE THE CONSTRUCTED SELECT SQL THAT CREATES/INSERTS RECYCLE TABLE

EXEC(@SSELECT)

--CHECK FOR ERRORS

IF @@ERROR > 0

BEGIN

      SET @ERRORMESSAGE = 'ERROR WHILE CREATING/UPDATING RECYCLE TABLE'

      ROLLBACK TRANSACTION TRANS_SP_DELETE

      RETURN -1

END

 

--EXECUTE THE ACTUAL DELETE STATEMENT NOW

EXEC (@SDELETE)

--CHECK FOR ERRORS

IF @@ERROR > 0

BEGIN

      SET @ERRORMESSAGE = 'ERROR WHILE EXECUTING PASSED DELETE SQL STATEMENT'

      ROLLBACK TRANSACTION TRANS_SP_DELETE

      RETURN -1

END

ELSE

BEGIN

      --COMPLETED SUCCESSFULLY

      COMMIT TRANSACTION TRANS_SP_DELETE

      RETURN 0

END

 

Parameters:

Parameter Name

Description

@SDELETE

Actual DELETE SQL statement

@SCOMMENT

Comment/Title for the deleting records.  This will be stored in “Comment” column of Recycle copy of the table.

@ErrorMessage  [INPUT/OUTPUT Parameter]

Any error during the SP execution.

 

Returns

Returns 0 on successful execution.

Returns 1 on unsuccessful execution with error message in @ErrorMessage input/output parameter

 

Limitation of SP

Currently the SP is designed to handle only certain kind of SQL ‘DELETE’ statements.

The supported SQL ‘DELETE’ types are below.

A.     Use DELETE with no parameters E.g. DELETE authors OR DELETE from authors
B.     Use DELETE on a set of rows E.g. DELETE FROM authors WHERE au_lname = 'McBadden'
Effort is on to include all type of ‘DELETE’ statements, some of the other types of DELETE statements are a) Use DELETE on the current row of a cursor  b)Use DELETE based on a subquery or use the Transact-SQL extension  c)Use DELETE and a SELECT with the TOP Clause

  

Usage

Ø       While fixing the Production related issues, use this SP instead of DELETE SQL to keep the history of existing/bad records.

Ø       To recycle the deleted records in future.

Ø       To Archive the old OR very rarely used records, thereby increasing the performance of the table transactions.

 

 Example

Check the Screen shot for example.

winzip iconDownload article

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. Afterdownloading it, you will need a program like Winzip to decompress it.

Virus note:All files are scanned once-a-day by Planet Source Code for viruses,but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:
1)Re-scan downloaded files using your personal virus checker before using it.
2)NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

If you don't have a virus scanner, you can get one at many places on the net including:McAfee.com

 
Terms of Agreement:   
By using this article, you agree to the following terms...   
1) You may use this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.   
2) You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
3) You may link to this article from another website, but ONLY if it is not wrapped in a frame. 
4) You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.


Other 9 submission(s) by this author

 

 
Report Bad Submission
Use this form to notify us if this entry should be deleted (i.e contains no code, is a virus, etc.).
Reason:
 
Your Vote!

What do you think of this article(in the Advanced category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor See Voting Log
 
Other User Comments
6/14/2003 11:26:36 AM:Zzzbla
How about adding a [Cancel] field to important tables, then using a trigger on the table to 'update cancel=1' on Delete, and do select on a view that filters the
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
6/14/2003 11:28:02 AM:Zzzbla
cancelled rows. Wouldn't it be faster? Not to mention if you just update instead of delete and don't use the trigger.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
Add Your Feedback!
Note:Not only will your feedback be posted, but an email will be sent to the code's author in your name.

NOTICE: The author of this article has been kind enough to share it with you.  If you have a criticism, please state it politely or it will be deleted.

For feedback not related to this particular article, please click here.
 
Name:
Comment:

 

Categories | Articles and Tutorials | Advanced Search | Recommended Reading | Upload | Newest Code | Code of the Month | Code of the Day | All Time Hall of Fame | Coding Contest | Search for a job | Post a Job | Ask a Pro Discussion Forum | Live Chat | Feedback | Customize | SQL Home | Site Home | Other Sites | About the Site | Feedback | Link to the Site | Awards | Advertising | Privacy

Copyright© 1997 by Exhedra Solutions, Inc. All Rights Reserved.  By using this site you agree to its Terms and Conditions.  Planet Source Code (tm) and the phrase "Dream It. Code It" (tm) are trademarks of Exhedra Solutions, Inc.