简体   繁体   中英

Schedule Stored Procedure in Microsoft SQL Server 2008 R2

I have to run a stored procedure on a daily basis at a particular time. I have struggled with Windows Service and after unsuccessful attempts I started looking into schedule a SQL job or schedule an event.

In order to schedule a SQL Server job I had to create one using the SQL Server Agent. I am working on Microsoft SQL Server 2008 R2 Express (with Advanced Services) on Windows and could not locate the SQL Server Agent even though I have admin access (logged in as windows authentication).

With the given scenario, what is the best way to schedule a stored procedure and how should I go about it?

There is a one way that you can schedule procedure using another SP. Create new SP like below:

CREATE SP1
AS
WHILE (1)
BEGIN
    WAITFOR TIME '22:20';   -- Your Time
    EXECUTE 'Your SP Name'
END;
GO

You can use error handling as per your requirement.

SQL server Agent contains thre back end tables to hold the front end data when you are creating a job

sysjobs
sysjobschedules
sysjobsteps

Enter job related information in sysjobs , give scheduling information in schedules table and give your sql code in steps like exec procname. Note that it should be updated in msdb database only.

Since SQL Server Express does not include SQL Server Agent, you will not be able to schedule SQL jobs directly in SQL Server. However, that does not mean that you cannot schedule jobs to be run.

Use sqlcmd . It is a command-line tool. (Run sqlcmd /? in a command window and it will show you the exact command-line syntax.)

For example, you could use the built-in Windows Task Scheduler to schedule and run a specific command-line task using a trusted connection (the -E argument):

sqlcmd -S {Server}\{SqlExpressInstance} -E -d {Database} -Q "EXECUTE {StoredProcedure}"

..Or using specific login credentials and a password (the -U and -P arguments):

sqlcmd -U {LoginId} -P {Password} -S {Server}\{SqlExpressInstance} -d {Database} -Q "EXECUTE {StoredProcedure}"

For more information about using sqlcmd , read: Using the sqlcmd Utility (SQL Server Express)

For more information about using the Windows Task Scheduler, read: Task Scheduler

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM