SQL Server Date Range Selection on Execution - sql-server-2008

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.

Related

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)

Using SSIS to query ADO .NET source query passing in parameters from SQL Server

I would like to pass parameters to a MySQL query using ado.net as the source of the query.
SELECT *
FROM userinfo
WHERE load_date > '2012-01-07'
AND load_date < '2012-01-14'
I have a settings table in sql server that has my values:
SELECT startdate, enddate
FROM tblsetting
I have managed to pass these values into SSIS. If I run a query against my sql server tables I am able to use this:
SELECT *
FROM userinfo
WHERE load_date > ?
AND load_date < ?
But when I change my source to ado.net, connecting to mysql server , it does not like that syntax. Can anyone explain what am I missing?
You can write a SQL expression and store it a variable of type String
"SELECT *
FROM userinfo
WHERE load_date > '" + (DT_WSTR,20) #[User::YourDateTimeVar] + "''
AND load_date < '" + (DT_WSTR,20)#[User::YourDateTimeVar] + " ' "
and then use this variable for a property which is present in the expression of Data Flow Task .Write click on DFT and select Properties . Click on Expression and select Ado.NET sql command from the properties in the dialogue box
Select the variable for the above property.Here ADO_SRC_Orale[SqlCommand] property will be replaced by the name of your ADO.NET source

SQL Server equivalent of MySQL DATE_FORMAT()

Hope we're having a good day and all set for Christmas.
Got a quick question. I'm converting a MySQL function into SQL Server, I've got most of the function converted except for one part which has the following:
#description = CONCAT(#description, date_format(#INLastUpdated, '%H:%i %d %b %Y'))
What I'm trying to do is to basically recreate the date_format function to format the date in the same way specified, but I'm not sure how to do it. from what I've seen in the MySQL documentation the format selected would give hour:minute day / short month name / year.
Anyone got any ideas?
You can try this:
DECLARE #description VARCHAR(1000) = 'test'
DECLARE #INLastUpdated DATETIME = '2012-12-21 14:32:22'
SET #description = #description + ' '
+ LEFT(CONVERT(VARCHAR(8), #INLastUpdated, 8), 5) + ' '
+ CONVERT(VARCHAR(20), #INLastUpdated, 106)
SELECT #description
But be careful as format 106 depends on local language settings. Read more on MSDN
The equivalent function is CONVERT. But you're basically out of luck. SQL Server does not allow to cherry-pick the date tokens. You need to browse the available full date built-in formats and choose one, or try to compose an output by string concatenation, as in:
CONVERT(VARCHAR, CURRENT_TIMESTAMP, 103) + ' ' + CONVERT(VARCHAR(8), CURRENT_TIMESTAMP, 114)
Which version of SQL Server? In SQL Server 2012 we now have the FORMAT function.
This, in MySQL
date_format(#INLastUpdated, '%H:%i %d %b %Y')
translates into something like this for SQL Server 2012 using the FORMAT function:
DECLARE #d DATETIME = GETDATE();
SELECT FORMAT(#d, 'HH:mm d MMM yyyy', 'en-US') AS 'DateTime Result';
BOL SQL Server 2012 > FORMAT (Transact-SQL)

adding current date as a parameter to a query in clover ETL

I have a query block for retrieving data from MSSQL Server. the query has some hardcoded date values which needs to be changed everyday to import the daily feed. I need to automate this execution. I am using cloverETL for executing the query right now.
Here is the query (its a query to retrieve sharepoint activity data)
use
DocAve_AuditDB;
DECLARE
#ParameterValue VARCHAR(100),
#SQL
VARCHAR(MAX)
SET
#SQL = STUFF((SELECT 'UNION ALL SELECT COL_ItemTypeName, COL_UserName, COL_MachineIp, COL_DocLocation, DATEADD(SECOND, COL_Occurred / 1000, ''19700101 00:00'') as Date_Occurred, COL_EventAction FROM '+ TABLE_NAME + ' WHERE DATEADD(SECOND, COL_Occurred / 1000, ''19700101 00:00'') BETWEEN '+ '''20120515'''+ 'AND' + '''20120516'''+ 'AND ' + 'COL_ItemTypeName='+ '''Document''' AS 'data()'
FROM INFORMATION_SCHEMA.TABLES
WHERE
TABLE_NAME LIKE '%2012_05%'
FOR
XML PATH('')),1,10,'')
EXEC
(#SQL)
In the above block I want the TABLE_NAME LIKE param i.e. %2012_05% to be a variable retrieved from the current data and also the date values in the between clause
BETWEEN '+ '''20120515'''+ 'AND' + '''20120516'''
to be todays date-1 and todays date
should create a small java program for handling this or it can be done directly in the query itself? if yes how?
Thanks in Advance
Use GETDATE() or CURRENT_TIMESTAMP to obtain the current date (and time).
Use CONVERT() with the 112 format specifier to convert the current timestamp to a string formatted as YYYYMMDD.
Use DATEADD() for calculations (like subtracting one day) on dates/times.
Use SUBSTRING() to subtract parts from the formatted date string to rearrange them to the %YYYY_MM% format.
Or you can use inline ctl notation in DBInputTable:
SELECT 'UNION ALL SELECT COL_ItemTypeName, COL_UserName, COL_MachineIp, COL_DocLocation, DATEADD(SECOND, COL_Occurred / 1000, ''19700101 00:00'') as Date_Occurred, COL_EventAction FROM `date2str(today(), "yyyy_MM")` WHERE DATEADD(SECOND, COL_Occurred / 1000, ''19700101 00:00'') BETWEEN '+ '''`date2str(today(), "yyyyMMdd")`'''+ 'AND' + '''`date2str(dateAdd(today(),1,day), "yyyyMMdd")`'''+ 'AND ' + 'COL_ItemTypeName='+ '''Document''' AS 'data()'

SQL Server Agent - Can Job Ask Information About Itself

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