Get the 2 digit year in T-SQL - sql

I need to get the current 2 digit year and increment by one. So the current number I'm looking for should be 11. How?

You can do ( YEAR( GETDATE() ) % 100 ) + 1
See GETDATE & YEAR

This will work for you
select Right(Year(getDate())+ 1,2)

For SQL Server 2012 and above, I'd suggest using FORMAT(#DATE, 'yy'):
SELECT FORMAT(DATEADD(year, 1, GETDATE()), 'yy')
Format offers a cleaner, more readable solution. Thus, less guesswork, and a better maintainability.

SELECT RIGHT(CONVERT(VARCHAR(8), GETDATE(), 1),2) as YEAR

You can try this in sql server
SELECT FORMAT(GETDATE(), 'yy')

If you are always going to be using GetDate() why not just do something like this:
Select (Year(GetDate()) - 2000) + 1
Dang people. Always making things so complicated. It's not like you are going to be living for another 1000 years!

select CAST( DAY(GETDATE()) as varchar(10))+'/'+CAST( month(GETDATE()) as varchar(10))+'/' +cast(right(year(getDate()),2) as varchar)

Related

SQL Convert dd/mm/yy to yymmdd

I have been trying to achieve this all day, I have followed numerous tutorials and can't seem to crack it, I have been trying things like:
select CONVERT(VARCHAR(10), DATE, 131) from Table
yet it does not seem to change anything.
Any advice or help would be appreciated. Thankyou in advance.
SELECT CONVERT(VARCHAR(10), DATE, 12)
12 is the right code for the format you want. See: https://msdn.microsoft.com/en-GB/library/ms187928.aspx
Try this
declare #TDATE Date = '2015-11-10';
select Convert(varchar,Datepart(Year, #TDATE))+Convert(varchar,Datepart(Month, #TDATE))+Convert(varchar,Datepart(Day, #TDATE))
Output:
20151110
12 is the right code. Use below query to get output as 'yymmdd'
select CONVERT(VARCHAR(10), DATE, 12) from Table
On PostgreSQL the easiest way is to use to_char:
to_char(date, 'yyyymmdd')::int
One method is to construct the value from date parts. Here is a numeric conversion:
select (year(date) % 100) * 10000) + month(date) * 100 + day(date)
It is easy to convert this to a number:
select cast( (year(date) % 100) * 10000) + month(date) * 100 + day(date) as varchar(10))
The slight advantage to this approach over using convert is that a human being can understand the logic without perusing arcane documentation, specific to SQL Server. I don't know why SQL Server doesn't support a simple format-type function similar to most other databases (and programming languages).
select date_format(column_name, '%Y%m%d') from table_name;

What is the best way to write the date in mm-mm-yyyy in SQL

I'd like to return a date from SQL in the following format 2011-12-DEC, 2012-01-JAN, 2012-02-FEB, 2012-03-MAR etc...
Currently I have the below code, but don't think it's the best. It also does not return a 0 in front of the month (i.e. 8 rather than 08)
print CONVERT(VARCHAR(20), DATEPART(yyyy,GETDATE())) + '-'+ CONVERT(VARCHAR(20), DATEPART(mm,GETDATE()))
For SQL Server, something like this
select convert(varchar(8), getdate(),120)
+ convert(varchar(3),datename(month,getdate()))
For Oracle use TO_CHAR and date formatting. For Example
SELECT TO_CHAR(SYSDATE, 'YYYY-DD-MON') FROM DUAL
There is a wide range of possible date format strings
See here.
If you really do want yyyy-mm-mmm then you could get it like so (for SQL server):
select substring(convert(nvarchar, getdate(), 120), 1, 7)
+ '-' +
substring(upper(datename(mm, getdate())), 1, 3)
Consider a DATE_FORMAT function or the like, depending on your RDMS.
Well,
you should use a formatter (eg AS [DD/MM/YYYY] ).
All of them are listed here including your requirement for "month" naming
http://www.sql-server-helper.com/tips/date-formats.aspx
SELECT SUBSTRING(CONVERT(VARCHAR(11), GETDATE(), 113), 4, 8) AS [Mon-YYYY]
would give you Apr-2006
just turn it around as you like.

SQL get last month name

Following command giving me current month (March) in short form.
SELECT left(datename(month, getdate()), 3)
But i need last month Feb.
I meant whenever i run this command will give me last month name.
What would be the sql command?
Assuming you are using T-SQL:
SELECT left(datename(month, dateadd(month,-1,getdate())), 3)
http://msdn.microsoft.com/fr-fr/library/ms186819.aspx
SELECT left(datename(month, dateadd(dd, -1, getdate())), 3)
try this:
SELECT left(datename(month, dateadd(m,-1,getdate())), 3)
Try this:
SELECT left(datename(month, date_sub( getdate(), interval 1 month ) ), 3)
This will work for MySQL (you didn't specify your SQL server), might need something similar to date_sub for different DBs.
SELECT left(datename(month, DATEADD(MM,-1,getdate())), 3)
select left(datename(month, dateadd(month, -1, getdate()),3)
SELECT DATENAME(MM,DATEADD(MM,-1,GETDATE())) AS 'The Name of last Month'
to print Name of the particular day we have to use DATENAME() function. So, we used this function here for that purpose.
MM represents month here.
-1 is used in Date function to get previous month.
Assuming TSQL, you're going to want to incorporate the DATEADD() function into that query:
http://msdn.microsoft.com/en-us/library/ms186819.aspx
wrap getdate in that and you should be golden.
Try this:
select substring(DATENAME(MONTH,getdate()),1,3)
i think it will help you much better
Regards,
Azarudhin S.

sql compare datetime today

I hope anyone can translate my abstract query.
I want to select * from TABLE where ( [MYDATETIMEROW] < (TODAY - 3 Days)).
Does I have to Convert, cast or use datepart or anything else?.. im confused.
Are there simple rules? I would'nt have problems to do that with linq but simple sql I learned just hardly.
Thank you and best regards.
In simple terms:
Select * from Table where MyDateTimeRow < dateadd(dd,-3,getdate())
But using getdate() will provide both a date and a time, experience says that this is unlikely to be exactly what you want - you might want to strip the time down and just consider the date portion
Select * From Table where MyDateTimeRow < dateadd(dd, datediff(dd, 0, getdate()) - 3, 0)
You want the DateAdd function to manipulate dates and the GetDate function to get the current date:
SELECT * FROM MyTable WHERE [MyDateTimeRow] < DateAdd(dd, -3, GetDate())

SQL Server: Get data for only the past year

I am writing a query in which I have to get the data for only the last year. What is the best way to do this?
SELECT ... FROM ... WHERE date > '8/27/2007 12:00:00 AM'
The following adds -1 years to the current date:
SELECT ... From ... WHERE date > DATEADD(year,-1,GETDATE())
I found this page while looking for a solution that would help me select results from a prior calendar year. Most of the results shown above seems return items from the past 365 days, which didn't work for me.
At the same time, it did give me enough direction to solve my needs in the following code - which I'm posting here for any others who have the same need as mine and who may come across this page in searching for a solution.
SELECT .... FROM .... WHERE year(*your date column*) = year(DATEADD(year,-1,getdate()))
Thanks to those above whose solutions helped me arrive at what I needed.
Well, I think something is missing here. User wants to get data from the last year and not from the last 365 days. There is a huge diference. In my opinion, data from the last year is every data from 2007 (if I am in 2008 now). So the right answer would be:
SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1
Then if you want to restrict this query, you can add some other filter, but always searching in the last year.
SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1 AND DATE > '05/05/2007'
The most readable, IMO:
SELECT * FROM TABLE WHERE Date >
DATEADD(yy, -1, CONVERT(datetime, CONVERT(varchar, GETDATE(), 101)))
Which:
Gets now's datetime GETDATE() = #8/27/2008 10:23am#
Converts to a string with format 101 CONVERT(varchar, #8/27/2008 10:23am#, 101) = '8/27/2007'
Converts to a datetime CONVERT(datetime, '8/27/2007') = #8/27/2008 12:00AM#
Subtracts 1 year DATEADD(yy, -1, #8/27/2008 12:00AM#) = #8/27/2007 12:00AM#
There's variants with DATEDIFF and DATEADD to get you midnight of today, but they tend to be rather obtuse (though slightly better on performance - not that you'd notice compared to the reads required to fetch the data).
Look up dateadd in BOL
dateadd(yy,-1,getdate())
GETDATE() returns current date and time.
If last year starts in midnight of current day last year (like in original example) you should use something like:
DECLARE #start datetime
SET #start = dbo.getdatewithouttime(DATEADD(year, -1, GETDATE())) -- cut time (hours, minutes, ect.) -- getdatewithouttime() function doesn't exist in MS SQL -- you have to write one
SELECT column1, column2, ..., columnN FROM table WHERE date >= #start
I, like #D.E. White, came here for similar but different reasons than the original question. The original question asks for the last 365 days. #samjudson's answer provides that. #D.E. White's answer returns results for the prior calendar year.
My query is a bit different in that it works for the prior year up to and including the current date:
SELECT .... FROM .... WHERE year(date) > year(DATEADD(year, -2, GETDATE()))
For example, on Feb 17, 2017 this query returns results from 1/1/2016 to 2/17/2017
For some reason none of the results above worked for me.
This selects the last 365 days.
SELECT ... From ... WHERE date BETWEEN CURDATE() - INTERVAL 1 YEAR AND CURDATE()
The other suggestions are good if you have "SQL only".
However I suggest, that - if possible - you calculate the date in your program and insert it as string in the SQL query.
At least for for big tables (i.e. several million rows, maybe combined with joins) that will give you a considerable speed improvement as the optimizer can work with that much better.
argument for DATEADD function :
DATEADD (*datepart* , *number* , *date* )
datepart can be: yy, qq, mm, dy, dd, wk, dw, hh, mi, ss, ms
number is an expression that can be resolved to an int that is added to a datepart of date
date is an expression that can be resolved to a time, date, smalldatetime, datetime, datetime2, or datetimeoffset value.
declare #iMonth int
declare #sYear varchar(4)
declare #sMonth varchar(2)
set #iMonth = 0
while #iMonth > -12
begin
set #sYear = year(DATEADD(month,#iMonth,GETDATE()))
set #sMonth = right('0'+cast(month(DATEADD(month,#iMonth,GETDATE())) as varchar(2)),2)
select #sYear + #sMonth
set #iMonth = #iMonth - 1
end
I had a similar problem but the previous coder only provided the date in mm-yyyy format. My solution is simple but might prove helpful to some (I also wanted to be sure beginning and ending spaces were eliminated):
SELECT ... FROM ....WHERE
CONVERT(datetime,REPLACE(LEFT(LTRIM([MoYr]),2),'-
','')+'/01/'+RIGHT(RTRIM([MoYr]),4)) >= DATEADD(year,-1,GETDATE())
Here's my version.
YEAR(NOW())- 1
Example:
YEAR(c.contractDate) = YEAR(NOW())- 1
For me this worked well
SELECT DATE_ADD(Now(),INTERVAL -2 YEAR);
If you are trying to calculate "rolling" days, you can simplify it by using:
Select ... FROM ... WHERE [DATE] > (GETDATE()-[# of Days])