How to flip month and day in a datetime? - sql

How can I flip "2012-12-01 12:33:00.0" to become "2012-01-12 12:33:00.0"? I had tried "select convert(varchar(50), convert(datetime, log_date, 103), 121)" and used both 101 and 103 and still not able to flip it.
The database is MS SQL

DECLARE #date DATETIME
SET DATEFORMAT ydm
SET #date = '2012-12-01 12:33:00.0'
SELECT #date
SET DATEFORMAT ydm will give you the result in your required format.
Other Option
UPDATE Table_Name
SET COLUMN_NAME= convert(varchar(20), convert(Date, #date, 101)) + convert(varchar(30),convert(time, #date))
WHERE
OR
select convert(datetime, convert(varchar(100), #date), 20)

You could just perform some string manipulation (NOTE: Untested code)
UPDATE table
SET date=
LEFT(CONVERT(VARCHAR(50),date,128),4) -- '2012'
+SUBSTRING(CONVERT(VARCHAR(50),date,128),7,3) -- '-01'
+SUBSTRING(CONVERT(VARCHAR(50),date,128),4,3) -- '-12'
+RIGHT(CONVERT(VARCHAR(50),date,128),LEN(CONVERT(VARCHAR(50),date,128))-10) -- ' 12:33:00.0'

You could use the Format function to swap day and month, while keeping the year and hour:
update MyTable
set [date] =
FORMAT([date],'yyyy') + '-' +
FORMAT([date],'dd') + '-' +
FORMAT([date],'MM') + ' ' +
FORMAT([date],'hh:mm:ss')
from MyTable

Related

Retrieve data quarterly(each 3 month) and also show last day of quarter

i have a problem, i cant get the sum for quarterly data.
I want my output like this:
#startdate='5/17/2017'
and
#enddate='5/27/2017
output:
AccountNo 06/30/2017
--------------------------
320002101 3453543.67
320003478 103343.56
user chooses two dates, 1st one is #startdate and another #enddate,
Enddate should be determining what quarter to choose of course, if its May then it must show JUNE(6th month) and the last day of quarter.
My query was something like this, but obviously it doesn't work, i tried mixing up things in data functions
SELECT bal.AccountNo,acc.AccountName ,
DATEADD(quarter,DATEDIFF(quarter,0,#enddate),30) [quarter],
SUM(bal.Sum) [quarterlySum]
FROM dbo.Balances AS bal
INNER JOIN dbo.Accounts AS acc
ON acc.AccountNo = bal.AccountNo
WHERE (bal.BalanceDate BETWEEN #startdate AND #enddate)
GROUP BY acc.AccountName,bal.AccountNo
Not really sure below will work, but it's worth to give a go:
declare #startdate date = (select getdate()- 60 )
declare #enddate date = (select getdate() - 30)
select #startdate, #enddate
declare #sql nvarchar(1000)
set #sql =
'SELECT bal.AccountNo,
SUM(bal.Sum) as ''' + replace(convert(nvarchar(10), DATEADD(dd, -1, DATEADD(qq, DATEDIFF(qq, 0, #enddate) +1, 0)), 101), '/', '') +'''
INNER JOIN dbo.Accounts AS acc
ON acc.AccountNo = bal.AccountNo
WHERE (bal.BalanceDate BETWEEN ''' + convert(varchar, #startdate, 101) + ''' AND ''' + convert(varchar, #enddate, 101) +''')
GROUP BY acc.AccountName'
print #sql
exec (#sql)
I do not think so there is another way than doing this dynamically as above.
My question was to get the end of the quarter from currentdate, and also not just end of the quarter, but the end of the month of the end of the quarter from currentdate
And here is the code, i used to retrieve my data
DECLARE #startdate DATE; SET #startdate='5/2/2017';
DECLARE #enddate DATE; SET #enddate='6/13/2017'
DECLARE #datatype VARCHAR; SET #datatype=3;
SELECT bal.AccountNo,acc.AccountName ,
CASE #datatype WHEN 3 THEN SUM(bal.Sumn)END AS [balance]
FROM dbo.Balances AS bal
INNER JOIN dbo.Accounts AS acc
ON acc.AccountNo = bal.AccountNo
WHERE (bal.BalanceDate BETWEEN convert(varchar, #startdate, 101) AND
convert(varchar, #enddate, 101))
GROUP BY acc.AccountName,bal.AccountNo

sql date format order dd-mm-yyyy

I am using this code to format date with SQL:
convert(VARCHAR, DT, 20)
The output is:
2016-01-01 20:40:12
But how do I get the day first.
I would like to get: dd-mm-yyyy:
01-01-2016 20:40:12
When I look in this table:
http://www.blackwasp.co.uk/sqldatetimeformats.aspx
I do not see this formatting.
Thx!
For dd/mm/yyyy hh:mi:ss
(CONVERT(varchar, DT, 103) + ' ' + CONVERT(varchar, DT, 108)) AS MyEuropeanDate
For dd-mm-yyyy hh:mi:ss
(CONVERT(varchar, DT, 105) + ' ' + CONVERT(varchar, DT, 108)) AS MyEuropeanDate
And to understand it right for the next time, look at the official doc that Gordon wisely linked in the comments :
https://msdn.microsoft.com/en-us/library/ms187928.aspx
Could not find a native tSQL function but you can do something like this:
DECLARE #Date DATETIME = '20160101';
SELECT CASE
WHEN LEN(CAST(DAY(#Date) AS VARCHAR)) = 1 THEN '0'+CAST(DAY(#Date) AS VARCHAR)
ELSE CAST(DAY(#Date) AS VARCHAR)
END
+'-'+
CASE
WHEN LEN(CAST(MONTH(#Date) AS VARCHAR)) = 1 THEN '0'+CAST(MONTH(#Date) AS VARCHAR)
ELSE CAST(MONTH(#Date) AS VARCHAR)
END
+'-'+
CAST(YEAR(#Date) AS VARCHAR)
+' '+
SUBSTRING(CONVERT(VARCHAR, #Date, 114), 1, 8);
OR you can do this:
DECLARE #Date DATETIME = '20160101';
SELECT (REPLACE(CONVERT(varchar, #Date, 103),'/','-') + ' ' + CONVERT(varchar, #Date, 108))
RESULT:

Datetime Format in Month and Year

I want to format a datetime column like so: "March 2004." Currently, I tried
DECLARE #Date VARCHAR(20) = '2004-03-05 01:00'
SELECT CONVERT(VARCHAR(20),CAST(#Date AS DATETIME),13) AS DateFormats
but not getting the right result.
You should really apply formatting when you present your data, not in the query, but to answer the question, if you're using SQL Server 2012 or above you can use FORMAT
DECLARE #Date datetime = '2004-03-05 01:00'
SELECT FORMAT( #Date, 'MMMM yyyy' ) AS DateFormats
Something like:
DECLARE #Date VARCHAR(20) = '2004-03-05 01:00'
SELECT DATENAME(MONTH, #Date) + ' ' + DATENAME(YEAR, #Date)
More on DATENAME can be found here https://msdn.microsoft.com/en-gb/library/ms174395.aspx
Essentially it gets the month part of the date and the year part of the date and concatenate them together.
None of the built-in formats include the full month. Instead, use datename():
select datename(month, #date) + ' ' + datename(year, #date)

How do I get the month and day with leading 0's in SQL? (e.g. 9 => 09)

DECLARE #day CHAR(2)
SET #day = DATEPART(DAY, GETDATE())
PRINT #day
If today was the 9th of December, the above would print "9".
I want to print "09". How do I go about doing this?
Pad it with 00 and take the right 2:
DECLARE #day CHAR(2)
SET #day = RIGHT('00' + CONVERT(NVARCHAR(2), DATEPART(DAY, GETDATE())), 2)
print #day
For SQL Server 2012 and up , with leading zeroes:
SELECT FORMAT(GETDATE(),'MM')
without:
SELECT MONTH(GETDATE())
Use SQL Server's date styles to pre-format your date values.
SELECT
CONVERT(varchar(2), GETDATE(), 101) AS monthLeadingZero -- Date Style 101 = mm/dd/yyyy
,CONVERT(varchar(2), GETDATE(), 103) AS dayLeadingZero -- Date Style 103 = dd/mm/yyyy
Try this :
SELECT CONVERT(varchar(2), GETDATE(), 101)
Leading 0 day
SELECT FORMAT(GetDate(), 'dd')
SQL Server 2012+ (for both month and day):
SELECT FORMAT(GetDate(),'MMdd')
If you decide you want the year too, use:
SELECT FORMAT(GetDate(),'yyyyMMdd')
Select Replicate('0',2 - DataLength(Convert(VarChar(2),DatePart(DAY, GetDate()))) + Convert(VarChar(2),DatePart(DAY, GetDate())
Far neater, he says after removing tongue from cheek.
Usually when you have to start doing this sort of thing in SQL, you need switch from can I, to should I.
SELECT RIGHT('0'
+ CONVERT(VARCHAR(2), Month( column_name )), 2)
FROM table
Might I suggest this user defined function if this what you are going for:
CREATE FUNCTION dbo.date_code (#my_date date) RETURNS INT
BEGIN;
DECLARE #retval int;
SELECT #retval = CAST(CAST(datepart(year,#my_date) AS nvarchar(4))
+ CONVERT(CHAR(2),#my_date, 101)
+ CONVERT(CHAR(2),#my_date, 103) AS int);
RETURN #retval;
END
go
To call it:
SELECT dbo.date_code(getdate())
It returns as of today
20211129
Roll your own method
This is a generic approach for left padding anything. The concept is to use REPLICATE to create a version which is nothing but the padded value. Then concatenate it with the actual value, using a isnull/coalesce call if the data is NULLable. You now have a string that is double the target size to exactly the target length or somewhere in between. Now simply sheer off the N right-most characters and you have a left padded string.
SELECT RIGHT(REPLICATE('0', 2) + CAST(DATEPART(DAY, '2012-12-09') AS varchar(2)), 2) AS leftpadded_day
Go native
The CONVERT function offers various methods for obtaining pre-formatted dates. Format 103 specifies dd which means leading zero preserved so all that one needs to do is slice out the first 2 characters.
SELECT CONVERT(char(2), CAST('2012-12-09' AS datetime), 103) AS convert_day
DECLARE #day CHAR(2)
SET #day = right('0'+ cast(day(getdate())as nvarchar(2)),2)
print #day
use
CONVERT(CHAR(2), DATE_COLUMN, 101)
to get the month part with 2 characters and
CONVERT(CHAR(2), DATE_COLUMN, 103)
for the day part.
Declare #dateToGet varchar(10)
Set #dateToGet = convert(varchar, getdate(), 112)
This works fine for the whole date with leading zeros in month and day
select
right('0000' + cast(datepart(year, GETDATE()) as varchar(4)), 4) + '-'+ +
right('00' + cast(datepart(month, GETDATE()) as varchar(2)), 2) + '-'+ +
right('00' + cast(datepart(day, getdate()) as varchar(2)), 2) as YearMonthDay

Date Format conversion in SQL

I want to convert date format from 01/09 to January 2009 , 09/03 to September 2003 etc. Is this possible in SQL? Please let me know if there is a API for the same.
if you have a DateTime column in your table, it's possible
SELECT DATENAME(MM, YOUR_DATE_COLUMN) + ' ' + CAST(YEAR(YOUR_DATE_COLUMN) AS VARCHAR(4)) AS [Month YYYY]
http://www.sql-server-helper.com/tips/date-formats.aspx
You should look here.
It's rather simple.
You should first convert it to a datetime. Then you can easily apply any formating when you read it later.
declare #d varchar(10);
set #d = '01/09'
select
--cast(#d as datetime) as d1, --syntax error converting char string
cast('20' + right(#d, 2) + '-' + left(#d, 2) + '-01' as datetime) as d2
then convert it to mmm yyyy using rm's answer
select datename(month, GETDATE()) + ' '+ substring(convert(varchar, GETDATE(), 100),8,4)