SQL Agent job - no results, yet stored proc works - sql-server

I have a SQL Agent Job which claims to succeed, however doesn't ACTUALLY do what it is supposed to do. If I run the script inside on its own it does generate results.
I am using SQL 2014. The scrip used/inside the agent job is:
IF OBJECT_ID('TEMPDB..##RCCON','U') IS NOT NULL DROP TABLE ##RCCON
SELECT top 10 R.RC_C__ID as ConsentId
,dbo.clr_RC_CON(R.RC_CON__ID,'','') AS RC_CON
INTO ##RCCON FROM RC_CON R
The script works independently, but as a JOB yields no results.
Any suggestions please? Cheers

The ##RCCON evaporates when the SQL Agent Job is done. They only exist for the duration of the session.
Perhaps use [dbo].[RCCON] instead

Related

MSSQL Secondary server's SQL agent job in AG Group still able to run cause script run twice

We have a AG Group setup for 2 server A (Primary) ,B (Secondary)
A,B have identical setup for sql agent job
A job run successful and
B job's failed in initial step when trying to access the db (Due to The target database , is participating in an availability group and is currently not accessible for queries.)
Once A failover and B become Primary. We notice a behaviour that A & B sql agent Job also running successfully, so the job run twice.
We tried to modify script in sql agent Job, by adding printing ##servername variable, we found that A & B sql agent job are also printing B(now is primary) servername. Likely 2 job are also running in B(primary) server.
The only way to resolve is currently just to restart the sql agent service. Would like to know if any other solution?
SQL server version is 13.0.5888.11
Below Issue is similar to mine, but no solution yet
[https://stackoverflow.com/questions/47433964/sql-server-ag-agent-jobs-running-successfully-on-secondary-replica][1]

Query taking more time on local SSMS than remote

When I am executing a select statement with 4 'inner' joins and two 'WHERE' conditions it took 13-15 s in local SSMS (I have executed 5 times). But when I connect the same instance from another server's SSMS and execute the same query it took 5 s to execute first time and then it took 0 s! I am using the same user SA.
Is there any possible explanation for that?
Host instance is SQL 2008 and Remote instance has SQL 2008 R2.
If your query is returning data to display in your local SSMS then this data needs to be transferred from the server to your local SSMS. The time to transfer the data from the server to your local SSMS is included in the execution time. So, the execution time is a combination of executing the script and fetching the data in order to display it.
You might want to "Include Client Statistics" and then review the row "Bytes received from server" in the "Client Statistic" tab of the result window.
In order to verify my assumption you can alter your select only to execute without fetching the data.

Job run in sql sever agent insert all null data.

I have a store procedure which insert data into a table in sql. It work find in SQL however when i create a job in sql server management studio to execute this store procedure by
exec store procedure name
the job does run successfully but all the data insert into the table is null.
i have no idea how this happen, please help. Thanks
Part 1:
We need to know more information than what you are supplying.
Here is a list of things to start.
1 - Generate TSQL for the table.
2 - Send us a couple of records to insert.
3 - Sample TSQL code inside the job step.
4 - What account is SQL Agent running under?
5 - Is the job running in the correct database when executing the TSQL statement?
6 - Are there any errors in the job history.
In short, this task can be easily done.
A screen shot or two would be worth a 1000 words!
Part 2:
Please use the snippet tool in windows to grab a screen shot so that I can see what is wrong.
It is very difficult to diagnose things remotely via just words.
Here are some more things to check.
1 - Are you a local admin of the laptop or server?
2 - Make sure you open the SQL server configuration manager as an admin.
This can be accomplished by right clicking the icon and selecting run as an admin instead of a double click to launch.
Below is a sample image of my configuration manager.
Here is the status of my SQL Server agent and the account it is running under.

Determining if a job is running

I have a job set up in SQL Server called "Retreat Update". It is a job that the SQL Server Agent runs every 45 minutes. Is there a SELECT statement or a system stored procedure that I can execute to determine if the job is currently running or if its idle?
I think you can use sp_help_job to see the status of the jobs on the server. You can see more information on it here.
From my search on SQL Help, try...
EXEC dbo.sp_help_job #Job_name = 'Retreat Update'

Scheduled run of stored procedure on SQL server

Is it possible to set up somehow Microsoft SQL Server to run a stored procedure on regular basis?
Yes, in MS SQL Server, you can create scheduled jobs. In SQL Management Studio, navigate to the server, then expand the SQL Server Agent item, and finally the Jobs folder to view, edit, add scheduled jobs.
If MS SQL Server Express Edition is being used then SQL Server Agent is not available. I found the following worked for all editions:
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.
A related question is: How to run a stored procedure every day in SQL Server Express Edition?
Yes, if you use the SQL Server Agent.
Open your Enterprise Manager, and go to the Management folder under the SQL Server instance you are interested in. There you will see the SQL Server Agent, and underneath that you will see a Jobs section.
Here you can create a new job and you will see a list of steps you will need to create. When you create a new step, you can specify the step to actually run a stored procedure (type TSQL Script). Choose the database, and then for the command section put in something like:
exec MyStoredProcedure
That's the overview, post back here if you need any further advice.
[I actually thought I might get in first on this one, boy was I wrong :)]
Probably not the answer you are looking for, but I find it more useful to simply use Windows Server Task Scheduler
You can use directly the command sqlcmd.exe -S "." -d YourDataBase -Q "exec SP_YourJob"
Or even create a .bat file. So you can even 2x click on the task on demand.
This has also been approached in this HERE
I'll add one thing: where I'm at we used to have a bunch of batch jobs that ran every night. However, we're moving away from that to using a client application scheduled in windows scheduled tasks that kicks off each job. There are (at least) three reasons for this:
We have some console programs that need to run every night as well. This way all scheduled tasks can be in one place. Of course, this creates a single point of failure, but if the console jobs don't run we're gonna lose a day's work the next day anyway.
The program that kicks off the jobs captures print messages and errors from the server and writes them to a common application log for all our batch processes. It makes logging from withing the sql jobs much simpler.
If we ever need to upgrade the server (and we are hoping to do this soon) we don't need to worry about moving the jobs over. Just re-point the application once.
It's a real short VB.Net app: I can post code if any one is interested.
You could use SQL Server Service Broker to create custom made mechanism.
Idea (simplified):
Write a stored procedure/trigger that begins a conversation (BEGIN DIALOG) as loopback (FROM my_service TO my_service) - get conversation handler
DECLARE #dialog UNIQUEIDENTIFIER;
BEGIN DIALOG CONVERSATION #dialog
FROM SERVICE [name]
TO SERVICE 'name'
...;
Start the conversation timer
DECLARE #time INT;
BEGIN CONVERSATION TIMER (#dialog) TIMEOUT = #time;
After specified number of seconds a message will be sent to a service. It will be enqueued with associated queue.
CREATE QUEUE queue_name WITH STATUS = ON, RETENTION = OFF
, ACTIVATION (STATUS = ON, PROCEDURE_NAME = <procedure_name>
, MAX_QUEUE_READERS = 20, EXECUTE AS N'dbo')
, POISON_MESSAGE_HANDLING (STATUS = ON)
Procedure will execute specific code and reanable timer to fire again.
You can find fully-baked solution(T-SQL) written by Michał Gołoś called Task Scheduler
Key points from blog:
Pros:
Supported on each version (from Express to Enterprise). SQL Server Agent Job is not available for SQL Server Express
Scoped to database level. You could easiliy move database with associated tasks (especially when you have to move around 100 jobs from one enviromnent to another)
Lower privileges needed to see/manipulate tasks(database level)
Proposed distinction:
SQL Server Agent (maintenance):
backups
index/statistics rebuilds
replication
Task Scheduler (business processes):
removing old data
preaggregations/cyclic recalculations
denormalization
How to set it up:
get source code from section: "Do pobrania" - To download
(enabling broker/setting up schema tsks/configuration table + triggers + stored procedure)/setting up broker things)
set up configuration table [tsks].[tsksx_task_scheduler] to add new tasks (columns names are self-descriptive, sample task included)
Warning: Blog is written in Polish but associated source code is in English and it is easy to follow.
Warning 2: Before you use it, please make sure you have tested it on non-production environment.
Using Management Studio - you may create a Job (unter SQL Server Agent)
One Job may include several Steps
from T-SQL scripts up to SSIS Packages
Jeb was faster ;)
You should look at a job scheduled using the SQL Server Agent.

Resources