How to run a stored procedure every day in SQL Server Express Edition? - sql

How is it possible to run a stored procedure at a particular time every day in SQL Server Express Edition?
Notes:
This is needed to truncate an audit table
An alternative would be to modify the insert query but this is probably less efficient
SQL Server Express Edition does not have the SQL Server Agent
Related Questions:
How can I schedule a daily backup with SQl Server Express?
Scheduled run of stored procedure on SQL Server

Since SQL Server express does not come with SQL Agent, you can use the Windows scheduler to run a SQLCMD with a stored proc or a SQL script.
http://msdn.microsoft.com/en-us/library/ms162773.aspx

I found the following mechanism worked for me.
USE Master
GO
IF EXISTS( SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[MyBackgroundTask]')
AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[MyBackgroundTask]
GO
CREATE PROCEDURE MyBackgroundTask
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- The interval between cleanup attempts
declare #timeToRun nvarchar(50)
set #timeToRun = '03:33:33'
while 1 = 1
begin
waitfor time #timeToRun
begin
execute [MyDatabaseName].[dbo].[MyDatabaseStoredProcedure];
end
end
END
GO
-- Run the procedure when the master database starts.
sp_procoption #ProcName = 'MyBackgroundTask',
#OptionName = 'startup',
#OptionValue = 'on'
GO
Some notes:
It is worth writing an audit entry somewhere so that you can see that the query actually ran.
The server needs rebooting once to ensure that the script runs the first time.

Create a scheduled task that calls "C:\YourDirNameHere\TaskScript.vbs" on startup. VBScript should perform repeated task execution (in this example, it's a 15 minute loop)
Via command line (must run cmd.exe as administrator):
schtasks.exe /create /tn "TaskNameHere" /tr "\"C:\YourDirNameHere\TaskScript.vbs\" " /sc ONSTARTUP
Example TaskScript.vbs: This executes your custom SQL script silently using RunSQLScript.bat
Do While 1
WScript.Sleep(60000*15)
Set WshShell = CreateObject("WScript.Shell")
WshShell.RUN "cmd /c C:\YourDirNameHere\RunSQLScript.bat C:\YourDirNameHere\Some_TSQL_Script.sql", 0
Loop
RunSQLScript.bat: This uses sqlcmd to call the database instance and execute the SQL script
#echo off
sqlcmd -S .\SQLEXPRESS -i %1

If you are using Express Edition, you will need to use the Windows Scheduler or the application connecting to the server in some way.
You would use the scheduler to run sqlcmd. Here are some instructions for getting the sqlcmd working with express edition.

SQL Scheduler from http://www.lazycoding.com/products.aspx
Free and simple
Supports all versions of SQL Server 2000, 2005, and 2008
Supports unlimited SQL Server instances with an unlimited number of jobs.
Allows to easily schedule SQL Server maintenance tasks: backups, index rebuilds, integrity checks, etc.
Runs as Windows Service
Email notifications on job success and failure

Since another similar question was asked, and will likely be closed as a duplicate of this one, and there are many options not mentioned in the answers already present here...
Since you are using SQL Express you can't use SQL Server Agent. However there are many alternatives, all of which you can schedule using AT or Windows Task Scheduler depending on your operating system:
VBScript
C# command line app
batch file with SQLCMD
PowerShell
All of these languages/tools (and many others) have the capacity to connect to SQL Server and execute a stored procedure. You can also try these Agent replacements:
SQLScheduler
Express Agent
Standalone SQL Agent (beta)

The easiest way I have found to tackle this issue is to create a query that executes the stored procedure then save it. The query should look similar to this one below.
use [database name]
exec storedproc.sql
Then create a batch file with something similar to the code below in it.
sqlcmd -S servername\SQLExpress -i c:\expressmaint.sql
Then have the task scheduler execute the batch as often as you like

Another approach to scheduling in SQL Express is to use Service Broker Conversation Timers. To run a stored procedure periodically, which you can use to bootstrap a custom scheduler.
See eg Scheduling Jobs in SQL Server Express

You could use Task Scheduler to fire a simple console app that would execute the Sql statement.

As you have correctly noted, without the agent process, you will need something else external to the server, perhaps a service you write and install or Windows scheduler.
Note that with an Express installation for a local application, it is possible that the machine may not be on at the time you want to truncate the table (say you set it to truncate every night at midnight, but the user never has his machine on).
So your scheduled task is never run and your audit log gets out of control (this is a problem with SQL Server Agent as well, but one would assume that a real server would be running non-stop). A better strategy if this situation fits yours might be to have the application do it on demand when it detects that it has been more than X days since truncation or whatever your operation is.
Another thing to look at is if you are talking about a Web Application, there might be time when the application is loaded, and the operation could be done when that event fires.
As mentioned in the comment, there is sp_procoption - this could allow your SP to run each time the engine is started - the drawbacks with this method are that for long-running instances, there might be a long time between calls, and it still has issues if the engine is not running at the times you need the operation to be done.

Our company also use SQLEXPRESS and there is no SQL Agent.
Since there is no marked answer as "right" and all the solutions are quite complex I'll share what I did there. May be its really bad, but it worked great to me.
I've chosen operations of Insertion (people do) to a table that got closely the same time range i needed and made a trigger "ON INSERT" that applies needed function.

Related

Using powershell - how to prevent SQL from access the same record

I want to run multiple instances of powershell to collect data from Exchange. In powershell, I use invoke-sqlcmd to run various SQL commands from powershell.
SELECT TOP 1 SmtpAddress FROM [MMC].[dbo].[EnabledAccounts]
where [location] = '$Location' and Script1 = 'Done' and (Script2 = '' or
Script2 is null)
When running more than one script, I see both scripts accessing the same record. I know there's a way to update the record, to lock it, but not sure how to write it out. TIA:-)
The database management system (I'll assume SQL Server) will handle contention for you. Meaning, if you have two sessions trying to update the same set of records, SQL Server will block one session while the other completes. You don't need to do anything to explicitly make that happen. That said, it's a good idea to run your update in a transaction if you are applying multiple updates as a single unit; a single change occurs in an implicit transaction. The following thread talks more about transactions using Invoke-SqlCmd.
Multiple Invoke-SqlCmd and Sql Server transaction

How call Procedure in Mssql on Specific Time

I am Using SQL server 2014 and i want to run a procedure automatically as per scheduled time..
I want to Sync Data from One Database to Another Database...
It is any Option in Express to Scheduled to call a specific procedure....
in SQL Server Express edition, there isn't a SQL Agent for scheduling. You can use Windows Task Scheduler and use sqlcmd to execute your stored procedure
Provided you don't have complex scheduling needs but only need something to run, say, once a day at a fixed time, you can combine a few features.
You can create a stored procedure that never ends, with a body something like:
WHILE 1=1
BEGIN
WAITFOR TIME '22:00'
EXEC SomeOtherTask /* parameters, etc */
END
You put this procedure in master, and then call sp_proc_option on it to mark it as a startup procedure.
Then restart your SQL Server instance and, at the appointed time, SomeOtherTask should be executed.
Note that you wouldn't want to over-use this technique - it keeps a connection permanently tied up just waiting for time to pass. Much easier (but of course with a cost) is to move up to a more fully-featured edition. You're starting to do things that are causing you pain - such as job scheduling and what appears to be some form of replication which are built into higher level editions. You may have outgrown Express edition.

Can I close SSMS but leave a stored procedure running?

Is it possible to shut down ms sql server management studio while a stored procedure is running, without stopping the stored procedure?
If you mean an SP you are running within SSMS then no. Obviously closing your own SSMS won't affect SP's that are running from other users on the server.
You really can't, however you can create a SQL Agent job which will execute the stored proc do you need a result set returned to you or are you updating data?
If its an update I think you're fine just running it from the agent, if not, your next simplest way to return a long running stored proc's result set would to be create an SSIS package which outputs that result set to a csv, excel doc what ever is appropriate. This package can then also be executed by the SQL Agent.
Yes you can, but you will not be able to see the result of the SP if something is returned. Once the execution is given to server the server will execute the SP not the SSMS.

Is it possiple to run a stored procedure automatically without sql sever Agent?

Hello I am using MS SQL Management Studio express 2005 and I need to have a stored procedure to activate daily.
However I do not have SQL agent.
The Managemnet studio will not be opened daily so I can't use a startup script.
Anyone know how to do this without the Agent?
Thanks in advance.
you can use sqlcmd
http://msdn.microsoft.com/en-us/library/ms162773.aspx
then have that in a batch file and scheduled via windows scheduler
example below
sqlcmd -E -S localhost -q "select count(1) from databasename.dbo.tablename"
this will connect to sql on the local machine and perform a rowcount on the table in the database
Create a script that does the database call and use Scheduled Tasks to execute the script.
You can create a windows scheduled task to run the command line client osql.
It's not pretty, but you can create a stored procedure in master:
use master
go
CREATE PROCEDURE DoStuffDaily
AS
WHILE 1=1
BEGIN
WAITFOR TIME '00:05' --5 past midnight?
EXEC <yourdb>.<schema>.<proc>
END
go
Then just mark this stored proc as a startup procedure using sp_procoption, and restart SQL Server.

Any solutions to test SQL Agent Job immediately to ignore schedule

I am using SQL Server 2008 and I want to test the execution correctness of my SQL Server Agent job immediately to ignore the schedule. Any ideas?
thanks in advance,
George
In SSMS, under the "SQL Server Agent" node, open the "Jobs" subnode and find your job, right click on it and select "Start Job" - that'll start and run the job right away.
Marc
Create a stored procedure that encapsulates all the aspects of your job and then use that in SQL Agent. You can then just call the procedure from the command line to test it eg. exec dbo.MyProcedure #param1 = 'foo'
Change the schedule to have it run five minutes in the future.
Then get off the server so it runs in exactly the environment you want to test.