I want to run a query in every 5 minutes. I am wondering if there is something like a timer exists in SQL Server.
It would be really helpful for me. I googled a lot but i didn't get anything helpful.
Your suggestions would be much appreciated.
Pooja
You can create a SQL Agent Job via the gui or using these stored procedures: https://technet.microsoft.com/en-us/library/ms181153(v=sql.105).aspx
Also check this example (borrowed from https://www.mssqltips.com/sqlservertip/3052/simple-way-to-create-a-sql-server-job-using-tsql/ ) :
USE msdb
go
CREATE procedure [dbo].[sp_add_job_quick]
#job nvarchar(128),
#mycommand nvarchar(max),
#servername nvarchar(28),
#startdate nvarchar(8),
#starttime nvarchar(8)
as
--Add a job
EXEC dbo.sp_add_job
#job_name = #job ;
--Add a job step named process step. This step runs the stored procedure
EXEC sp_add_jobstep
#job_name = #job,
#step_name = N'process step',
#subsystem = N'TSQL',
#command = #mycommand
--Schedule the job at a specified date and time
exec sp_add_jobschedule #job_name = #job,
#name = 'MySchedule',
#freq_type=1,
#active_start_date = #startdate,
#active_start_time = #starttime
-- Add the job to the SQL Server Server
EXEC dbo.sp_add_jobserver
#job_name = #job,
#server_name = #servername
exec dbo.sp_add_job_quick
#job = 'myjob', -- The job name
#mycommand = 'sp_who', -- The T-SQL command to run in the step
#servername = 'serverName', -- SQL Server name. If running localy, you can use #servername=##Servername
#startdate = '20130829', -- The date August 29th, 2013
#starttime = '160000' -- The time, 16:00:00
Create a batch file and use windows scheduler to trigger it every five minutes.
Or write a service in .Net
Working with SQL-Server Agent job
Maintenance plan
Windows job scheduler
Trick for run on SSMS query windows (Not recommend for production or main plan)
If you need run a simple query on SSMS you can use WAITFOR DELAY statement
for example:
Declare #a int = 0
WHILE 1=1
BEGIN
-- Example code
EXEC sp_WhoIsActive -- You can write you query or code
WAITFOR DELAY '00:05:00'
IF #a = 10
Break;
SET #a = #a + 1
END
Parameter #a is important for count of running. limit to 10 running in this query., or this query run untiled, your session is open. when you close session or stop running this query is stop to work.
This is not a best practice, and use for typical trick on work. for testing, check results... this is not idea for production long time
Related
I am working on SQL server and have a procedure that takes data from one table and put into other table. I want to execute this procedure every midnight. I have searched on this
I didn't find a proper way to achieve this.
My procedure is "archive_table_sp" I want to run this every day at 12 midnight
This sounds like setting up a SQL Server Agent Job.
You can do something like this, and it is fairly simple. As long as you have full access to the SQL Server Management Studio (SSMS), you should be able to set this up.
Below is the command (T-SQL) way of doing it. I would use GUI method as it is probably easier (please see the link down below for detail).
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
For more information, please go to the following:
https://learn.microsoft.com/en-us/sql/ssms/agent/create-a-job?view=sql-server-ver15
https://learn.microsoft.com/en-us/sql/ssms/agent/schedule-a-job?view=sql-server-ver15
I didn't know anything about Stored procedures. unfortunately I have to run a stored procedure automatically.
I have a table called pass and I want to update status as cancelled at the end of the day automatically. I'm using phpmyadmin in wampserver.
I have already tried some codes but I don't know this code is correct and how to set execution automatically.
here is my code,
CREATE PROCEDURE MyTask
AS
BEGIN
SET NOCOUNT ON;
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
-- For executing the stored procedure at 1:00 A.M
declare #delayTime nvarchar(50)
set #delayTime = '01:00'
while 1 = 1
BEGIN
waitfor time #delayTime
BEGIN
ALTER PROCEDURE [dbo].[updateDuration] AS
UPDATE pass SET status = 'Cancelled' WHERE duration_type='Daily' && duration = DATE_SUB(CURRENT_DATE(),INTERVAL 1 DAY);
--Name for the stored proceduce you want to call on regular bases
execute [gatepass].[dbo].[updateDuration];
END
END
END
It says that to put below code, but I don't know where to put these.
-- Sets stored procedure for automatic execution.
sp_procoption #ProcName = 'MyTask',
#OptionName = 'startup',
#OptionValue = 'on'
Method #1 - Batching
Create a script named runMyTask.sql or whatever you want.
That script should have your SQL to run the stored procedure:
-- Sets stored procedure for automatic execution.
CALL sp_procoption('MyTask','startup', 'on');
Then you need a batch script which you might name runMyTask.bat.
In the .bat file you add the line that runs the mysql.exe command line tool and redirects the contents of the runMyTask.sql file along the lines of something like
C:/wamp/bin/mysql/mysql..../bin/mysql -u root --password=your_password database_name < C:/path/to/runMyTask.sql
When you have tested that the batch script runs correctly from the windows cmd shell, set it up in the scheduler.
Method #2 MySQL - Event Scheduler
To use the event scheduler you'll need to first make sure you it's enabled on the server. By default it is not. From the aforementioned mysql command line, login as root.
SET GLOBAL event_scheduler = ON;
After you turn it on, run a SHOW PROCESSLIST; command and you should see a line similar to this one, showing the user event_scheduler owning a process.
| 10729276 | event_scheduler | localhost | NULL | Daemon | 4 | Waiting on empty queue | NULL | 0.000 |
At this point you can add "events". To add your stored procedure run as an event, once an hour:
USE your_db;
CREATE EVENT IF NOT EXISTS EventRunMyTask
ON SCHEDULE EVERY 1 HOUR
ENABLE
DO CALL sp_procoption('MyTask','startup', 'on');
If everything goes well you should be able to see information about the scheduled job using SHOW EVENTS;
I'm trying to modify an XML value using XML.modify in an SQL Server Agent job. I'm using SQL Server 2008. Here is my code...
DECLARE #temp XML;
DECLARE #newname VARCHAR(50);
SELECT #temp = CAST(ExtensionSettings AS XML) FROM [ReportServer].[dbo].[Subscriptions] WHERE SubscriptionID = 'a2e1dd4e-5f65-4f0e-bc5a-8e58d21d7292';
SET #newname = 'Monthly_Data_' + CONVERT(VARCHAR(7), DATEADD(day, -1, GETDATE()), 120);
SET #temp.modify('replace value of (/ParameterValues/ParameterValue/Value[../Name/text()="FILENAME"]/text())[1] with sql:variable("#newname")');
UPDATE [ReportServer].[dbo].[Subscriptions] SET ExtensionSettings = CAST(#temp AS varchar(2000)) WHERE SubscriptionID = 'a2e1dd4e-5f65-4f0e-bc5a-8e58d21d7292';
This code runs fine if I just run it in a query window, but when I run it as a step in my job, the job fails. The problem seems to be with the line...
SET #temp.modify('replace value of (/ParameterValues/ParameterValue/Value[../Name/text()="FILENAME"]/text())[1] with sql:variable("#newname")');
Because if I comment it out and run the job, it completes fine.
Can XML.modify not be used in a job? What am I missing?!
Thanks
I worked on this the better part of today, finally post my question, and promptly found the answer!
I finally discovered how to view the job run history (right click on job, View History). There it mentioned QUOTED_IDENTIFIER being set wrong. A Google search later tells me that Agent jobs by default turn QUOTED_IDENTIFIER OFF (https://dba.stackexchange.com/questions/52802/sql-server-agent-quoted-identifier).
I added the line...
SET QUOTED_IDENTIFIER ON
to my job's step and it started working!
I've got a large T-SQL script that opens and closes a few transactions. I have read that committing a batch with a GO statement effectively clears all variables out from it's scope.
Given the script below, will #MyImportantVariable be defined after the transaction is committed?
Is this an issue, if so, how do I overcome it?
DECLARE #MyImportantVariable INT;
SET #MyImportantVariable = 42;
DECLARE #Counter INT;
SET #Counter = 0
DECLARE UpdateGarmentCursor CURSOR FAST_FORWARD
FOR
SELECT
MyColumn
FROM
MyWonderfulTable
BEGIN TRANSACTION
WHILE ##TRAN_STATUS = 0
BEGIN
-- Do interesting work in here
SET #Counter = #Counter +1
IF(#Counter>10)
BEGIN
COMMIT TRANSACTION
-- What happens here to #MyImportantVariable?
SET #Counter = 0
BEGIN TRANSACTION
END
END
-- Close the transaction one last time
COMMIT TRANSACTION
The variable will still exist.
Your example contains no GO commands, only transactions.
GO signals the end of a batch... batches and transactions are two different things entirely.
From MSDN:
GO is not a Transact-SQL statement; it is a command recognized by the
sqlcmd and osql utilities and SQL Server Management Studio Code
editor.
SQL Server utilities interpret GO as a signal that they should send
the current batch of Transact-SQL statements to an instance of SQL
Server. The current batch of statements is composed of all statements
entered since the last GO, or since the start of the ad hoc session or
script if this is the first GO.
I've created a SQL agent job in our SQL Server 2008 that executes the following code:
BEGIN
SET NOCOUNT ON;
declare #database nchar(20);
DECLARE Database_Cursor CURSOR FOR
SELECT [name]
FROM master.dbo.sysdatabases
ORDER BY [name]
OPEN Database_Cursor;
FETCH NEXT FROM Database_Cursor INTO #database;
WHILE ##FETCH_STATUS = 0
BEGIN
EXEC [dbo].[sp_BackupDatabase]
#databaseName = #database
FETCH NEXT FROM Database_Cursor INTO #database;
END;
CLOSE Database_Cursor;
DEALLOCATE Database_Cursor;
END
GO
Basically I retrieve a list of databases and execute a backup script for each database.
This script works for most database, but some databases return an error:
Msg 911, Level 16, State 11, Line 1
Database 'appName_Configuration' does not exist. Make sure that the name is entered correctly.
This is correct, this database does not exist. We have several database named like this:
appName_Configuration1
appName_Configuration2
...
For some reason, the script doesn't pass the name including the number to the backup script. If I replace the #database variable with a static name (appName_Configuration1) it works just fine.
Also worth mentioning: there are a few other databases that have a number at the end, which work fine:
appName_Microsoft1
appName_Microsoft2
I suspect that the word "Configuration" may have something to do with it, but renaming the database is not an option for now. Can anyone help me finding a solution so that the name is passed to the stored procedure correctly ?
Kind regards,
Mathew
Increase the size of #database variable as per your database name maximum length can be...
e.g.
declare #database nchar(100);
You declared #database as nchar(20). Your names are longer. Use nvarchar(50), for example.