SQL Server Agent - Can Job Ask Information About Itself - sql-server-2008

I don't suppose anyone knows whether a SQL Server Agent Job can ask information about itself, such as its own ID, or the path it's running from? I'm aware of xp_sqlagent_enum_jobs and sp_help_job but this doesn't help, because you have to specify the job ID.
The idea is that we want code that we don't have to manage by being able to call a sproc which will identify the current job. Any ideas?

Yes, but it isn't pretty.
Look at the sys.sysprocesses (or dbo.sysprocesses in SQL 2000 and below). The program name will be SQL Agent something with a binary value at the end. That binary value is the binary vale of the guid of the job. So, substring out that value and do a lookup against the msdb.dbo.sysjobs table to find out what job it is (you'll need to cast the sysjobs.job_id to varbinary(100) to get the values to match).
I told you it wasn't pretty, but it will work.

nasty!!! but i think it might work...
eg. used within a job - select * from msdb..sysjobs where job_id = dbo.fn_currentJobId()
let me know.
create function dbo.fn_CurrentJobId()
returns uniqueidentifier
as
begin
declare #jobId uniqueidentifier
select #jobId = j.job_id
from master..sysprocesses s (nolock)
join msdb..sysjobs j (nolock)
on (j.job_id = SUBSTRING(s.program_name,38,2) + SUBSTRING(s.program_name,36,2) + SUBSTRING(s.program_name,34,2) + SUBSTRING(s.program_name,32,2) + '-' + SUBSTRING(s.program_name,42,2) + SUBSTRING(s.program_name,40,2) + '-' + SUBSTRING(s.program_name,46,2) + SUBSTRING(s.program_name,44,2) + '-' + SUBSTRING(s.program_name,48,4) + '-' + SUBSTRING(s.program_name,52,12) )
where s.spid = ##spid
return #jobId
end
go
thanks for the info though

Related

SSRS Report Parameters passed out

I am currently building a number of logging and analysis tools to keep tabs on our SQL environment. We are currently using SQL Server 2014.
What I want to do is keep check of all the parameters that are passed to our reports during the day. All of the reports are currently using stored procedures so in my table or a select statement based on a table is output the stored procedure with the parameters for every time the report was run.
At the end of the day I would then like to be able to take the outputted statement and run it in SSMS without having to use the report. I have been looking at the ExceutionLogStorage table and the ExecutionLog view's and though it has most of the information that I need, the parameters are not in an easily usable state.
Has anyone done something similar to what I have described?
You need to add logging part in your original SP, for example:
Alter procedure a
(#parameter)
As
Begin
..
..
Insert into loggingTable(col)
Values(#parameter)
..
..
End
Then query directly against that loggingTable for getting the history of used parameters
A Google search around this topic quickly brought up the following blog post already identified by the OP as useful and shown below (this query itself is actually an expansion of work linked to by LONG's answer below)
SELECT TOP 1 ParValue
FROM (
SELECT els.TimeEnd
, IIF(CHARINDEX('&' + 'ParameterName' + '=', ParsString) = 0, 'ParameterName',
SUBSTRING(ParsString
, StartIndex
, CHARINDEX('&', ParsString, StartIndex) - StartIndex)) AS ParValue
FROM (SELECT ReportID, TimeEnd
, '&' + CONVERT(VARCHAR(MAX), Parameters) + '&' AS ParsString
, CHARINDEX('&' + 'ParameterName' + '=', '&' + CONVERT(VARCHAR(MAX), Parameters) + '&')
+ LEN('&' + 'ParameterName' + '=') AS StartIndex
FROM ExecutionLogStorage
WHERE UserName='UserName' -- e.g. DOMAIN\Joe_Smith
) AS els
INNER JOIN [Catalog] AS c ON c.ItemID = els.ReportID
WHERE c.Name = 'ReportName'
UNION ALL
SELECT CAST('2000-01-01' AS DateTime), 'ParameterName'
) i
ORDER BY TimeEnd DESC;
Both these approaches though really only give us a starting point since they (variously) rely upon us knowing in advance the report name and parameter names. Whilst we can quickly make a couple of changes to Ken Bowman's work to get it to run against all executions of all reports, we still have the problem that the query hardcodes the parameter name.
The parameters required to execute a report are stored on the Catalog table in the Parameter column. Although the column has a datatype ntext, it is actually storing an XML string. Meaning we can use an XPath query to get at the parameter names
with
CatalogData as (
select ItemID, [Path], [Name], cast(Parameter as xml) 'ParameterXml'
from Catalog
where [Type] = 2),
ReportParameters as (
select ItemID, [Path], [Name], ParameterXml, p.value('Name[1]', 'nvarchar(256)') 'ParameterName'
from CatalogData
cross apply ParameterXml.nodes('/Parameters/Parameter') as Parameters(p))
select *
from ReportParameters;
Executing this query will list all reports on the server and their parameters. Now we just need to combine this with Ken Bowman's query. I've gone with a CTE approach
with
CatalogData as (
select ItemID, [Path], [Name], cast(Parameter as xml) 'ParameterXml'
from Catalog
where [Type] = 2),
ReportParameters as (
select ItemID, [Path], [Name], p.value('Name[1]', 'nvarchar(256)') 'ParameterName'
from CatalogData
cross apply ParameterXml.nodes('/Parameters/Parameter') as Parameters(p))
select
els.TimeEnd
, c.[Name]
, rp.ParameterName
, iif(
charindex(
'&' + rp.ParameterName + '=', ParametersString) = 0
, rp.ParameterName, substring(ParametersString
, StartIndex, charindex('&', ParametersString, StartIndex) - StartIndex
)) 'ParameterValue'
from (
select
ReportID
, TimeEnd
, rp.ParameterName
, '&' + convert(varchar(max), Parameters) + '&' 'ParametersString'
, charindex(
'&' + rp.ParameterName + '=',
'&' + convert(varchar(max), Parameters) + '&'
) + len('&' + rp.ParameterName + '=') 'StartIndex'
from
ExecutionLogStorage
inner join ReportParameters rp on rp.ItemID = ReportID) AS els
inner join [Catalog] c on c.ItemID = els.ReportID
inner join ReportParameters rp on rp.ItemID = c.ItemID and rp.ParameterName = els.ParameterName;
Note that the parameter values are passed to the report as part of a URL, so you'll still need get rid the literal space encoding and so on. Also, this doesn't (yet...) work for multi-value parameters.

SQL server triming

I am trying to format the licenseenum column in my table by removing everything starting the before space and also I would like to remove any character in licenseenum column starting after '-' including '-'
For example:
current data in Licenseenum GA 350-0
What I'm trying to get 350
Here is my code
select Licenseenum, SUBSTRING (Licenseenum, 4, LEN(Licenseenum)-1)
from licensee
this results
350-0
How would I remove -0 from the results?
Thanks for the help
Try it like this
DECLARE #YourString VARCHAR(100)='GA 350-0';
SELECT SUBSTRING(#YourString,CHARINDEX(' ',#YourString,1),CHARINDEX('-',#YourString,1)-CHARINDEX(' ',#YourString,1));
UPDATE 1
This is quite the same, but better to read
DECLARE #YourString VARCHAR(100)='GA 350-0';
WITH Positions AS
(
SELECT CHARINDEX(' ',#YourString,1) AS posBlank
,CHARINDEX('-',#YourString,1) AS posMinus
)
SELECT SUBSTRING(#YourString,posBlank,posMinus-posBlank)
FROM Positions;
UPDATE 2 Avoid the leading blank...
My logic needs small correction in order to cut the blank before the number:
SELECT SUBSTRING(#YourString,posBlank+1,posMinus-posBlank-1)
Would be the same with the first example...
Please try the below code. Its working fine in SQL Server 2012.
DECLARE #Licenseenum varchar(max)
SET #Licenseenum ='GA 350-0'
DECLARE #TempLicense VARCHAR(100)
DECLARE #License VARCHAR(100)
IF (len(#Licenseenum ) - len(replace(#Licenseenum ,' ',''))>=1)
SET #TempLicense = (SELECT REVERSE(LEFT(REVERSE(#Licenseenum ),CHARINDEX(' ', REVERSE(#Licenseenum ), 1) - 1)))
ELSE
SET #TempLicense = #Licenseenum
SELECT #License = (SELECT LEFT(#TempLicense,LEN(#TempLicense) - charindex('-',reverse(#TempLicense),1)))
SELECT #License AS Licenseenum

How to Convert DATETIME to CHAR in MS SQL

I need to convert a MS SQL date time a specific format:
MM/DD/YYYY HH:MM AMPM
which means that the HH has to have a leading zero if necessary: 03:25 PM instead of 3:25 PM.
Also, there should be a space between the minutes and either AM or PM.
I couldn't find one of the convert codes to match this.
In case it matters, this is SQL Server 2008 R2.
Use the new FORMAT function:
DECLARE #dt DATETIME = '2016-04-18 15:05:22'
SELECT FORMAT(#dt, 'MM/dd/yyyy hh:mm tt')
-- output: 04/18/2016 03:05 PM
Available from SQL Server 2012.
Reference: https://msdn.microsoft.com/en-us/library/ee634398.aspx
Examples: http://sqlhints.com/2013/06/23/format-string-function-in-sql-server-2012/
SELECT CONVERT(NVARCHAR,GETDATE(),101) + ' ' +
CASE SUBSTRING(CONVERT(NVARCHAR,GETDATE(),100),13,1) WHEN ' ' THEN '0' ELSE SUBSTRING(CONVERT(NVARCHAR,GETDATE(),100),13,1) END +
SUBSTRING(CONVERT(NVARCHAR,GETDATE(),100),14,4) + ' ' + RIGHT(CONVERT(NVARCHAR,GETDATE(),100),2)
Might I also suggest this code:
DECLARE #OFDate DATETIME
SET #OFDate = DATEADD(hh,13,GETDATE())
SELECT CONVERT(NVARCHAR,#OFDate,101) + ' ' +
CASE SUBSTRING(CONVERT(NVARCHAR,#OFDate,100),13,1) WHEN ' ' THEN '0' ELSE SUBSTRING(CONVERT(NVARCHAR,#OFDate,100),13,1) END +
SUBSTRING(CONVERT(NVARCHAR,#OFDate,100),14,4) + ' ' + RIGHT(CONVERT(NVARCHAR,#OFDate,100),2)
which you can use to offset the current date to prove that it works for multiple cases. For instance, when I use the numbers 0, 1, 12 and 13 right now, I get:
04/18/2016 09:34 AM
04/18/2016 10:34 AM
04/18/2016 09:34 PM
04/18/2016 10:34 PM
which means you can probably guess my time zone.
This is pretty cumbersome code. I don't know if you can do any better or not, but it will hopefully get you started. I suggest that if you are going to be needing this in a lot of places, but without a whole lot of access in your procedure, that you could use a function to return it. If you're going to be doing it for lots of different lines in a table, though, you're better off just to put the unelegant, complicated code right into your procedure.
CAST and CONVERT (Transact-SQL)
SELECT CONVERT (VARCHAR, GETDATE(), 101) + ' ' + CONVERT (VARCHAR,CONVERT (TIME, GETDATE()))
or
change the language setting in your session with
SET LANGUAGE us_english
SELECT * FROM sys.syslanguages
With Microsoft Sql Server:
--
-- Create test case
--
DECLARE #myDateTime DATETIME
SET #myDateTime = '2016-04-03'
--
-- Convert string
--
SELECT LEFT(CONVERT(VARCHAR, #myDateTime, 120), 10)

SQL Server Date Range Selection on Execution

I am running the below query in SQL Server 2008 which is returning data items post 01/01/2014.
How do I change the query to prompt for a date range on execution so I can return data between specific dates? I eventually want to create this as a view on the database and run the query through MS Excel.
SELECT J_CODATE as Typed_Date,
J_CRDATE as Created_Date,
J_AUTHOR as Author_Id,
CAST(A_FNAME + ' ' + A_SURNAME AS NVARCHAR) AS Author_Name,
J_JNUMBER as Job_Number,
J_SRSTATUS as SR_Status,
J_LENGTH as Job_Length,
J_TRANTIME as Typing_Time,
J_TRANS as Typist_id,
CAST(T_FNAME + ' ' + T_SURNAME AS NVARCHAR) AS Typist_Name,
CAST(J_TRANTIME AS FLOAT) / CAST(Job.J_LENGTH AS FLOAT) AS Productivity_Factor
FROM author, job, trans
WHERE J_CODATE >= '2014-01-01 00:00:00'
and J_LENGTH > 0 and J_TRANTIME > 1 and J_SRSTATUS > 0
and (Cast(J_LENGTH as Float) / Cast(J_TRANTIME as Float)) < 2
and (Cast(J_TRANTIME as Float) / Cast(J_LENGTH as Float)) < 20
and Job.J_TRANS = Trans.T_ID
and Job.J_AUTHOR = author.A_ID
ORDER BY J_CODATE desc
Thanks
So your goal is to access database data through Excel, and to have Excel prompt you for the parameters?
There is no way to build into a query the ability to prompt you for parameters. Where would the prompt appear - on the screen of the server? What would happen if the program doing the querying was a Windows service or some other process that doesn't have a UI?
You can do it in MS Access, because Access is both a database and a UI for manipulating that database. But even in Access, if an application other than the Access executable is attempting to use the database, you will not be prompted within that program for parameters: you'll just get an exception if the parameters are not provided when the program attempts to execute the query.
So this is at least half an Excel question. I'm not sure whether Excel's data tools include the ability to prompt you for parameters, although I expect it can. But you'll have to do research on that.
To address the SQL Server part of your question: probably the simplest way to parameterize your query would be to create a stored procedure, which Excel will execute for you through its data tools. It would look like this:
CREATE PROCEDURE dbo.TestProcedure
(
#StartDate datetime,
#EndDate datetime
)
AS
SELECT J_CODATE as Typed_Date,
J_CRDATE as Created_Date,
J_AUTHOR as Author_Id,
CAST(A_FNAME + ' ' + A_SURNAME AS NVARCHAR) AS Author_Name,
J_JNUMBER as Job_Number,
J_SRSTATUS as SR_Status,
J_LENGTH as Job_Length,
J_TRANTIME as Typing_Time,
J_TRANS as Typist_id,
CAST(T_FNAME + ' ' + T_SURNAME AS NVARCHAR) AS Typist_Name,
CAST(J_TRANTIME AS FLOAT) / CAST(Job.J_LENGTH AS FLOAT) AS Productivity_Factor
FROM author, job, trans
WHERE J_CODATE BETWEEN #StartDate and #EndDate
and J_LENGTH > 0 and J_TRANTIME > 1 and J_SRSTATUS > 0
and (Cast(J_LENGTH as Float) / Cast(J_TRANTIME as Float)) < 2
and (Cast(J_TRANTIME as Float) / Cast(J_LENGTH as Float)) < 20
and Job.J_TRANS = Trans.T_ID
and Job.J_AUTHOR = author.A_ID
ORDER BY J_CODATE desc
If that looks a lot like your query, it's because it is: aside from wrapping it in a stored procedure, I turned the date literal you used into the parameters #StartDate and #EndDate, since you said you wanted a date range.

Indexing issue in sql server

hey guys,
i have a query in sql server which takes atleast 10-15 seconds to execute, and when this is called in asp.net, it is more worst there, it just throws request timeout error.
Below is the query i am using.
SELECT C.Id,
C.Summary,
C.Title,
C.Author,
CONVERT(VARCHAR(12), C.PublishDate, 104)
AS 'DATE',
'/Article/' + SUBSTRING(dbo.RemoveSpecialChars(C.Title), 0, 10) + '/' + CAST(CA.CategoryId AS VARCHAR(MAX)) + '/' + CAST(C.Id AS VARCHAR(MAX)) +
'.aspx' AS
'URL'
FROM CrossArticle_Article C
INNER JOIN CrossArticle_ArticleToCategory CA
ON C.Id = CA.ArticleId
WHERE C.Title LIKE '%' + #KEYWORD + '%'
OR C.Summary LIKE '%' + #KEYWORD + '%'
OR C.Article LIKE '%' + #KEYWORD + '%'
SELECT ##ROWCOUNT
Below are the Fields Specification.
Id int Primary Key
Summary nvarchar(1000)
Title nvarchar(200)
Author nvarchar(200)
PublishDate DateTime
CategoryId int PrimaryKey
i think this can be resolved by using Indexing on these columns using include.. i checked over net, but didnt find any solution..
i would appreciate if i could get help for the same.
Thanks and Regards
Abbas Electricwala
Ordinary column indexing most likely cannot help your query, unfortunately. LIKE conditions can only be assisted by indexes when they are in the form of value% (meaning that you can only have a wildcard on the end of the expression; the prefix must be static).
I am assuming that you already have an index on CrossArticle_Article.Id and CrossArticle_ArticleToCategory.ArticleId. If not, you should add those.