How to format datetime in SQL SERVER - sql-server

I am trying to port MySQL function DATE_FORMAT(date,'%y-%m-%d %h:%i:%s %p') to MsSQL equivalent by using CONVERT().
How to format equivalent datetime string in SQL SERVER 2012 to give this output '2014-05-24 01:24:37 AM'?

In SQL Server 2012 and up you can use FORMAT():
SELECT FORMAT(CURRENT_TIMESTAMP, 'yyyy-MM-dd hh:mm:ss tt')
In prior versions, you might need to concatenate two or more different datetime conversions to get what you need, for example:
SELECT
CONVERT(CHAR(10), CURRENT_TIMESTAMP, 23) + ' ' +
RIGHT('0' + LTRIM(RIGHT(CONVERT(CHAR(20), CURRENT_TIMESTAMP, 22), 11)), 11);
See the Date and Time Styles section of CAST and CONVERT (Transact-SQL) for all of the built-in formatting styles.
I would keep in mind that unless you have a good reason for it, I mean a really good reason, formatting is usually a better job for the technology displaying the data.

Related

SQL Server stored procedure passing date parameters

ALTER PROCEDURE [dbo].[AccountsData]
#Start_Date datetime,
#End_Date datetime
AS
BEGIN
SET NOCOUNT ON;
SELECT
a.Customer_AC_No, a.Customer_Name, a.Product_Code,
a.Product_Description, a.Sales_Person, c.HSID
FROM
(SELECT
Customer_AC_No, Customer_Name, Product_Code,
Product_Description, Sales_Person
FROM
View_Sales_Details
WHERE
([Week Ending] >=' #Start_Date') AND ([Sales Value] > 0)
GROUP BY
Customer_AC_No, Product_Code, Product_Description,
Customer_Name, Sales_Person) AS a
LEFT JOIN
(SELECT
Customer_AC_No, Product_Code
FROM
View_Sales_Details
WHERE
([Week Ending] >= '#End_Date') AND ([Sales Value] > 0)
GROUP BY
Customer_AC_No, Product_Code) AS b ON a.Customer_AC_No = b.Customer_AC_No
AND a.Product_Code = b.Product_Code
INNER JOIN
Hubspot.dbo.View_BPA_Cust_Data AS c ON a.Customer_AC_No = c.CustomerNo COLLATE Latin1_General_100_CI_AS
WHERE
b.Customer_AC_No IS NULL
ORDER BY
a.Customer_AC_No, a.Product_Code ASC
END
I am trying to pass the above date parameters to the SQL Server stored procedure above, but I keep getting this error
Msg 241, Level 16, State 1, Procedure AccountsData, Line 52
Conversion failed when converting date and/or time from character string.
Can some one please help. WeekEnding date is also in datetime format. Thanks
There are many formats supported by SQL Server for specifying a date&time as a string literal - see the MSDN Books Online on CAST and CONVERT. Most of those formats are dependent on what settings you have - therefore, these settings might work some times - and sometimes not.
The way to solve this is to use the (slightly adapted) ISO-8601 date format that is supported by SQL Server - this format works always - regardless of your SQL Server language and dateformat settings.
The ISO-8601 format is supported by SQL Server comes in two flavors:
YYYYMMDD for just dates (no time portion); note here: no dashes!, that's very important! YYYY-MM-DD is NOT independent of the dateformat settings in your SQL Server and will NOT work in all situations!
or:
YYYY-MM-DDTHH:MM:SS for dates and times - note here: this format has dashes (but they can be omitted), and a fixed T as delimiter between the date and time portion of your DATETIME.
This is valid for SQL Server 2000 and newer.
If you use SQL Server 2008 or newer and the DATE datatype (only DATE - not DATETIME!), then you can indeed also use the YYYY-MM-DD format and that will work, too, with any settings in your SQL Server.
Don't ask me why this whole topic is so tricky and somewhat confusing - that's just the way it is. But with the YYYYMMDD format, you should be fine for any version of SQL Server and for any language and dateformat setting in your SQL Server.
The recommendation for SQL Server 2008 and newer is to use DATE if you only need the date portion, and DATETIME2(n) when you need both date and time. You should try to start phasing out the DATETIME datatype if ever possible.
So in your case, either switch to using DATE as your parameter datatype (since you obviously don't use the time portion):
ALTER PROCEDURE [dbo].[AccountsData]
#Start_Date DATE,
#End_Date DATE
and then execute your stored procedure like this:
EXEC [dbo].[AccountsData] '2019-05-11', '2020-06-10'
or use this format to support DATETIME if you insist on keeping that:
EXEC [dbo].[AccountsData] '2019-05-11T00:00:00', '2020-06-10T00:00:00'
Your have an error in your select. You have change your query like this
DATEPART(wk, Ending)>=DATEPART(wk, #Start_Date) AND ([Sales Value] > 0)
DATEPART(wk, Ending)>=DATEPART(wk, #End_Date) AND ([Sales Value] > 0)

Conversion failed when converting date and/or time from character string in MS SQL Server 2017

I am a newbie to MS SQL Server, I get the error
Conversion failed when converting date and/or time from character string
running the following query:
CREATE TABLE DateVals
(
dt datetime,
t time,
dt2 datetime2,
dts datetimeoffset
);
GO
INSERT INTO DateVals (dt, t, dt2, dts)
VALUES ('2011-01-01 23:10:10.003', '23:10:10.003', '2011-01-01 23:10:10.003', '2011-01-01 23:10:10.003 +02.00');
GO
Could you tell me why I get this error?
PS. My OS language is Polish
Your query is correct, just need a colon instead of a comma in the datetimeoffset when you use +02:00.
INSERT INTO DateVals (dt, t, dt2, dts)
VALUES ('2011-01-01 23:10:10.003', '23:10:10.003', '2011-01-01 23:10:10.003', '2011-01-01 23:10:10.003 +02:00');
Instead of
INSERT INTO DateVals (dt, t, dt2, dts)
VALUES ('2011-01-01 23:10:10.003', '23:10:10.003', '2011-01-01 23:10:10.003', '2011-01-01 23:10:10.003 +02.00');
Converting a string literal into a DATETIME column is quite an adventure - and DATETIME is very peculiar about what formats are supported.
The best way to solve this is to use the (slightly adapted) ISO-8601 date format that is supported by SQL Server - this format works always - regardless of your SQL Server language and dateformat settings.
The ISO-8601 format is supported by SQL Server comes in two flavors:
YYYYMMDD for just dates (no time portion); note here: no dashes!, that's very important! YYYY-MM-DD is NOT independent of the dateformat settings in your SQL Server and will NOT work in all situations!
or:
YYYY-MM-DDTHH:MM:SS for dates and times - note here: this format has dashes (but they can be omitted), and a fixed T as delimiter between the date and time portion of your DATETIME.
So in your case, try either:
INSERT INTO DateVals (dt, t, dt2, dts)
VALUES ('2011-01-01T23:10:10', '23:10:10.003', '2011-01-01 23:10:10.003', '2011-01-01 23:10:10.003 +02:00');
(you also need to use a : in the +02:00 moniker for the DATETIMEOFFSET - not a dot or comma)
or make dt in your table a column of type DATETIME2(n) (instead of DATETIME).
This is valid for SQL Server 2000 and newer.
If you use SQL Server 2008 or newer and the DATE datatype (only DATE - not DATETIME!), then you can indeed also use the YYYY-MM-DD format and that will work, too, with any settings in your SQL Server.
Don't ask me why this whole topic is so tricky and somewhat confusing - that's just the way it is. But with the YYYYMMDD format, you should be fine for any version of SQL Server and for any language and dateformat setting in your SQL Server.
The recommendation for SQL Server 2008 and newer is to use DATE if you only need the date portion, and DATETIME2(n) when you need both date and time. You should try to start phasing out the DATETIME datatype if ever possible

can't find the date style format in sql server 2012

I want to convert this nvarchar column to Datetime format:
"29/12/14 07:46:20 PM"
This style is good but has no time:
SELECT CONVERT(datetime, nvarcharDateColumn, 3) AS [DD/MM/YY]
How can i convert it and keep all the date parts (date+time) ??
A datetime data type in SQL Server has no "format". It is natively a 8-byte binary value. To convert the nvarchar string to datetime, use CONVERT with the nvarchar column as the second parameter:
SELECT CONVERT(datetime, nvarcharColumnWithDateAndTime, 3) AS NativeDateTime
FROM dbo.YourTable;
Note the datetime format displayed by this query is determined by the application your are using, not the SQL Server database. Also, consider changing the table data type to datetime to avoid data integrity issues; nvarchar will allow storing invalid dates.
This one has time, however includes Miliseconds...it could be too much :)
SELECT CONVERT(VARCHAR(30), GETDATE(), 131)
This is a harder task that I would have thought. This is the best I could come up with:
DECLARE #MyDate DATETIME
SET #MyDate = GETDATE()
SELECT CONVERT(VARCHAR(50), #MyDate, 3) + ' ' + CONVERT(VARCHAR(50), CONVERT(TIME, #MyDate), 100)

what is the best way to insert only datepart of system date into SQL Server

I'm currently using
Convert(varchar, Getdate(), 101)
to insert only date part of system date into one of my sql server database tables.
my question is: is it the right way to do that or is there any other better method to do it?
I don't understand why you're converting the GETDATE() output (which is DATETIME already) to a VARCHAR and then SQL Server would convert it back to DATETIME upon inserting it again.
Just use:
INSERT INTO dbo.YourTable(SomeDateTimeColumn)
VALUES(GETDATE())
If you're doing that conversion to get rid of the time portion of the DATETIME, you should better:
use the DATE datatype (available in SQL Server 2008 and newer) to store only the DATE (no time)
if you're using SQL Server 2005 or earlier, use this conversion instead - should be much more efficient than two conversions!
INSERT INTO dbo.YourTable(SomeDateTimeColumn)
VALUES(DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0))
Update: did some performance testing, and in this particular case, it seems the amount of work that SQL Server needs to do is really the same - regardless of whether you're using the convert to varchar stripping the time and back to datetime approach that you already have, or whether you're using my get the number of days since date 0 approach. Doesn't seem to make a difference in the end.
The BEST solution however would still be: if you only need the date anyway - use a column of type DATE (in SQL Server 2008 and newer) and save yourself any conversions or manipulations of the GETDATE() output altogether.

12 hr time format in sql like.. 02:32:00 PM

How can I get the time like 02:32:00 PM in sql server?
I can get 24 hr with the following code.
CONVERT(VARCHAR(26), getdate(), 108)
But I want pure hh:mm:ss tt not with milliseconds.
I found the one with milliseconds.
select convert(varchar, getdate(), 109)
How to achieve that?
SELECT RIGHT('0' + LTRIM(STUFF(RIGHT(CONVERT(CHAR(26), CURRENT_TIMESTAMP, 109), 14),9, 4, ' ')),11)
See the SQL Server Books Online for a full listing of all supported styles / formats for date/time conversion using CONVERT.
There doesn't seem to be an exact match for what you're looking for, I'm afraid. You'll have to use some other, supported format and possibly do some string manipulation on the result yourself.
Those are all the supported formats - there is no way I'm aware of to extend this (other than writing a SQL CLR module yourself and plugging it into SQL Server).

Resources