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)
Related
I have a date in my table that is in there as 2016-12-05 etc
When I use a select statement to get that value back however it comes back in a really odd way: Mon Dec 5 00:00:00 UTC 2016
How do I get this to come back in YYYY-MM-DD?
Edit:
Using JSCRIPT. Select command is
SELECT AccessDate from screens.signoff WHERE BadgeNo = '" + BadgeNo + "'"
BadgeNo being a variable defined above somewhere
Use DATE_FORMAT() function for this
In your case, it will be :
SELECT DATE_FORMAT(AccessDate, '%Y-%m-%d') as AccessDate from screens.signoff WHERE BadgeNo = '" + BadgeNo + "'"
refer this documentation
MySQL DATE_FOMAT() reference
Hope it helps.
I think this can help you.
for MySQL
DATE_FORMAT(STR_TO_DATE(myValue, '%d.%m.%y'), '%Y-%m-%d')
look for str_to_date : http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_str-to-date
edit: for MSSQL
SELECT CONVERT(char(10), GetDate(),126)
why 126? look there: https://msdn.microsoft.com/en-us/library/ms187928.aspx
Use this:
$Date_database= $row['date']; // your database code
$Date= date('Y-m-d', strtotime($Date_database)); // change to right date format
Date Contains 2016-12-05 now
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.
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)
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()'
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