Extract month and day from a field in sql - sql

how do you select Month and day like in 'MMDD' format from a column, which has dates in '2014-01-12'(Datetime) format?

If your filed is a Date or DateTime, I would use the function DATEPART.
For example, this gets the current year:
DATEPART(year, GETDATE())
View the msdn page for the full documentation.
If your field is text, use CONVERT to convert your field to a DATE, then use the first method with the converted date as your value.
For example:
DATEPART(year, CONVERT(DATE, '11/1/2014'))
Complete Copy/Paste Example
DECLARE #DateVal VARCHAR(10) = '11/01/2014'
DECLARE #Month VARCHAR(2) = CAST(DATEPART(MONTH, CONVERT(DATE, #DateVal)) AS VARCHAR),
#Day VARCHAR(2) = CAST(DATEPART(DAY, CONVERT(DATE, #DateVal)) AS VARCHAR)
PRINT REPLICATE('0', 2 - LEN(#Month)) + #Month + REPLICATE('0', 2 - LEN(#Day)) + #Day

Related

How to get the last day of the month using only month and year?

I want to find out how to find the last day of the month if I only have a year and a month (and no day).
I tried using EOMONTH(), but this function needs the date consisted of year, month and day. I can only use year and month values.
How do I do something like this?
If you are using Sql Server 2012 then I'd use DATEFROMPARTS.
DECLARE #year SMALLINT = 2016
,#month TINYINT= 02
SELECT EOMONTH(DATEFROMPARTS(#year,#month,1))
You can still use EOMONTH even if you do not have a day of the month, just use the first of the month as the day of month is not significant in the input.
-- incoming parameters (assuming string but could be int and you could cast them)
DECLARE #month VARCHAR(2) = '11', #year VARCHAR(4) = '2016'
DECLARE #date DATETIME
DECLARE #lastDayOfMonth INT
SELECT #date = CONVERT(date, #year + #month + '01', 101) -- this first part is what you know (year + month), the 01 is just the first day of whatever month appended so the date is valid
-- get the last day of month as a date using EOMONTH and then use DATEPART to get the day of the month
SELECT #lastDayOfMonth = DATEPART(dd, EOMONTH(#date))
SELECT #lastDayOfMonth -- your output on the screen
VARCHAR TYPES
DECLARE #D DATE
DECLARE #YearV VARCHAR(4) = '2016'
DECLARE #MonthV VARCHAR(2) = '12'
SET #D = DATEADD(dd,-1,DATEADD(mm,1,CAST(#YearV + #MonthV + '01' AS DATE)))
SELECT #D
INT TYPES
DECLARE #D DATE
DECLARE #Year INT = '2016'
DECLARE #Month INT = '11'
SET #D = DATEADD(dd,-1,DATEADD(mm,1,CAST(CAST(#Year AS VARCHAR(4)) + CAST(#Month AS VARCHAR(2)) + '01' AS DATE)))
SELECT #D
COMBINED TYPES
some SUBSTRING code depending on the format... :)

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 to grab data from the last 13 months?

So I have this code, this is for grabbing data for the last 11 month of sale including the current month, make it a whole year. What do I have to do to change it to grabbing data for the last 12 months plus current month? I know I have to change something on the right(select period)... but not sure
In this one, the left function shows how to get the current year (2014 ) minus 1 to give 2013.. but I don't understand the right function, what does 2 mean?
Thanks
period <= (
SELECT Period
FROM dbo.FiscalDates
WHERE (Date = CONVERT(varchar(10), GETDATE(), 102))) and period >= (
convert(varchar, left((
SELECT Period
FROM dbo.FiscalDates
WHERE (Date = CONVERT(varchar(10), GETDATE(), 102))),4)-1)+'-'+
convert(varchar, right((
SELECT Period
FROM dbo.FiscalDates
WHERE (Date = CONVERT(varchar(10), GETDATE(), 102))),2)))
group by prodnum, period, WhseNum
Whoah buddy I think you may be overcomplicating things here. If you want to get data for the past X number of months then just use DATEADD it's a very useful function.
All you need to do then is
select
YourColumns
FROM YourTable
WHERE YourDate >= DATEADD(MONTH, -13, CAST(GETDATE() AS DATE))
and bam there you go.
DECLARE
#FormYear AS INT,
#FormMonth AS INT,
#ToYear AS INT,
#ToMonth AS INT,
#FromDate AS DATE,
#ToDate AS DATE
SET #FormYear=YEAR(DATEADD(DAY, -365, GETDATE()))
SET #FormMonth=MONTH(DATEADD(DAY, -365, GETDATE()))
SET #ToYear=YEAR(GETDATE())
SET #ToMonth=MONTH(GETDATE())
SET #FromDate= CAST(CAST(#FormMonth AS VARCHAR) +'-'+'01'+ '-' +CAST(#FormYear AS VARCHAR) AS DATE)
SET #ToDate= CAST(CAST(#ToMonth AS VARCHAR) +'-' + '01'+'-' + CAST(#ToYear AS VARCHAR) AS DATE)
After that, just select-
YourDateField Between #FormDate AND #ToDate

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

How to get month and year from the date

Using SQL Server 2000
Date like 20120101, 20120201, 20120301...
Fomat is yyyymmdd
I want to display month and year from the date like 01/2012, 02/2012, 03/2012...
Expected Output
01/2012
02/2012
03/2012
I don't want 1/2012, 2/2012, 3/2012...
Can any one give me a idea or query help....
You can use something like this:
DECLARE #input VARCHAR(20)
SET #input = '20120101'
-- convert the 20120101 to a DATETIME
DECLARE #thedate DATETIME
SELECT #thedate = CONVERT(DATETIME, #input, 112)
-- reformat that DATETIME to your needs
DECLARE #output VARCHAR(20)
SET #output = RIGHT('00' + CAST(DATEPART(MONTH, #thedate) AS VARCHAR(2)), 2) +
'/' + CAST(DATEPART(YEAR, #thedate) AS VARCHAR(4))
SELECT #output
You could "hide" this functionality into a user-defined function to make it more easily usable in your code:
CREATE FUNCTION dbo.MonthYearFromDate (#input VARCHAR(20))
RETURNS VARCHAR(20)
AS BEGIN
DECLARE #thedate DATETIME
SELECT #thedate = CONVERT(DATETIME, #input, 112)
DECLARE #output VARCHAR(20)
SET #output = RIGHT('00' + CAST(DATEPART(MONTH, #thedate) AS VARCHAR(2)), 2) + '/' + CAST(DATEPART(YEAR, #thedate) AS VARCHAR(4))
RETURN #output
END
and then you can call this like so:
SELECT dbo.MonthYearFromDate('20120515')
and get the output
05/2012
SELECT CAST(datepart(month,getdate()) AS CHAR) + '/' + CAST(datepart(year,getdate()) AS CHAR)
Instead of the function getdate() you need your date field.
have a look at the SUBSTRING function http://msdn.microsoft.com/en-us/library/ms187748.aspx
You should also consider storing your dates as a DATETIME (I assume you are using VARCHAR?)
Search on extract() function. It will solve your problem.