SQL Server equivalent of MySQL DATE_FORMAT() - mysql

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)

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)

is it possible to achieve String to DateTime Conversion in sql server like mysql?

I have created store procedure in mysql for string to datetime conversion. in my application data is dynamic I mean user import CSV file so only user know data format. so user specify data format like DD/MM/YYYY or YYYY-MM-DD or anything the data contain with any separator. I parse this Date Format and convert into mysql string to date conversion format like %d/%m/%Y and use STR_TO_DATE function.
Everything works perfect.
Now I want to achieve same functionality in sql server but in sql server there are some numbers for each date format like 100 in below example.
SELECT convert(datetime, 'Oct 23 2012 11:01AM', 100) -- mon dd yyyy hh:mmAM (or PM)
so in sql server it looks like for some date formats some numbers are fixed.
In my case I want to make date format dynamic so user can enter any date format with any separator.
so anyone has any idea how to achieve same string to datetime conversion functionality in sql server same as in mysql i already have achieved and explain as above.
Thanks in advance.
The thirt parameter in the convert function is optional. If you omit it, you can use it to convert different date formats. These all give the same result (at least with my culture settings):
select convert(datetime, 'Oct 23 2012 11:01AM')
union all
select convert(datetime, '2012-10-23 11:01')
union all
select convert(datetime, '2012/10/23 11:01')
union all
select convert(datetime, '10/23/2012 11:01')
union all
select convert(datetime, '2012 Oct 23 11:01')
Note that the current culture setting will be used to determine some formats. the format 10/23/2012 is a valid date with my settings, but not 23/10/2012. The opposite may be the case with your settings.
I am sorry to say, but the convert using a numeric representing the date format is the only possibility in SQL Server next to creating an own implementation using a stored procedure.
You could optionally create a table containing the various date formats and join that with this statement to get the correct number out, but that sounds not like a real solution to me.
The only solution seems to be to accept this.
I found a sql server function that might assist you in what you want.
CREATE FUNCTION dbo.fnFormatDate (#Datetime DATETIME, #FormatMask VARCHAR(32))
RETURNS VARCHAR(32)
AS
BEGIN
DECLARE #StringDate VARCHAR(32)
SET #StringDate = #FormatMask
IF (CHARINDEX (‘YYYY’,#StringDate) > 0)
SET #StringDate = REPLACE(#StringDate, ‘YYYY’,
DATENAME(YY, #Datetime))
IF (CHARINDEX (‘YY’,#StringDate) > 0)
SET #StringDate = REPLACE(#StringDate, ‘YY’,
RIGHT(DATENAME(YY, #Datetime),2))
IF (CHARINDEX (‘Month’,#StringDate) > 0)
SET #StringDate = REPLACE(#StringDate, ‘Month’,
DATENAME(MM, #Datetime))
IF (CHARINDEX (‘MON’,#StringDate COLLATE SQL_Latin1_General_CP1_CS_AS)>0)
SET #StringDate = REPLACE(#StringDate, ‘MON’,
LEFT(UPPER(DATENAME(MM, #Datetime)),3))
IF (CHARINDEX (‘Mon’,#StringDate) > 0)
SET #StringDate = REPLACE(#StringDate, ‘Mon’,
LEFT(DATENAME(MM, #Datetime),3))
IF (CHARINDEX (‘MM’,#StringDate) > 0)
SET #StringDate = REPLACE(#StringDate, ‘MM’,
RIGHT(’0′+CONVERT(VARCHAR,DATEPART(MM, #Datetime)),2))
IF (CHARINDEX (‘M’,#StringDate) > 0)
SET #StringDate = REPLACE(#StringDate, ‘M’,
CONVERT(VARCHAR,DATEPART(MM, #Datetime)))
IF (CHARINDEX (‘DD’,#StringDate) > 0)
SET #StringDate = REPLACE(#StringDate, ‘DD’,
RIGHT(’0′+DATENAME(DD, #Datetime),2))
IF (CHARINDEX (‘D’,#StringDate) > 0)
SET #StringDate = REPLACE(#StringDate, ‘D’,
DATENAME(DD, #Datetime))
RETURN #StringDate
END
GO
The usage of the function is the following:
SELECT dbo.fnFormatDate (getdate(), ‘MM/DD/YYYY’) – 01/03/2012
SELECT dbo.fnFormatDate (getdate(), ‘DD/MM/YYYY’) – 03/01/2012
SELECT dbo.fnFormatDate (getdate(), ‘M/DD/YYYY’) – 1/03/2012
SELECT dbo.fnFormatDate (getdate(), ‘M/D/YYYY’) – 1/3/2012
SELECT dbo.fnFormatDate (getdate(), ‘M/D/YY’) – 1/3/12
SELECT dbo.fnFormatDate (getdate(), ‘MM/DD/YY’) – 01/03/12
SELECT dbo.fnFormatDate (getdate(), ‘MON DD, YYYY’) – JAN 03, 2012
SELECT dbo.fnFormatDate (getdate(), ‘Mon DD, YYYY’) – Jan 03, 2012
SELECT dbo.fnFormatDate (getdate(), ‘Month DD, YYYY’) – January 03, 2012
SELECT dbo.fnFormatDate (getdate(), ‘YYYY/MM/DD’) – 2012/01/03
SELECT dbo.fnFormatDate (getdate(), ‘YYYYMMDD’) – 20120103
SELECT dbo.fnFormatDate (getdate(), ‘YYYY-MM-DD’) – 2012-01-03
– CURRENT_TIMESTAMP returns current system date and time in standard internal format
SELECT dbo.fnFormatDate (CURRENT_TIMESTAMP,‘YY.MM.DD’) – 12.01.03
Of course you can expand the function so it also can handle times
Reference:
How to format datetime & date in Sql Server 2005
convert function in sqlserver gives you the format.
Here is same question asked : -
Sql Server string to date conversion
SQL Server convert string to datetime
You are not written your sqlserver version : if 2012 , then check link-
http://www.databasejournal.com/features/mssql/the-format-function-in-sql-server-2012.html
You can uset ISDATE function to check that string is valid datetime value.
Make a sp, not a function because it not handle try... catch.. block
create procedure dbo.strToDatefunction
(
#dateString varchar(50)
)
as
BEGIN
Declare #ConvertDateInMDYFormat datetime
set dateformat dmy
/*now start arbitraory string to convert and handle in try catch , so next format apply to convert*/
BEGIN TRY
set #ConvertDateInMDYFormat = (select #dateString,convert(varchar,#dateString,101),101,'mm/dd/yy')
END TRY
BEGIN CATCH
END CATCH
/*apply second format you want */
BEGIN TRY
set #ConvertDateInMDYFormat = (select #dateString,convert(varchar,#dateString,101),103,'mm/dd/yy')
END TRY
BEGIN CATCH
END CATCH
.... apply all format as above which possbile to give datetime as per your requirement
return #ConvertDateInMDYFormat
END

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.

How to get a particular date format ('dd-MMM-yyyy') in SELECT query SQL Server 2008 R2

I am using CONVERT(data_type(length),expression,style) function to change the format of a date in a SELECT query.
Declare #dt nvarchar(20)
Select #dt = Convert(nvarchar(20), SalesDate, 113) FROM SalesTable
The format I need is 'dd-MMM-yyyy' (eg. '05-Jul-2013') but I could not find the proper style number (eg. 113) for this particular format. Can any one help me with that please?
Try this:
Declare #dt NVARCHAR(20)
Select
#dt = REPLACE(CONVERT(CHAR(15), SalesDate, 106),' ',' - ')
FROM SalesTable
select CONVERT(NVARCHAR, SYSDATETIME(), 106) AS [DD-MON-YYYY]
or else
select REPLACE(CONVERT(NVARCHAR,GETDATE(), 106), ' ', '-')
both works fine
It doesn't look like DD-MMM-YYYY is supported by default (at least, with dash as separator). However, using the AS clause, you should be able to do something like:
SELECT CONVERT(VARCHAR(11), SYSDATETIME(), 106) AS [DD-MON-YYYY]
See here: http://www.sql-server-helper.com/sql-server-2008/sql-server-2008-date-format.aspx
I Think this is the best way to do it.
REPLACE(CONVERT(NVARCHAR,CAST(WeekEnding AS DATETIME), 106), ' ', '-')
Because you do not have to use varchar(11) or varchar(10) that can make problem in future.
SELECT Convert(varchar(10),CONVERT(date,'columnname',105),105) as "end";
OR
SELECT CONVERT(VARCHAR(10), CAST(event_enddate AS DATE), 105) AS [end];
will return the particular date in the format of 'dd-mm-yyyy'
The result would be like this..
04-07-2016
select convert(varchar(11), transfer_date, 106)
got me my desired result of date formatted as 07 Mar 2018
My column transfer_date is a datetime type column and I am using SQL Server 2017 on azure
select FORMAT(getdate(), 'dd-MMM-yyyy') as DateToday
Other answers here seem to return columns that are quite wide.
This answer returns a varchar(11) which is all that is required for a date in dd-Mon-yyyy format.
'SalesDate' = CONVERT(VARCHAR(11),REPLACE(CONVERT(VARCHAR(11),SalesDate, 106), ' ', '-')),
Try also:
select CONVERT(VARCHAR(11),REPLACE(CONVERT(VARCHAR(11),getdate(), 106), ' ', '-'))
As of today, this gives a result as per: 22-Jul-2021

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()'