SQL Server query to get previous month name in string from another month in string - sql

I need to get previous month name from given month name.
For example I need to get previous month as May for the given month June.
There is no date.
I tried select CAST(Monthname-1 AS Varchar(max)) from table

Because "There is no date."
You can convert an augmented string {month name} + ' 01, 1980' to a date, and then perform the date calculation
Example
Select datename(MONTH,dateadd(MONTH,-1,convert(date,'June'+' 01,1980')))
If 2012+ and potentially bogus data ... try_convert()
Select datename(MONTH,dateadd(MONTH,-1,try_convert(date,'June'+' 01,1980')))
Returns
May

Add -1 months to your starting date, then use DATENAME(month) to get its name.
DATENAME(month, DATEADD(month, -1, <yourDateField>))

You can try this:
SELECT DATENAME(MM,CAST('1 June 2018' AS datetime)-1)

Related

Get first day of first month of previous year in yyyy-mm-dd format

How do I get the first day of the first month of previous year in yyyy-mm-dd format? ie. 2019-01-01.
This is the code I have tried:
SELECT DATEADD(yy,-1,DATEADD(yy,DATEDIFF(yy,0,GETDATE()),0))
You can use DATEFROMPARTS() function in SQL Server for creating date from given year, month and date in integer as shown below. To get the previous year you can use Year() function and subtract 1 from that. First date and month is always 1 so it has been hard-coded here.
declare #IntYear int = Year(Getdate()) - 1 --Previous Year
Select datefromparts(#Intyear, 1, 1)
The output in SSMS is as shown below.
To get the output in the different format you can follow this link.
You seem to be looking to generate a string, not a date. Consider using date functions and string concatenation: you just need to substract 1 year from the current date, and then append '-01-01'
concat_ws('-', year(getdate()) - 1, '01', '01')
Demo on DB Fiddle
You basically have it. You just need the FORMAT function.
SELECT FORMAT (DATEADD(yy,-1,DATEADD(yy,DATEDIFF(yy,0,GETDATE()),0)), 'yyyy-MM-dd') as date

Hardcode a specific day in data time while pulling the data - SQL

Actually I have different date in SQL table when I pull those via SQL query, day of datetime field should have fixed day.
Example: (DD-MM-YYYY) day should be "7" > (7-MM-YYYY)
10-08-2007 > 07-08-2007
27-12-2013 > 07-12-2013
01-03-2017 > 07-03-2017
Can someone help me on this. Thanks in Advance.
Find the difference between 7 and the day of the original date and add that to the original date:
SELECT DATEADD(DAY, 7 - DAY(OriginalDate), OriginalDate)
Use DATEPART to take out the month and year parts. Cast those into varchar and concatenate with 07.
Query
select '07-' +
cast(DATEPART(mm, [date_column]) as varchar(2)) + '-' +
cast(DATEPART(yyyy, [date_column]) as varchar(4))
from your_table_name;
Assuming You might have to change the day number example
DECLARE #dayNum char(2)
SELECT #dayNum = '07'
select #dayNum + Right(convert(char(10),getdate(),105),8)
If that is not the case You could do this
select '07'+ Right(convert(char(10),'10-08-2007',105),8)
I'd go this way:
SELECT CONVERT(DATE,CONVERT(VARCHAR(6),GETDATE(),112)+'25',112);
CONVERT with format 112 will return the date as unseparated ISO (today we would get 20170407). Convert this to VARCHAR(6) will implicitly cut away the day's part (201704).
Now we add a day and use again CONVERT with 112, but now with DATE as target type.
One thing to keep in mind: The day you add must be two-digit. You can achieve this with
DECLARE #int INT=7;
SELECT REPLACE(STR(#int,2),' ','0');
Use DATEFROMPARTS: Updated ONLY works from 2012 - OP has tagged SQL-Server 2008
select DATEFROMPARTS ( year('10-08-2007'), month('10-08-2007'), 7 )
Assuming that your field is of datetime datatype and your fixed day is of integer type.
select datetimecolumn+(yourparamfixedday-datepart(dd,datetimecolumn))

Date Manipulation in SQL

I tried different functions to convert Datepart for year, month and day to a date but I am getting errors.
This is what I tried:
SELECT
CONVERT(datetime, CHAR(YEAR(GETDATE()) + CHAR(DATEPART(MM, '02')) + CHAR(DATEPART(DD, '28')));
When running this code, I get an error:
Conversion failed when converting date and/or time from character string.
In case I remove those single quotes on 02 and 28 then SQL will return null.
Thanks in advance
If 2012+ you could also try DateFromParts()
Select DateFromParts(2016,2,28)
Returns
2016-02-28
Try this instead:
SELECT CONVERT(datetime, DATENAME(YEAR, GETDATE()) + '-02-28')
You can't extract a day or month from a string such as '02'. But there is no need to do that anyway.
As you can read in the documentation on DATEPART, the second parameter should be a date parameter:
Returns an integer that represents the specified datepart of the specified date.
In your SQL statement you are misusing this function twice... following are invalid because the second parameter cannot be converted to a date type:
DATEPART(MM,'02')
DATEPART(DD,'28')
You can construct a date from its parts using the DATEFROMPARTS function in SQL Server 2012 and later versions:
Returns a date value for the specified year, month, and day.
Or if you need the time parts filled in as well, DATETIMEFROMPARTS
Returns a datetime value for the specified date and time.
In versions prior to SQL Server 2012, this can be done like this:
DATEADD(MM, (#year - 1900) * 12 + #month - 1 , #day - 1);

Date Conversion in SQL

I have a date in following format in my DB.
10/16 - mm/yy
I need to convert it to:
October/16
Is this possible?
If it's not possible then please tell me why.
This is not a date, it's missing the day, it's a bad way to store year/month. There should be a 4 digit year to avoid confusion and the year should be listed first to enable correct sorting, e.g. '2016/10' or a numeric value 201610.
You can cast it to a DATE first and then use a FORMAT to disply only month/year:
set dateformat myd;
select format(cast(mystupidcolumn + '/1' as date), 'MMMM/yy')
Or SUBSTR the month part and use a CASE.
try this format,
SELECT DATENAME(month, DATEADD(month, #mydate-1, CAST('2008-01-01' AS datetime)))
You can display date by using this code
select datename(month, YourColumnName) + '/' + right(YEAR(YourColumnName),2)
FROM yourTableName
Simply change yourColumnName with name of your table column and yourTableName with name of table.
Yes you can, and it depend in what database you use to call date functions
If you column Datetime format
SQL server DATENAME(Month, GETDATE())
MySQL database MONTHNAME(now())
otherwise
convert it will in your choice at database or you code logic
split the value and lookup at month enum or fake the date to be accepted and complete date format like 01/10/16
so do something like SELECT DATENAME(Month, datecolumn) + '/' + YEAR (datecolumn)
also you can use instead of Year function DATEPART(yy,datecolumn)
the way you do it with format will look like
CONVERT(VARCHAR(11),GETDATE(),106)
but excepted to get first 3 char of month JUN

Function get the last day of month in sql

I need to get the last day of month with input of month and year. For example, with input 06/2016 it will return 30. I use SQL Server 2005. Thanks for any help.
Suppose your input is VARCHAR in the form of MM/YYYY.
Use RIGHT and LEFT to get the year and month respectively. Then use DATEFROMPARTS to generate the starting date. Next, use EOMONTH to get the last day of the month. Finally use DAY to extract the day part.
DECLARE #input VARCHAR(7) = '06/2016'
SELECT
DAY(
EOMONTH(
DATEFROMPARTS(CAST(RIGHT(#input,4) AS INT),CAST(LEFT(#input, 2) AS INT),1)
)
)
The above only works for SQL Server 2012+.
For SQL Server 2005, you can use DATEADD to generate the dates:
SELECT
DAY( -- Day part
DATEADD(DAY, -1, -- Last day of the month
DATEADD(MONTH, CAST(LEFT(#input, 2) AS INT), -- Start of next month
DATEADD(YEAR, CAST(RIGHT(#input, 4) AS INT) - 1900, 0) -- Start of the year
)
)
)
Reference:
Some Common Date Routines
You would do something like this:
select eomonth(getdate(), 0);
If you want it formatted as MM/YYYY then you'd do this:
select format(eomonth(getdate(), 0), 'MM/yyyy');
Pardon me for tossing-in a response that is not specific to "SQL Server," nor thence to "2005," but the generalized way to compute the answer that you seek is as follows:
Break down the input that you have, e.g. 06/2016, into two parts. Call 'em #MONTH and #YEAR. Define a third value, #DAY, equal to 1.
Typecast this into a date-value ... "June 1, 2016."
Now, using the date-handling functions that you're sure to have, "first add one month, then subtract one day."
One thing that you must be very careful of, when designing code like this, is to be certain(!) that your code for decoding 06/2016 works for every(!) value that actually occurs in that database, or that it can be relied upon to fail.
try this,
declare #input varchar(20)='06/2016'
set #input=#input+'/01'
declare #dtinput datetime=#input
select dateadd(day,-1,dateadd(month,datediff(month,0,#dtinput)+1,0))
--OR in sql server 2012
select eomonth(#dtinput)