Date in MON-YYYY format to Text format - sql

How do I convert date format field to MON-YYYY format.
I have date 12-06-2014 and I want to compare it with JUN-2014.

Here is a link that explains everything about date format:
Date Format
Your solution is probably the following (MySQL version):
UPPER(DATE_FORMAT(yourDate, '%b-%Y'))
And for SQL Server:
UPPER(SUBSTRING(DATENAME(MONTH, yourDate), 1, 3) + '-' + CAST(DATEPART(YEAR, yourDate) AS VARCHAR(4)))
Hope this will help you

The SQL Server syntax is:
UPPER(FORMAT(yourDate, 'MMM-yyyy'))

SQL supports a number of different date formats, but does not support non-numeric based date formats. I would strongly suggest finding a method which uses one of these formats as suggested the Microsoft SQL documentation.
Alternatively, if it is absolutely necessary that you use this format, then the following code can change any date format into the format you have requested.
declare #date date = '2014-01-01'
select
case when DATEPART(mm,#date) = 1 then 'JAN'
when DATEPART(mm,#date) = 2 then 'FEB'
when DATEPART(mm,#date) = 3 then 'MAR'
when DATEPART(mm,#date) = 4 then 'APR'
when DATEPART(mm,#date) = 5 then 'MAY'
when DATEPART(mm,#date) = 6 then 'JUN'
when DATEPART(mm,#date) = 7 then 'JUL'
when DATEPART(mm,#date) = 8 then 'AUG'
when DATEPART(mm,#date) = 9 then 'SEP'
when DATEPART(mm,#date) = 10 then 'OCT'
when DATEPART(mm,#date) = 11 then 'NOV'
when DATEPART(mm,#date) = 12 then 'DEC' end
+ '-'
+ CONVERT(char(4),DATEPART(yy,#date)) as new_format

You could use something like the following to format the date and compare (SQL Fiddle):
SELECT *
FROM
(
SELECT
CONCAT(
CONVERT(CHAR(3), CONVERT(DATE, MyDateField, 105), 0),
'-',
DATEPART(YYYY, CONVERT(DATE, MyDateField, 105))
) AS DF
FROM MyTable
) m
WHERE m.DF = 'JUN-2014';

You can use below for convert date formate.
select left(datename(mm,[Date]),3)
+'-' + cast( DATEPART(YYYY,[date]) as nvarchar(50))
from ArtistCalendar

You can use the DATENAME() function to get the name for a given month, which can be abbreviated like so:
SELECT LEFT(DATENAME(mm, GETDATE()),3) -- Output: 'Sep'
You can append the year using:
SELECT YEAR(GETDATE())
This should have to be converted to a string value to enable comparison with your supplied value. So you can do this:
SELECT LEFT(DATENAME(mm, GETDATE()),3) + '-'
+ CAST(YEAR(GETDATE()) AS NVARCHAR(4)) AS InputDate -- Output: Sep-2014
To check equality of a supplied value, e.g. Sep-2014:
SELECT LEFT(DATENAME(mm, GETDATE()),3) + '-'
+ CAST(YEAR(GETDATE()) AS NVARCHAR(4)) AS InputDate,
GETDATE() as FullDate,
CASE WHEN LEFT(DATENAME(mm, getdate()),3) + '-'
+ CAST(YEAR(GETDATE()) as nvarchar(4)) = 'SEP-2014'
THEN 'True'
ELSE 'False'
END as Equality
Ouptut
InputDate FullDate Equality
----------------------------------------------
Sep-2014 2014-09-15 14:35:57.427 True
To use with your table:
DECLARE #compareDate AS NVARCHAR(10)
SET #compareDate = 'Jan-2014' -- set this
SELECT LEFT(DATENAME(mm, [YOUR_COL]),3) + '-'
+ CAST(YEAR([YOUR_COL]) AS NVARCHAR(4)) AS InputDate,
[YOUR_COL]as FullDate,
CASE WHEN LEFT(DATENAME(mm, [YOUR_COL]),3) + '-'
+ CAST(YEAR([YOUR_COL]) as nvarchar(4)) = #compareDate
THEN 'True'
ELSE 'False'
END as Equality
From [YOUR_TABLE]
Just replace [YOUR_COL] with your date column and [YOUR_TABLE] with the table that holds the data column.

In Oracle SQL
You can do something like this
TO_CHAR(column_name, 'MON-YYYY')

Related

Get 'Week Of' Date from Date

I have a field named 'AirDate' which is in mm/dd/yyyy format. I'd like to create a 'WeekOf' field which uses the AirDate field to give me the WeekOf date using Tuesday as the start of the week.
AirDate = 11/11/2019, WeekOf = 11/5/2019
AirDate = 11/12/2019, WeekOf = 11/12/2019
AirDate = 11/13/2019, WeekOf = 11/12/2019
etc.
What's the proper way to write the query to return the 'WeekOf' date in this format?
sql server you can use datefirst to set tuesday. See documentation
set datefirst 2
select wkTuesday = dateadd(dd, (-1)* (datepart(dw,'11/11/2019')-1), '11/11/2019')
set datefirst 7
Try this
and replace getdate() with the date that you want
SELECT dateadd(dd, (-1 * DATEPART(WEEKDAY, getdate())) + 1, getdate())
EDIT
declare #YourDate date = '19 NOv 2019'
declare #DayNo int
SET #DayNo = CASE WHEN DATEPART(WEEKDAY, #YourDate) < 3 THEN DATEPART(WEEKDAY, #YourDate) + 5 ELSE DATEPART(WEEKDAY, #YourDate) - 2 END
SELECT 'AirDate = ' + cast(#YourDate as varchar(100)) + ' , WeekOf = ' + cast( dateadd(dd, (-1 * #DayNo) + 1, #YourDate) as varchar(100))

Convert YYYYMM to MMMYY

I have a period 201604 (nvarchar). Is there a way that I can convert 201604 to APR16?
Use the DATENAME & SUBSTRING functions, like this:
declare #str nvarchar(50) = '201604'
select UPPER(left(datename(mm,cast(#str+'01' as date)),3))+substring(#str,3,2) --APR16
It is a bit ugly, but you can't use any of the built-in date formatting stuff as is. Feel free to swap out the case statement for a join if you have a month names table, etc.:
DECLARE #exampleVal NVARCHAR(6) = '201604';
SELECT CASE SUBSTRING(#exampleVal, 5, 2)
WHEN '01' THEN 'JAN'
WHEN '02' THEN 'FEB'
WHEN '03' THEN 'MAR'
WHEN '04' THEN 'APR'
WHEN '05' THEN 'MAY'
WHEN '06' THEN 'JUN'
WHEN '07' THEN 'JUL'
WHEN '08' THEN 'AUG'
WHEN '09' THEN 'SEP'
WHEN '10' THEN 'OCT'
WHEN '11' THEN 'NOV'
WHEN '12' THEN 'DEC'
END +
SUBSTRING(#exampleVal, 3, 2)
Try this:
Add '01' (as first day of month), so convert your varchar to datetime and get the datename of the month:
declare #myperiod nvarchar(10)
SET #myperiod = '201604'
SET #myperiod = #myperiod + '01'
SELECT UPPER(SUBSTRING(DATENAME(month, CONVERT(datetime, #myperiod)), 1, 3)) +
SUBSTRING(CONVERT(varchar, DATEPART(year, CONVERT(datetime, #myperiod))), 3, 4)
Add 01 at the last, so that it changes to a valid date format. Then use the datename function:
DECLARE #STRING VARCHAR(10)='201604'
SELECT DATENAME(MONTH,#STRING+'01') +' '+SUBSTRING(#STRING,3,2)
Output:
April 16
In two lines:
declare #napis varchar(6)='201506'
SELECT UPPER(LEFT(DATENAME(month, #napis+'01'),3)) + SubString(#napis,3,2)
Another option is by using Format() and DateFromParts(). This will work in SQL Server 2012 or newer versions:
Declare #Period NVarchar (6) = N'201604'
Declare #Format NVarchar (5) = N'MMMyy'
Select Upper(Format(DateFromParts(Left(#Period, 4), Right(#Period, 2), 1), #Format))
APR16
Use simple this
declare #test nvarchar(max) = '201604'
select left(DATENAME(month, #test +'01'),3) + SubString(#napis,3,2)
Another way:
DECLARE #Date varchar(6) = '201604'
SELECT REPLACE(SUBSTRING(CONVERT(char(9), CAST(#Date +'01' as Date), 6), 4, 7), ' ', '')
Try this one..
DECLARE #DATE NVARCHAR(6) = '201604'
SELECT datename(MONTH,CONVERT(DATE,CONVERT(DATE,LEFT(#DATE,4)+'.'+RIGHT(#DATE,2)+'.01',102),102))

Sql Datetime convert

In a database table, I have two column storing date and time in this format:
D30DAT D30TIM
140224 75700
I need update a new field where store date in the format
2014-02-24 07:57:00.000
How I can use a SQL query to do it?
For Postgres and Oracle (assuming those columns are varchar):
select to_timestamp(dt, 'yymmdd hh24miss')
from (
select d30dat||' '||case when length(d30tim) = 5 then '0'||d30tim else d30tim end as dt
from x
) t;
The case expression adds a leading 0 if the time part only consists of 5 digits so that the format mask can be specified with always 2 digits for the hour. The blank between the two columns is essentially only a debugging aid and could be left out.
The result is a real timestamp value that can easily be formatted using to_char() to the desired format.
SQLFiddle for Postgres: http://sqlfiddle.com/#!15/ac07a/2
SQLFiddle for Oracle: http://sqlfiddle.com/#!4/ac07a2/4
Try this function. Its not particularly fast or great, but converts the fields you specified.
CREATE FUNCTION GetDateTimeFromINT
(
#Date INT,
#Time INT
)
RETURNS DATETIME
AS
BEGIN
DECLARE #YearNo VARCHAR(4)
DECLARE #MonthNo VARCHAR(3)
DECLARE #DayNo VARCHAR(2)
DECLARE #HourNo VARCHAR(2)
DECLARE #MinNo VARCHAR(2)
DECLARE #SecNo VARCHAR(2)
SET #YearNo = LEFT(CONVERT(VARCHAR,#Date), LEN(#Date)-4)
SET #MonthNo = SUBSTRING(CONVERT(VARCHAR,#Date),LEN(#Date)-3,2)
SET #DayNo = SUBSTRING(CONVERT(VARCHAR,#Date),LEN(#Date)-1,2)
SET #HourNo = LEFT(CONVERT(VARCHAR,#Time), LEN(#Time)-4)
SET #MinNo = SUBSTRING(CONVERT(VARCHAR,#Time),LEN(#Time)-3,2)
SET #SecNo = SUBSTRING(CONVERT(VARCHAR,#Time),LEN(#Time)-1,2)
SET #YearNo = '20' + #YearNo
IF LEN(#HourNo) = 1
BEGIN
SET #HourNo = '0' + #HourNo
END
SET #MonthNo = CASE
WHEN #MonthNo = '01' THEN 'JAN'
WHEN #MonthNo = '02' THEN 'FEB'
WHEN #MonthNo = '03' THEN 'MAR'
WHEN #MonthNo = '04' THEN 'APR'
WHEN #MonthNo = '05' THEN 'MAY'
WHEN #MonthNo = '06' THEN 'JUN'
WHEN #MonthNo = '07' THEN 'JUL'
WHEN #MonthNo = '08' THEN 'AUG'
WHEN #MonthNo = '09' THEN 'SEP'
WHEN #MonthNo = '10' THEN 'OCT'
WHEN #MonthNo = '11' THEN 'NOV'
WHEN #MonthNo = '12' THEN 'DEC'
END
RETURN CONVERT(DATETIME, #DayNo + '-' + #MonthNo + '-' + #YearNo +' ' + #HourNo + ':' + #MinNo + ':' + #SecNo)
END
GO
Call it like so:
SELECT *, dbo.GetDateTimeFromINT(D30DAT,T30DAT) OutputDT
FROM SourceTable
If you need help with the update statement, let me know
Because someone gave a convoluted answer in SQL Server, I want to point out that there is a much simpler way.
I also want to point out that the format is not unreasonable. It provides easy access to the date parts and it is sortable. Of course, a real date/time value has these properties as well; I am guessing that this is some legacy format from some ancient system.
In any case, try this:
with t as (select 140224 as ymd, 75700 as hms)
select cast(cast(ymd as varchar(255)) + ' ' +
stuff(stuff(right('000000' + cast(hms as varchar(255)), 6
), 3, 0, ':'
), 6, 0, ':')
from t;
This turns the numbers into the format YYMMDD HH:MM:SS which SQL Server recognizes as a date/time value. Actually it would be better to pre-pend "20" for the four-digit year, but I'm not sure what the OP wants in terms of Y2K convertibility.
Although the code would look a bit different, similar logic would work in most databases.

how to get nth date of each month for an year

How to get the nth date of each month if "sunday" then that next Immediate date n+1 for a year.
for example :
Year=2014
nth value = 2(2nd of each month)
Date:
2014-01-02
2014-02-03 (since 02 is "Sunday" next Immediate date)
2014-03-03 (since 02 is "Sunday" next Immediate date)
2014-04-02
2014-05-02
2014-06-02
2014-07-02
and so on...
how about this, fiddle here
Will work with day values between '01' and '28', I've left parameter checking and conversion to the OP.
DECLARE #Year = Char(4);
DECLARE #Day = VarChar(2);
SET #Year = '2014';
SET #Day = '2';
SELECT
CASE DATENAME(dw, [Date])
WHEN 'Sunday' THEN DATEADD(d, 1, [Date])
ELSE [Date]
END [Date]
FROM (
SELECT
CAST(#Year + '-' + [M] + '-' + #Day AS DATETIME) [Date]
FROM (
SELECT '1' [M] UNION ALL
SELECT '2' UNION ALL
SELECT '3' UNION ALL
SELECT '4' UNION ALL
SELECT '5' UNION ALL
SELECT '6' UNION ALL
SELECT '7' UNION ALL
SELECT '8' UNION ALL
SELECT '9' UNION ALL
SELECT '10' UNION ALL
SELECT '11' UNION ALL
SELECT '12') [Months]) [RawDays];
This worked for me...!
Declare #Tracker int
set #Tracker = 2
Declare #FromDate datetime
Declare #ToDate datetime
set #FromDate = '2014-01-01'
set #ToDate = '2014-12-31'
Declare #TrackerTable Table ( Date Datetime)
;with DateDifference As
(
SELECT #FromDate DateValue
UNION ALL
SELECT DateValue + 1
FROM DateDifference
WHERE DateValue + 1 < #ToDate
)
Insert into #TrackerTable
Select
Case
when datename(dw,DateValue) = 'Sunday' Then DateValue + 1
Else DateValue
End as Date
from DateDifference where Day(DateValue) = #Tracker
OPTION (MAXRECURSION 0)
Select * from #TrackerTable

SQL Server 2008 select data only between month and year

I would like select data between two date, without day
An input example:
start month: 9 , start year: 2011
end month: 3, end year: 2012
I think that there are two way to do this.
The first is convert start month and start year to date like 2011-09-01 and convert last date to 2012-03-31, but this requires calculation of the last day of end month. Obtained these date we can use a BEETWEN function for the WHERE clause (but, is the CONVERT function reliable?)
The second solution is to use the DATEPART function like in the following code:
I try to explain: if end year is equal to the initial year, then month must be between the start and end months; else if the final months is greater than the initial years if different from the initial and final year, I take everything in between; else if the final year, the month must be less than or equal to the final month, if the initial year, month must be greater than or equal to the final month
Can you help me do this in the best way? Is correct, the solution I adopted?
declare #IndDebitoCredito bit,#ProgTributo int,#mi as integer,#ai as integer,#mf as integer,#af as integer,#IDAnagrafica varchar(5)
select #mi = 01,#ai = 2011,#mf = 12,#af = 2011,#IDAnagrafica = 'DELEL',#IndDebitoCredito = 1
select distinct rrd.IDTributo
from TBWH_Delega d
--inner join TBWH_SezioneDelega sd on d.IDDelega = sd.IDDelega
inner join TBWH_Rigo rd on rd.IDDelega = d.IDDelega
inner join TBWH_RataRigo rrd on rrd.IDRigo = rd.IDRigo
where
(
DATEPART(MM,d.DataDelega)<=#mf and
DATEPART(MM,d.DataDelega)>=#mi and
DATEPART(YYYY,d.DataDelega)=#ai and
#af = #ai
)
OR
(
--anno finale magg. anno iniziale
#af > #ai AND
(
( -- delega nell'intervallo
DATEPART(YYYY,d.DataDelega)<#af AND
DATEPART(YYYY,d.DataDelega)>#ai
-- DATEPART(MM,d.DataDelega)>=#mi
)
OR
( -- delega limite destro
DATEPART(YYYY,d.DataDelega)=#af AND
DATEPART(MM,d.DataDelega)<=#mf
)
OR
( -- delega limite sinistro
DATEPART(YYYY,d.DataDelega)=#ai AND
DATEPART(MM,d.DataDelega)>=#mi
)
)
)
GO
Your first solution is almost there, but is more complicated than it needs to be and won't work anyway. It will miss out any rows from the last day of the end month.
You can add one month to the end month and then use BETWEEN on the first of each month. eg.
start month: 9 , start year: 2011
end month: 3, end year: 2012
BETWEEN '2011-09-01' AND '2012-04-01'
or, as JNK points out, this will be better:
DataDelega >= '2011-09-01' AND DataDelega < '2012-04-01'
You'll need to add in some logic to deal with the end month being December, but this looks like the simplest way of doing it.
You are WAY overcomplicating this. You really only need two comparisons:
Is the month and year after or equal to the initial value?
Is the month and year before or equal to the final value?
Try:
SELECT *
FROM MyTable
WHERE Datefield BETWEEN
CAST(#mi as varchar) + '/1/' + CAST(#ai as varchar)
-- first of first month
AND
DATEADD(DAY, -1, (DATEADD(Month, + 1, (CAST(#mf as varchar) + '/1/' + CAST(#af as varchar)))))
-- Last day or final month
SELECT *
FROM Table
WHERE DateField
BETWEEN CONVERT(DATE, CONVERT(CHAR(4), #ai) + RIGHT('00' + CONVERT(VARCHAR(2), #mi), 2) + '01', 112)
AND DATEADD(DD, -1, DATEADD(MM, 1, CONVERT(DATE, CONVERT(CHAR(4), #af) + RIGHT('00' + CONVERT(VARCHAR(2), #mf), 2) + '01', 112)))
Avoid using expressions on the DateField columns, as it makes query not SARGable.
I would use:
WHERE DateToCheck >= --- first day of StartMonth
DATEADD( mm, #StartMonth-1,
DATEADD( yy, #StartYear-2000, '2000-01-01')
)
AND DateToCheck < --- first day of next month (after EndMonth)
DATEADD( mm, #EndMonth,
DATEADD( yy, #EndYear-2000, '2000-01-01')
)
DECLARE #mi INT
, #ai INT
, #mf INT
, #af INT
SELECT #mi = 01
, #ai = 2011
, #mf = 12
, #af = 2011
--local variables to hold dates
DECLARE #i DATETIME
, #f DATETIME
--build strings to represent dates in YYYYMMDD format
--add a month to the #f date
SELECT #i = CONVERT(VARCHAR(4), #ai) + RIGHT('0' + CONVERT(VARCHAR(2), #mi),
2) + '01'
, #f = DATEADD(month, 1,
CONVERT(VARCHAR(4), #af) + RIGHT('0'
+ CONVERT(VARCHAR(2), #mf),
2) + '01')
--select data where date >= #i, and < #f
SELECT *
FROM MyTable
WHERE DateField >= #i
AND DateField < #f