Get year and month from SQL - sql

I want to know how can I get the year and month into my database. For example, suppose it’s August, 2011. The output that I need is like this: CAB 11 08 001 (CAB + YEAR + MONTH + CURRENT NO. in tracking number. )
This is my SQL:
ALTER PROCEDURE [dbo].[generateTrackNo] AS
Declare #tempYear VARCHAR(5),#tempMonth VARCHAR(5)
Set #tempYear = Year(GetDate())
Set #tempMonth = Month(GetDate())
SELECT 'CAB' + Right(Cast(Year(GetDate()) as varchar(10)),2)+ Right(Cast(Month(GetDate()) as varchar(10)),2) + Right('000000'+ Cast(CurrentNo as varchar(10)), 5) from tblTrackNo where GenYear = #tempYear
--UPDATE tblTrackNo SET CurrentNo = CurrentNo + 1 where GenYear = #tempYear
The output for this is CAB1180035, but I need CAB1108035. I need to put zero(0) 08 like this for the month.
In my table I have only genYear and Current No. Do I need to add another column for MONTH?

It looks like you're making separate columns for YEAR, MONTH, etc.
Most (all?) DBMSs I'm aware of have a Date type. Use it. They put a lot of useful stuff in it, like accepting date inputs in different formats and giving them as output in pretty much any format you can think of.
For example, if you have a DT column of type Date in Oracle, you can output month as
SELECT TO_CHAR(DT, "MM") FROM MYTABLE;
and the month will always be displayed as 2 digits (01, 02, ... 12)

SELECT
'CAB'
+ RIGHT(YEAR(GetDate()),2)
+ RIGHT('0' + CONVERT(VARCHAR, MONTH(GetDate())),2)
+ Right('00000' + Cast(CurrentNo as varchar(10)), 5)
That might work..

Using your method \ logic..
Right('0' + Cast(Month(GetDate()) as varchar(10)),2)

Related

3 Letter Month Abbreviation to Date

I have a list of months formatted with the 3 letter abbreviation followed by the last 2 numbers of the year.
For example, this current month would be SEP22. I need to find a way to turn this from a varchar into a date/datetime value, pointing to the first day of the month.
So, if I have 'SEP22', I need to get the output of September 1st, 2022 as a date/datetime object.
I can find a lot of data on turning the datetime value or numeric month into the abbreviation, but not the other way around.
I know I can make a giant case statement, but I was wondering if there's an easier method to read this type of data.
Any and all help is appreciated.
EDIT: I know the data is in the current century, I know where the data comes from and when it started being collected, all of this data has been collected in or after August 2013 (AUG13).
Try this:
SELECT
CAST(
LEFT(StringDate, 3) -- e.g. SEP
+' 1 20' -- assumes 21st century
+ RIGHT(StringDate, 2) -- e.g. 22
AS DATE
) AS ActualDate
;
For SQL Server:
convert(date, '01 ' + LEFT('SEP22', 3) + ' ' + RIGHT('SEP22', 2), 6)
When SQL Server converts the date from a string with a 2-digit year, the cutoff is at 50:
declare #myMonth table (
mo varchar(5)
)
declare #i int = 0
while #i < 100
begin
set #i = #i + 1
insert #myMonth
values ('SEP' + RIGHT('0' + CAST(#i AS VARCHAR(5)), 2))
end
SELECT mo
, convert(date, '01 ' + LEFT(mo, 3) + ' ' + RIGHT(mo, 2), 6)
FROM #myMonth
For Oracle:
TO_DATE('01' || 'SEP22', 'DDMONYY')
For Oracle, all of the dates are after 2000:
CREATE TABLE MYMONTH (
MO VARCHAR2(6) NOT NULL
)
;
INSERT INTO MYMONTH (MO)
SELECT 'SEP' || SUBSTR('0' || CAST(N AS VARCHAR2(5)), -2)
FROM (
SELECT (0 + ROWNUM) N
FROM DUAL CONNECT BY ROWNUM <= 100
)
;
SELECT MO
, TO_CHAR(TO_DATE('01' || MO, 'DDMONYY'), 'MM/DD/YYYY')
FROM MYMONTH
;

SQL Server sort by date

I have a table of transactions in SQL Server 2016 with a column called mthweekyr where each row in this column has as a string, the month number, week number of the month, and year of the transaction, where week number is determined by day of the month / 7.
For example, if the transaction date was: 2018-09-28, this would appear as 9-4-2018.
The problem is that the original transaction date column is not actually in the table, and I would like to sort these transactions by the mthweekyr column, but am unable to do so because this column is not a date type, it is a string type. (I don't make the tables, I just use them!)
Any suggestions on how to proceed?
Thanks.
Here's another way...
declare #table table(mthweekyr varchar(10))
insert into #table
values
('9-4-2018'),
('8-4-2018'),
('9-5-2018'),
('7-5-2018'),
('7-4-2018'),
('9-5-2017'),
('9-4-2017')
select *
from #table
order by
cast(right(mthweekyr,4) as int) --order by year first
,cast(left(mthweekyr,charindex('-',mthweekyr)-1) as int) --order by month. Works for single or double digit months
,left(right(mthweekyr,6),1) --order by week number which is always a single digit, since it's the week number of the month not the year.
Late answer, but perhaps a thinner alternative.
You can simply use the implicit conversion of m-d-y to date
Example
declare #table table(mthweekyr varchar(10))
insert into #table
values
('9-4-2018'),
('8-4-2018'),
('9-5-2018'),
('7-5-2018'),
('7-4-2018'),
('9-5-2017'),
('9-4-2017'),
('10-4-2017'), -- added 2 digit month
('10-5-2017') -- added 2 digit month
Select *
From #table
Order By convert(date,mthweekyr)
Returns
mthweekyr
9-4-2017
9-5-2017
10-4-2017
10-5-2017
7-4-2018
7-5-2018
8-4-2018
9-4-2018
9-5-2018
Using JNevill's suggestion you could leverage PARSENAME for this.
declare #Date varchar(20) = '9-4-2018'
select PARSENAME(replace(#Date, '-', '.'), 1) + '-' + right('00' + PARSENAME(replace(#Date, '-', '.'), 3), 2) + '-' + right('00' + PARSENAME(replace(#Date, '-', '.'), 2), 2)
This returns 2018-09-04
You could also do some string manipulation but that starts to get rather tedious.
obviously not the most efficient I'm sure but to brute force it...
order by substring(#theStr, len(#theStr) - 4 + 1, 4)
+ substring(#thestr, charindex('-',#Thestr)+1,1)
+ right('00' + substring(#thestr, 1, charindex('-',#Thestr)-1),2)
here's how to get there by pieces:
declare #thestr varchar(255) = '9-4-2018'
Declare #SortStr as Varchar(255)
--year
Select #SortStr = substring(#theStr, len(#theStr) - 4 + 1, 4)
print #Sortstr
--day
Select #SortStr = right('00' + substring(#thestr, 1, charindex('-',#Thestr)-1),2)
print #sortStr
--week
Select #SortStr = substring(#thestr, charindex('-',#Thestr)+1,1)
print #sortStr
Select #SortStr = substring(#theStr, len(#theStr) - 4 + 1, 4)
+ substring(#thestr, charindex('-',#Thestr)+1,1)
+ right('00' + substring(#thestr, 1, charindex('-',#Thestr)-1),2)
will yield this output
2018
09
4
2018409
Since you know what the algorithm for date hashing is you can restore the original dates into a new column and then sort on it. Something like:
SELECT *, CONVERT(datetime2(1),
RIGHT(#mthweekyr, 4) + '-' +
LEFT(#mthweekyr, CHARINDEX('-', #mthweekyr) - 1) + '-' +
SUBSTRING(#mthweekyr, CHARINDEX('-', #mthweekyr) + 1,
CHARINDEX('-', #mthweekyr, CHARINDEX('-', #mthweekyr) + 1)
- CHARINDEX('-', #mthweekyr) - 1)) AS EstimatedDate
FROM theTable
ORDER BY EstimatedDate
UPDATE
So the above is the long, harder way.
A smarter approach would be to leave the heavy lifting to the SQL Engine and use the third parameter of the CONVERT function, which specifies the style of the input. As the mthweekyr basically represents a USA style of mm-d-yyyy, the query will look like:
SELECT *, CONVERT(datetime2(1), mthweekyr, 110) AS EstimatedDate
FROM theTable
ORDER BY EstimateDate

merge two column with date format

I need merge two column to date format
input
month year
---- ----
7 2013
The result should be come date format like this (DD/MM/YYYY) :
New_Date
--------
01/07/2013
You can use for example this:
select convert(date, '01/' + convert(varchar(2), month) + '/' + convert(varchar(4), year), 101)
The output of your data is depended on the collation, not how you store it.
To get the date, try this:
SELECT DATEFROMPARTS(year, month, 1);
Check This: Suppose you have variable declaration as below and you can get the desired output in desired form by using CONVERT
DECLARE #year INT = '2017', #month INT = '7'
SELECT CONVERT(VARCHAR(10),DATEFROMPARTS(#year, #month, 1), 103) AS [DD/MM/YYYY]
OUTPUT:
DD/MM/YYYY
01/07/2017
You have so many date format which you can use to get output in various format please check this http://www.sql-server-helper.com/sql-server-2008/sql-server-2008-date-format.aspx
Try below code :
SELECT RIGHT('00'+CAST('1' AS VARCHAR(2)),2) + '/' + RIGHT('00'+CAST('7' AS
VARCHAR(2)),2) + '/' + CAST('2013' AS VARCHAR(4))

select year(getdate() -2) and month as 12

my source table column is ReportingPeriod Nvarchar(6)
delete query has to be for datas before 2 years.
this query does not work
delete from table where ReportingPeriod < year(getdate() -2) and month as 12
I need to get 201212 as result
the criteria is current year -2 and month is 12
in 2014 expected result is 201212
in 2015 expected result is 201312
I would do all of the date maths first keeping things as datetime and then convert to nvarchar at the end. Handily, CONVERT will just truncate the result if not enough space is provided, so we just provide space for the year and month and we get what we want:
select CONVERT(nvarchar(6),
DATEADD(year,DATEDIFF(year,'20010101',CURRENT_TIMESTAMP)
,'19991201')
,112)
Result:
201212
This works because we exploit the relationship between two arbitrary dates - for instance, for any date in 2001, the result we would want would be a date in december 1999 - so that's what I've used.
It's true that the above may look overly complex for this requirement, but it's possible to make a great many problems fit the DATEADD/DATEDIFF pattern with the appropriate choice of the period to use and the two arbitrary dates and the relationship between them.
You could try something like
SELECT FROM <YOUR_TABLE>
WHERE ReportingPeriod < Convert(nvarchar(4), year(getdate()) - 2) + '12'
You could cast your ReportingPeriod to a date, so 201212 would become 2012-12-01 as I assume you aren't concerned with the day of the month.
cast(left(ReportingPeriod,4) + '-'
+ RIGHT(ReportingPeriod, 2) + '-01' as datetime)
Then take the current year -2 from GETDATE() and append the month 12 and day 31 to compare these values against, which would return 2012-12-31.
cast(cast(
cast(year(getdate()) -2 as nvarchar(4))
+ '-12-31' as nvarchar(10)) as datetime)
So combining these you should be able to select all records older than 2 years, based on the month being set to 12.
select cast(left(ReportingPeriod,4) + '-'
+ RIGHT(ReportingPeriod, 2) + '-01' as datetime) ReportPeriodDate
from [YourTable]
where cast(left(ReportingPeriod,4) + '-'
+ RIGHT(ReportingPeriod, 2) + '-01' as datetime)
<= cast(cast(
cast(year(getdate()) -2 as nvarchar(4))
+ '-12-31' as nvarchar(10)) as datetime)
Then you just need to delete with this logic.
delete [YourTable]
where cast(left(ReportingPeriod,4) + '-'
+ RIGHT(ReportingPeriod, 2) + '-01' as datetime)
<= cast(cast(
cast(year(getdate()) -2 as nvarchar(4))
+ '-12-31' as nvarchar(10)) as datetime)
Demo SQL Fiddle

SQL view to select the last 3 months of payroll data

I have a view that I want to use to generate a payroll report.
I want it such that it selects/gets the last 3 months of monthly processed data.
E.g. If today is 15th May 2012 and payroll for May has not been done, I want to get the results for April, March and February only.
My query:
SELECT dbo.[#EIM_PROCESS_DATA].U_Tax_year, dbo.[#EIM_PROCESS_DATA].U_Employee_ID, SUM(dbo.[#EIM_PROCESS_DATA].U_Amount) AS PAYE,
dbo.OADM.CompnyName, dbo.OADM.CompnyAddr, dbo.OADM.TaxIdNum, dbo.OHEM.lastName + ', ' + ISNULL(dbo.OHEM.middleName, '')
+ ' ' + ISNULL(dbo.OHEM.firstName, '') AS EmployeeName, dbo.OHEM.govID, dbo.[#EIM_PROCESS_DATA].U_Process_month
FROM dbo.[#EIM_PROCESS_DATA] INNER JOIN
dbo.OHEM ON dbo.[#EIM_PROCESS_DATA].U_Employee_ID = dbo.OHEM.empID CROSS JOIN
dbo.OADM
WHERE (dbo.[#EIM_PROCESS_DATA].U_PD_code = 'SYS033')
GROUP BY dbo.[#EIM_PROCESS_DATA].U_Tax_year, dbo.[#EIM_PROCESS_DATA].U_Employee_ID, dbo.OADM.CompnyName, dbo.OADM.CompnyAddr, dbo.OADM.TaxIdNum,
dbo.OHEM.lastName, dbo.OHEM.firstName, dbo.OHEM.middleName, dbo.OHEM.govID, dbo.[#EIM_PROCESS_DATA].U_Process_month
The field U_Process_Month stores the name of the months of the year (varchar). Any help?
Here is one option if you want to turn a month name into a datetime:
declare #Month varchar(10) = 'DEC'
declare #Year varchar(4) = '2012'
SELECT CAST(#Month ' ' + #Year AS DATETIME) AS KeyDate
Replace the #Month and #Year variables with your field names, and you have the first step ;-)
For selecting only the last three months, try the HAVING clause, together with a variable #MaxKeydate that indicates the last processed month:
SELECT (...) FROM bla
HAVING KeyDate > DATEADD(month, -3, #MaxKeyDate)
You need to see yourself, if you can determine the value for #MaxKeyDate with a simple
SELECT MAX(CAST(#Month ' ' + #Year AS DATETIME)) FROM bla
or if it is more complicated.