MS SQL Development
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
User Name:
Password:
Remember me
Go Back   Dev Shed ForumsDatabasesMS SQL Development

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Rate Thread Display Modes
  #1  
Old November 27th, 2003, 11:19 PM
lblock0110 lblock0110 is offline
Junior Member
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Nov 2003
Posts: 3 lblock0110 User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 0
Exclamation Stored Procedure - Daily Autodelete

I new in the world of Stored Procedures so there it goes:

I need an Stored Procedure that will automatically delete records that are more than one week old from the db, my date field is called 'ammend'. Eventhough I kind of know how to do the actual procedure, I just want to make sure, or I will erase necessary data accidentaly .

Also, how do I make it run daily from SQL? .

Thanks in advance,

lblock0110

Reply With Quote
  #2  
Old November 30th, 2003, 10:55 PM
messorian messorian is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Jul 2003
Location: NY
Posts: 18 messorian User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 2 h 34 m 18 sec
Reputation Power: 0
Alright, below is a sample of how you can write the procedure (use the delete statement from the code). I have wrapped everything up in a larger script to show the usage of the DateAdd() function which you will want to use to select the desired records. The script consists of three parts. The first, creates a test table to delete from records with and adds a months worth of records. The second creates the stored procedure used to delete all records over one week old. The final selects the data from the table, calls the delete proc and then selects the data from table again to show the record differences.
As far as scheduling, just use Sql Agent and set it as a daily job to be executed.

-- Messorian


Code:
-- Create  a test table in tempdb

USE tempdb -- scratchpad :-)
SET NOCOUNT ON -- disable record counts from being returned (improves performance)

DECLARE @date smalldatetime

-- drop the table if it exists
IF EXISTS(SELECT * FROM sysObjects WHERE name = 'TestData' AND xtype='U')
	DROP TABLE TestData


-- create a table to test with
CREATE TABLE TestData(
	pk int NOT NULL PRIMARY KEY CLUSTERED IDENTITY(1,1),
	myData varchar(128) NULL,
	ammend smalldatetime
)
CREATE NONCLUSTERED INDEX IDX_TESTDATA_ENTDATE
	ON TestData(ammend) -- helps the performance of the delete statement

	
	-- today's Date
	SET @date = getdate() 

	-- loop until the table has been populated with the dates of the last four weeks
	-- newid() is used just to put in some arbitary data
	WHILE @date > DateAdd(wk, -4, GetDate()) BEGIN
		INSERT INTO TestData(myData, ammend)
			VALUES(newID(), @date)

		-- set @date back one day
		SET @date = DateAdd(d, -1, @date)
	END
GO





---------------------------------------
---------------------------------------
-------- RUN THIS PART SECOND ---------
---------------------------------------
---------------------------------------

-- STORED PROC CREATION
IF EXISTS(SELECT * FROM sysobjects WHERE name='usp_DeleteOldEntries' AND xtype='P')
	DROP PROCEDURE usp_DeleteOldEntries
GO
CREATE PROCEDURE usp_DeleteOldEntries
AS
	SET NOCOUNT ON

	-- start a transaction to ensure that if something goes wrong, you can revert to the original
	-- data
	BEGIN TRANSACTION
		DELETE FROM TestData 
			WHERE ammend < DateAdd(wk, -1, GetDate())

	-- if an error occurred roll the tran back (yes, this is not a perfect example of 
	-- handling errors, but the question wasnt about transaction management ;-)		 )
	IF @@ERROR != 0 BEGIN
		ROLLBACK TRANSACTION
		PRINT 'Mayday!! Mayday!!'
		RETURN
	END	ELSE	
		COMMIT TRANSACTION
GO




---------------------------------------
---------------------------------------
-------- RUN THIS PART THIRD  ---------
---------------------------------------
---------------------------------------
-- Execute the query and review the results on the table --
	SELECT * FROM TestData

	exec usp_DeleteOldEntries

	SELECT * FROM TestData

Reply With Quote
Reply

Viewing: Dev Shed ForumsDatabasesMS SQL Development > Stored Procedure - Daily Autodelete


Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump

 Free IT White Papers!
 
Accelerating Trading Partner Performance
One in five. That's how many partner transactions have at least one error. That is an amazing statistic, particularly given the extraordinary leaps in innovation across the global supply chain during the past two decades. Download this white paper to learn more.

 
Competing on Analytics
This Tech Analysis is designed to help identify characteristics shared by analytics competitors, and includes information about 32 organizations that have made a commitment to quantitative, fact-based analysis.

 
Cost Effective Scaling with Virtualization and Coyote Point Systems
An overview of the industry trend toward virtualization, how server consolidation has increased the importance of application uptime and the steps being taken to integrate load balancing technology with virtualized servers.

 
Five Checkpoints to Implementing IP Telephony
Implementation planning for IP PBX software and IP telephony has become vital as businesses replace discontinued legacy PBX phone systems. This informative whitepaper outlines five "checkpoints" for any implementation plan that will help make IP communications a successful proposition.

 
Hosted Email Security: Staying Ahead of New Threats
In the last two years, email has become a fierce battleground between the nefarious forces of spam and malware, and the heroes of messaging protection. The spam volumes increased alarmingly every month, bringing clever new forms of phishing and virus propagation attacks.

 

Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
  
 





© 2003-2008 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway