Backup and restore SQL Server Management Studio job schedule - sql

I've got a job in SQL Server Management Studio and I want to back up the schedule that it runs on so that the schedule can be applied to other jobs that I add. I know that I can get what I assume is the data I need to copy from using the following:
-- lists all aspects of the information for the job NightlyBackups.
USE msdb ;
GO
EXEC dbo.sp_help_job
#job_name = N'NightlyBackups',
#job_aspect = N'SCHEDULES' ;
GO
I'm just wondering how I can store the results of this stored procedure in a way that will allow me to add it to other jobs on the system. Preferably in T-SQL .

The GUI method:
Right-click the job in SSMS and script it as CREATE; alter parameters to suit.
The T-SQL method:
I don't have that on-hand, but try opening Profiler, look for SQL:Completed and RPC:Completed, and then do the GUI method - you should capture the T-SQL that SSMS is executing! Alter to suit.

Related

Can I write a SQL script to dynamically create all stored procedures and views from one database to another?

Can I write a SQL script to dynamically create all stored procedures and views from one database to another?:
I have 2 instances of MyDatabase
1 MyDatabase instance on ServerX
1 MyDatabase instance on ServerY
I'd like to write a SQL script which does the following:
Drop all stored procedures and views on ServerY
Generate CREATE statements for all stored procedures and views on ServerX
Execute those CREATE statements on ServerY, so all stored procedures and views on ServerY match those on ServerX
I'm sure this can be done but can anyone here describe a way to go about doing this?
There is an easier way to do this - SQL Server can script the creation of the objects for you into a single *.sql file. You then just run that script on the other server. You can even have it include the data from the existing database. For a detailed walk through, see: https://dzone.com/articles/generate-database-scripts-with-data-in-sql-server
Why? SQL Server has all this built in for you
Once all your SP and views are on Server.. Right click on your database and click Tasks > Generate scripts. SQL Server Management Studio is able to generate the CREATE scripts for you, which can be done on SP, views and more.
Then you simple copy this script and execute it on ServerX server/database.
BUT if you need it to be automated you should use powershell to simulate this task. Doing this in a SQL script isn't the best solution.
Create a link from the server X to the server Y and select, assume server x for the primary.

Create SQL Server Agent job for stored procedure with input parameter

Could you suggest please how to create SQL Server Agent job for a stored procedure that have 1 input parameter?
The procedure is correctly created and i executed it using this code :
EXECUTE dbo.MYProcedure N'2016-02-25';
Is there a way to create a SQL Server Agent job for this procedure that have parameter ?
So i'm trying the basic way that is add this ligne in EXECUTE dbo.MYProcedure N'2016-02-25'; to the window of step in job
But the paraméter can change
here are the steps
in SQL management studio, right click on "SQL Server Agent" under the SQL server which you are connected to.
Select New Job.
Enter the job name and then click on steps
Click on "New" which should be right at the bottom of the screen.
Enter step name.
Type: keep it selected as Transact SQL
Enter : EXECUTE dbo.MYProcedure N'2016-02-25';
Now save it and it should be ready for running manually.
If you do want to automate it then open the job by going into the job monitor under SQL Server Agent in SQL management studio and then click on schedule and provide when and how often you would like your job to run.
If you automating the date parameter then add this as your Transact SQL statement:
DECLARE #DATE DATETIME
--Trim out the time so the date is set to 2016/02/25
--and time changes to 00:00 get date will get todays
--date or the run date
SET #DATE = DATEADD(DD,0,DATEDIFF(DD,0,GETDATE()))
EXECUTE dbo.MYProcedure #DATE
Happy coding!!!

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.

How to run a stored procedure automatically every day

How do I set up to run a stored procedure automatically every day in SQL Server 2008 R2?
Set up a SQL job http://msdn.microsoft.com/en-us/library/ms135739.aspx
You need to use the Job scheduler in the sql agent. Sql express doesn't include it so I just have a batch file run as a scheduled task to run it.
-James
Was discussed here:
Scheduled run of stored procedure on SQL server
Under SQL agent you need to go to the job scheduler and create a job that runs the stored proc. Once you have created the job you can create one or more schedules for the job. http://msdn.microsoft.com/en-us/library/ms135739.aspx

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

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.