如何通过T-SQL在SQL Server 2008中创建预定作业?

时间:2022-03-18 14:36:09

I want to create a job which deletes records from a database after a period of time has passed. For example I have a field in news table Time Stamp and each month a SQL query runs like a scheduled job against my database and deletes news where the time stamp is two month old. Generally I want to delete news for 2 month ago and older to not let my table become a large table. How can I accomplish this?

我想创建一个在一段时间过后删除数据库记录的作业。例如,我在新闻表时间戳中有一个字段,每个月SQL查询就像我的数据库中的预定作业一样运行,并删除时间戳为两个月的新闻。一般来说,我想删除2个月前和更早的新闻,不要让我的桌子变成一张大桌子。我怎么能做到这一点?

2 个解决方案

#1


13  

you should create a job in SQL below is a sample T-SQL for create a job via SQL agent

您应该在SQL中创建一个作业,下面是一个示例T-SQL,用于通过SQL代理创建作业

USE msdb ;
GO
EXEC dbo.sp_add_job
    @job_name = N'Weekly Sales Data Backup' ;
GO
EXEC sp_add_jobstep
    @job_name = N'Weekly Sales Data Backup',
    @step_name = N'Set database to read only',
    @subsystem = N'TSQL',
    @command = N'ALTER DATABASE SALES SET READ_ONLY', 
    @retry_attempts = 5,
    @retry_interval = 5 ;
GO
EXEC dbo.sp_add_schedule
    @schedule_name = N'RunOnce',
    @freq_type = 1,
    @active_start_time = 233000 ;
USE msdb ;
GO
EXEC sp_attach_schedule
   @job_name = N'Weekly Sales Data Backup',
   @schedule_name = N'RunOnce';
GO
EXEC dbo.sp_add_jobserver
    @job_name = N'Weekly Sales Data Backup';
GO

#2


0  

You will need to create a SQL Agent Job to schedule a job to periodically run. If you want to create the job with T-SQL, refer to How to: Create a SQL Server Agent Job (Transact-SQL).

您需要创建一个SQL代理作业来安排作业定期运行。如果要使用T-SQL创建作业,请参阅如何:创建SQL Server代理作业(Transact-SQL)。

#1


13  

you should create a job in SQL below is a sample T-SQL for create a job via SQL agent

您应该在SQL中创建一个作业,下面是一个示例T-SQL,用于通过SQL代理创建作业

USE msdb ;
GO
EXEC dbo.sp_add_job
    @job_name = N'Weekly Sales Data Backup' ;
GO
EXEC sp_add_jobstep
    @job_name = N'Weekly Sales Data Backup',
    @step_name = N'Set database to read only',
    @subsystem = N'TSQL',
    @command = N'ALTER DATABASE SALES SET READ_ONLY', 
    @retry_attempts = 5,
    @retry_interval = 5 ;
GO
EXEC dbo.sp_add_schedule
    @schedule_name = N'RunOnce',
    @freq_type = 1,
    @active_start_time = 233000 ;
USE msdb ;
GO
EXEC sp_attach_schedule
   @job_name = N'Weekly Sales Data Backup',
   @schedule_name = N'RunOnce';
GO
EXEC dbo.sp_add_jobserver
    @job_name = N'Weekly Sales Data Backup';
GO

#2


0  

You will need to create a SQL Agent Job to schedule a job to periodically run. If you want to create the job with T-SQL, refer to How to: Create a SQL Server Agent Job (Transact-SQL).

您需要创建一个SQL代理作业来安排作业定期运行。如果要使用T-SQL创建作业,请参阅如何:创建SQL Server代理作业(Transact-SQL)。