DATENAME and DATEPART in SQL - sql

I'm trying to get my EntryDate column in this format 'YYYY_m' for example '2013_04'.
This code has been unsuccessful
DATENAME (YYYY, EntryDate) + '_' + DATEPART (M, EntryDate)
Attempts using DATEFORMAT have also been unsuccessful, stating there was syntax error at ',' after the M. What code would work instead?
Thank you.

How about date_format()?
select date_format(EntryDate, '%&Y_%m')
This is the MySQL way. Your code looks like an attempt to do this in SQL Server.
EDIT:
The following should work in SQL Server:
select DATENAME(year, EntryDate) + '_' + RIGHT('00' + DATEPART(month, EntryDate), 2)
Personally, I might use convert():
select replace(convert(varchar(7), EntryDate, 121), '-', '_')

select DATENAME (YYYY, EntryDate)
+ '_'
+ right('0' + convert(varchar(2),datepart (MM, EntryDate)), 2)
You have to convert the result of DATEPART() to a character string in order for the + to perform an append.
FYI - in the future "unsuccessful" doesn't mean anything. Next time post the actual error you are receiving.

For example:
SELECT concat(EXTRACT(YEAR FROM '2015/1/1'), '_',
LPAD(extract(month from '2014/1/1'),2,'0')) AS OrderYear
This uses
concat to combine strings
lpad to place a leading 0 if month is one digit
and uses extract to pick of the part of date needed.
working fiddle
http://sqlfiddle.com/#!2/63b24/8

DATEPART
It is a Datetime function which extract information from date. This function always returns result as integer type.
SELECT DATEPART(month, '2009-01-01 00:00:00:000') as month
it is return "1" as an integer:
DATENAME
It is also another Datetime function which to extract information from date. This function always returns result as varchar
SELECT DATENAME(month, '2009-01-01 00:00:00:000') as month
it is return "January".

Related

Looking to replace the year in SQL Server

I am converting a date using CONVERT(varchar,DateOfBirth,101) for birthdates.
I want to show these dates with the current year, I've tried REPLACE but you can't use wildcards with it and when I use DATEPART, it doesn't format with the right digits for month and day. I also can't add years because they are wildly different birthdates. Thanks.
If you want to display the date as a string in 101 format for current year, one option uses a direct format():
format(DateOfBirth, 'MM/dd/2020')
You can compute the current date dynamically:
format(DateOfBirth, concat('MM/dd/', year(getdate())))
On the other hand, if you want your result as a date, then you could use datefromparts():
datefromparts(year(getdate()), month(DateOfBirth), day(DateOfBirth))
If it is a datevalue, you can use FORMAT function. If it is a character value, you can use RIGHT and REPLACE.
DECLARE #dateValue DATETIME = '05/12/1999'
DECLARE #dateCharValue VARCHAR(12) = '05/12/1999'
SELECT FORMAT(#dateValue, 'MM/dd/2020')
SELECT REPLACE(#dateCharValue, RIGHT(#dateCharValue,4),2020)
--Result
05/12/2020
This could helped you:
The code CONVERT(varchar(5),GETDATE(),1) return this 05/27 and then just add the year of the date
SELECT CONVERT(varchar(5),GETDATE(),1) + '/' + cast(year(getdate()) as varchar)
Or
SELECT CONVERT(varchar(5),GETDATE(),1) + '/' + convert(varchar,year(getdate()))
The result of both:
05/27/2020 --(This is my current date n.n )
This work but if you use a string something like your example DateOfBirth will be the variable and if this is a string (DateOfBirth = '5/27/1987') you need to convert the string DateOfBirth to Date:
SELECT CONVERT(varchar(5),convert(date,DateOfBirth),1) + '/' + cast(year(GETDATE()) as varchar)
Or
SELECT CONVERT(varchar(5),convert(date,DateOfBirth),1) + '/' + convert(varchar,year(GETDATE()))
The Result of Both :
05/27/2020

Output year and month with a string

Trying to output something like:
2016,11
Using this:
SELECT
CONVERT(VARCHAR(20),YEAR(GETDATE()) + ',' + MONTH(GETDATE())) AS YearMonth
Am I missing something in convert? Because I am getting this error:
Conversion failed when converting the varchar value ',' to data type
int.
Thanks
Try this.
SELECT
CONVERT(VARCHAR(20),YEAR(GETDATE())) + ',' + CONVERT(VARCHAR(20), MONTH(GETDATE())) AS YearMonth
You might use CONVERT with 112 to reach a string without delimiters ("20161110"). Converting this to VARCHAR(*6*) will implicitly cut the day. One (in most cases positiv) side-effect: You will get a low month zero padded (e.g. 2016,04). Then I use STUFF to insert the ,:
SELECT STUFF(CONVERT(VARCHAR(6),GETDATE(),112),5,0,',')
If you do not like the zero padded month, you could replace the 0 in STUFF like this:
DECLARE #d DATETIME={d'2016-04-05'};
SELECT STUFF(CONVERT(VARCHAR(6),#d,112),5,CASE WHEN MONTH(#d)<10 THEN 1 ELSE 0 END,',')
You are missing converting the output of MONTH() to a string. Here is one method:
select datename(year, getdate()) + ',' + cast(month(getdate()) as varchar(255)) as YearMonth
datename() is convenient because it returns a string. Unfortunately, for month it returns the name of the month, rather than the number.
You could also do:
select replace(convert(varchar(7), getdate(), 120), '-', ',')
Or use format() in SQL Server 2012+:
select format(getdate(), 'yyyy,MM')

Two Digit date format in SQL

I have a table field AccID where I have to concatenate Name with Date like 'MyName-010415' in SQL query.
Date format is 01-04-2015 or 01/04/2015. But I want to display it like 010415.
For the date part, to get the format you want you, try this:
SELECT
RIGHT(REPLICATE('0', 2) + CAST(DATEPART(DD, accid) AS VARCHAR(2)), 2) +
RIGHT(REPLICATE('0', 2) + CAST(DATEPART(MM, accid) AS VARCHAR(2)), 2) +
RIGHT(DATEPART(YY, accid), 2) AS CustomFormat
FROM yourtablename
...
The DATEPART(DD, accid) will give you the day part and the same for mm and yy will give you the month and the year parts. Then I added the functions RIGHT(REPLICATE('0', 2) + CAST(... AS VARCHAR(2)), 2) to add the leading zero, instead of 1 it will be 01.
SQL Fiddle Demo
As #bernd-linde suggested, you can use this function to concatenate it with the name part like:
concat(Name, ....) AS ...
Also you can just SELECT or UPDATE depending on what you are looking for.
As in #bernd-linde's fiddle.
I am not sure which language you are using. Let take php as an example.
$AccID = $name.'-'.date('dmy');
OR before you save this data format the date before you insert the data in database.. or you can write a trigger on insert.
You need to use DATE_FORMAT to change format of your date and CONCAT to marge name with date.
Example:
SELECT CONCAT(name, '-', DATE_FORMAT(field,'%m%d%y'))
FROM tbl

Convert date to SQL datetime

I'm somewhat new to T-SQL and despite reading a number of articles that indicate this should work, I'm having trouble converting October 1st of the current year to a datetime.
I've tried:
SELECT CAST(DATEPART(year, GETDATE()) + '1015' AS DATETIME)
SELECT CONVERT(datetime, 'Oct 15 ' + DATEPART(YEAR,GETDATE()),100)
And all kinds of variations.
Any ideas? I need to set a datetime variable to whatever Oct 1st of the current year is.
What you're trying to is close, but DATEPART returns a number, so the "+" is doing addition, not concatenation.
Try it like this:
SELECT CAST(CAST(DATEPART(year, GETDATE()) AS VARCHAR(4)) + '1015' AS DATETIME)
edit -- Ed beat me to it, and the Concat function is better too.
But if you really wanted to knock it out of the park, try this...
SELECT DATEADD(month, 9, DATEADD(year, DATEDIFF(year, 0, getdate()), 0)) As October1CurrentYear
No casting required!
Your first query is very close. The problem is that the plus sign (+) for concatenation is actually giving you a numeric value, which you can't cast to a date.
To concatenate a year and '1015' and end up with a string, use the CONCAT function instead:
SELECT CAST(CONCAT(DATEPART(YEAR, GETDATE()), '1015') AS DATE)

SQL Converting string MMM.YY to date

how do i convert/cast a column contains strings e.g. Jan.08,Feb.08.. into date format so that i can sort them?
Greatest Thanks!
I'd just format as a convertible string for the first of the relevant month, and then cast to datetime, e.g.
CAST('1.' + YourMonthAndYearColumnName AS DATETIME)
...is an expression that will yield a datetime that should be sortable, so:
SELECT
YourMonthAndYearColumnName
FROM
YourTable
ORDER BY
CAST('1.' + YourMonthAndYearColumnName AS DATETIME)
...should do what you're looking for.
If you can make the assumption that all dates will be within the last ten years, you can use the following code:
select convert(datetime, replace('Jan.08', '.', ' 20'))
select convert(datetime, replace('Dec.08', '.', ' 20'))
That formats the string into the format "Jan 2008", which is unambiguous. "Dec.08" could be "8th December this year" or "The month of december 2008".
Or you could use Matt Gibson's suggestion of prepending a "1." to your date before conversion. That removes the ambiguity, and has the advantage of using whatever defaults that SQL server has for dates (i.e. 50 is 1950 and 49 is 2049).
select convert(datetime, '1.' + 'Jan.08')
select convert(datetime, '1.' + 'Dec.49')
select convert(datetime, '1.' + 'Jan.50')