This works for me: (i.e. I only need 2 columns of the 30+ returned by sp_help_job
)
SELECT name, current_execution_status
FROM OPENQUERY (MYSERVER,
'EXEC msdb.dbo.sp_help_job @job_name = ''My Job'', @job_aspect = ''JOB''');
Before this would work, I needed to run this:
sp_serveroption 'MYSERVER', 'DATA ACCESS', TRUE;
....to update the sys.servers
table. (i.e. Using a self-reference within OPENQUERY seems to be disabled by default.)
For my simple requirement, I ran into none of the problems described in the OPENQUERY section of Lance's excellent link.
Rossini, if you need to dynamically set those input parameters, then use of OPENQUERY becomes a little more fiddly:
DECLARE @innerSql varchar(1000);
DECLARE @outerSql varchar(1000);
-- Set up the original stored proc definition.
SET @innerSql =
'EXEC msdb.dbo.sp_help_job @job_name = '''+@param1+''', @job_aspect = N'''+@param2+'''' ;
-- Handle quotes.
SET @innerSql = REPLACE(@innerSql, '''', '''''');
-- Set up the OPENQUERY definition.
SET @outerSql =
'SELECT name, current_execution_status
FROM OPENQUERY (MYSERVER, ''' + @innerSql + ''');';
-- Execute.
EXEC (@outerSql);
I'm not sure of the differences (if any) between using sp_serveroption
to update the existing sys.servers
self-reference directly, vs. using sp_addlinkedserver
(as described in Lance's link) to create a duplicate/alias.
Note 1: I prefer OPENQUERY over OPENROWSET, given that OPENQUERY does not require the connection-string definition within the proc.
Note 2:
Having said all this: normally I would just use INSERT ... EXEC :) Yes, it's 10 mins extra typing, but if I can help it, I prefer not to jigger around with:
(a) quotes within quotes within quotes, and
(b) sys tables, and/or sneaky self-referencing Linked Server setups (i.e. for these, I need to plead my case to our all-powerful DBAs :)
However in this instance, I couldn't use a INSERT ... EXEC construct, as sp_help_job
is already using one. ("An INSERT EXEC statement cannot be nested.")