How do I get the month and day with leading 0's in SQL? (e.g. 9 => 09) - sql

DECLARE #day CHAR(2)
SET #day = DATEPART(DAY, GETDATE())
PRINT #day
If today was the 9th of December, the above would print "9".
I want to print "09". How do I go about doing this?

Pad it with 00 and take the right 2:
DECLARE #day CHAR(2)
SET #day = RIGHT('00' + CONVERT(NVARCHAR(2), DATEPART(DAY, GETDATE())), 2)
print #day

For SQL Server 2012 and up , with leading zeroes:
SELECT FORMAT(GETDATE(),'MM')
without:
SELECT MONTH(GETDATE())

Use SQL Server's date styles to pre-format your date values.
SELECT
CONVERT(varchar(2), GETDATE(), 101) AS monthLeadingZero -- Date Style 101 = mm/dd/yyyy
,CONVERT(varchar(2), GETDATE(), 103) AS dayLeadingZero -- Date Style 103 = dd/mm/yyyy

Try this :
SELECT CONVERT(varchar(2), GETDATE(), 101)

Leading 0 day
SELECT FORMAT(GetDate(), 'dd')

SQL Server 2012+ (for both month and day):
SELECT FORMAT(GetDate(),'MMdd')
If you decide you want the year too, use:
SELECT FORMAT(GetDate(),'yyyyMMdd')

Select Replicate('0',2 - DataLength(Convert(VarChar(2),DatePart(DAY, GetDate()))) + Convert(VarChar(2),DatePart(DAY, GetDate())
Far neater, he says after removing tongue from cheek.
Usually when you have to start doing this sort of thing in SQL, you need switch from can I, to should I.

SELECT RIGHT('0'
+ CONVERT(VARCHAR(2), Month( column_name )), 2)
FROM table

Might I suggest this user defined function if this what you are going for:
CREATE FUNCTION dbo.date_code (#my_date date) RETURNS INT
BEGIN;
DECLARE #retval int;
SELECT #retval = CAST(CAST(datepart(year,#my_date) AS nvarchar(4))
+ CONVERT(CHAR(2),#my_date, 101)
+ CONVERT(CHAR(2),#my_date, 103) AS int);
RETURN #retval;
END
go
To call it:
SELECT dbo.date_code(getdate())
It returns as of today
20211129

Roll your own method
This is a generic approach for left padding anything. The concept is to use REPLICATE to create a version which is nothing but the padded value. Then concatenate it with the actual value, using a isnull/coalesce call if the data is NULLable. You now have a string that is double the target size to exactly the target length or somewhere in between. Now simply sheer off the N right-most characters and you have a left padded string.
SELECT RIGHT(REPLICATE('0', 2) + CAST(DATEPART(DAY, '2012-12-09') AS varchar(2)), 2) AS leftpadded_day
Go native
The CONVERT function offers various methods for obtaining pre-formatted dates. Format 103 specifies dd which means leading zero preserved so all that one needs to do is slice out the first 2 characters.
SELECT CONVERT(char(2), CAST('2012-12-09' AS datetime), 103) AS convert_day

DECLARE #day CHAR(2)
SET #day = right('0'+ cast(day(getdate())as nvarchar(2)),2)
print #day

use
CONVERT(CHAR(2), DATE_COLUMN, 101)
to get the month part with 2 characters and
CONVERT(CHAR(2), DATE_COLUMN, 103)
for the day part.

Declare #dateToGet varchar(10)
Set #dateToGet = convert(varchar, getdate(), 112)
This works fine for the whole date with leading zeros in month and day

select
right('0000' + cast(datepart(year, GETDATE()) as varchar(4)), 4) + '-'+ +
right('00' + cast(datepart(month, GETDATE()) as varchar(2)), 2) + '-'+ +
right('00' + cast(datepart(day, getdate()) as varchar(2)), 2) as YearMonthDay

Related

Change date format dd/mm/yyyy to yyyy-mm-dd

am working in SQL Server 2008, while merging I got error like
conversion failed when converting datetime from character string
select *
from table_name
where cast(f_datetime as date) <=
cast(cast(datepart(year,cast(convert(varchar(250),#Year,103) as date) )as varchar(250))+ '-'+ cast(datepart(MM,cast(convert(varchar(10),#month,103) as varchar(50))+'-01' as date)
I cannot speak to the cast() on f_datetime. But for the rest, you can do:
where cast(f_datetime as date) <= convert(date, convert(varchar(250), #year * 10000 + #month * 100 + 1))
This simplifies the calculation, and prevents things like #year from being treated as a date due to the convert() function.
I assume your f_datetime field format is "dd/mm/yyyy". If yes you can easily convert this field instead of trying to merge and convert #year and #month fields. check this query :
SELECT *
FROM table_name
WHERE CONVERT(DATE,f_datetime,103)<= CAST(CONVERT(VARCHAR, #year) + '-' + CONVERT(VARCHAR, #month) + '-' + '01' AS DATE)

Converting three int parameter to one date [duplicate]

This question already has answers here:
Create a date from day month and year with T-SQL
(15 answers)
SQL Server: convert ((int)year,(int)month,(int)day) to Datetime [duplicate]
(4 answers)
Closed 8 years ago.
Consider three parameters:
#Y=2014
#M=11
#D=24
I want to have a function in SQL Server which gets three numbers and return one date as result.
You can use SQL Server 2012 DATEFROMPARTS function.
SELECT DATEFROMPARTS(#year, #month, #day)
For versions below 2012, I'd use:
SELECT CONVERT(DATETIME, STR(#year * 10000 + #month * 100 + #day))
You could do:
select cast(cast( (#y * 10000 + #m * 100 + #d) as varchar(255)) as date)
But datefromparts() is best if you are using SQL Server 2012+.
create function dbo.formatDate(#Y int, #M int, #D int)
returns date
as
begin
declare #retDate date
select #retDate = cast(cast(#Y as varchar) + '-' + cast(#M as varchar) + '-' + cast(#D as varchar) as date)
return #retDate
end
Testing:
select dbo.formatDate(2014, 11, 24)
SELECT CONCAT(day, '/', month, '/', year) AS Date
this is a duplicate of this question
https://stackoverflow.com/a/1923918/3632420
SELECT
CAST(
CAST(year AS VARCHAR(4)) +
RIGHT('0' + CAST(month AS VARCHAR(2)), 2) +
RIGHT('0' + CAST(day AS VARCHAR(2)), 2)
AS DATETIME)
Try this,
declare #Y int=2014
declare #M int =11
declare #D int =2
SELECT CONVERT(VARCHAR(12), (SELECT Cast(#d AS VARCHAR(20)) + '-'
+ Cast(#M AS VARCHAR(20)) + '-'
+ Cast(#y AS VARCHAR(20))), 110)
Change the 110 accordingly needed for different formats
formats in sql server datetime conversion
If you are using SQL Server 2000 and above use the below query
Select MyDate=cast(DateAdd(day, #DayOfMonth - 1,
DateAdd(month, #Month - 1,
DateAdd(Year, #Year-1900, 0))) as date)
If you are using SQL Server 2012 and above use the built function DATEFROMPARTS
like
select DATEFROMPARTS(#year, #month, #day)

Extract month and day from a field in sql

how do you select Month and day like in 'MMDD' format from a column, which has dates in '2014-01-12'(Datetime) format?
If your filed is a Date or DateTime, I would use the function DATEPART.
For example, this gets the current year:
DATEPART(year, GETDATE())
View the msdn page for the full documentation.
If your field is text, use CONVERT to convert your field to a DATE, then use the first method with the converted date as your value.
For example:
DATEPART(year, CONVERT(DATE, '11/1/2014'))
Complete Copy/Paste Example
DECLARE #DateVal VARCHAR(10) = '11/01/2014'
DECLARE #Month VARCHAR(2) = CAST(DATEPART(MONTH, CONVERT(DATE, #DateVal)) AS VARCHAR),
#Day VARCHAR(2) = CAST(DATEPART(DAY, CONVERT(DATE, #DateVal)) AS VARCHAR)
PRINT REPLICATE('0', 2 - LEN(#Month)) + #Month + REPLICATE('0', 2 - LEN(#Day)) + #Day

How to flip month and day in a datetime?

How can I flip "2012-12-01 12:33:00.0" to become "2012-01-12 12:33:00.0"? I had tried "select convert(varchar(50), convert(datetime, log_date, 103), 121)" and used both 101 and 103 and still not able to flip it.
The database is MS SQL
DECLARE #date DATETIME
SET DATEFORMAT ydm
SET #date = '2012-12-01 12:33:00.0'
SELECT #date
SET DATEFORMAT ydm will give you the result in your required format.
Other Option
UPDATE Table_Name
SET COLUMN_NAME= convert(varchar(20), convert(Date, #date, 101)) + convert(varchar(30),convert(time, #date))
WHERE
OR
select convert(datetime, convert(varchar(100), #date), 20)
You could just perform some string manipulation (NOTE: Untested code)
UPDATE table
SET date=
LEFT(CONVERT(VARCHAR(50),date,128),4) -- '2012'
+SUBSTRING(CONVERT(VARCHAR(50),date,128),7,3) -- '-01'
+SUBSTRING(CONVERT(VARCHAR(50),date,128),4,3) -- '-12'
+RIGHT(CONVERT(VARCHAR(50),date,128),LEN(CONVERT(VARCHAR(50),date,128))-10) -- ' 12:33:00.0'
You could use the Format function to swap day and month, while keeping the year and hour:
update MyTable
set [date] =
FORMAT([date],'yyyy') + '-' +
FORMAT([date],'dd') + '-' +
FORMAT([date],'MM') + ' ' +
FORMAT([date],'hh:mm:ss')
from MyTable

Date Format conversion in SQL

I want to convert date format from 01/09 to January 2009 , 09/03 to September 2003 etc. Is this possible in SQL? Please let me know if there is a API for the same.
if you have a DateTime column in your table, it's possible
SELECT DATENAME(MM, YOUR_DATE_COLUMN) + ' ' + CAST(YEAR(YOUR_DATE_COLUMN) AS VARCHAR(4)) AS [Month YYYY]
http://www.sql-server-helper.com/tips/date-formats.aspx
You should look here.
It's rather simple.
You should first convert it to a datetime. Then you can easily apply any formating when you read it later.
declare #d varchar(10);
set #d = '01/09'
select
--cast(#d as datetime) as d1, --syntax error converting char string
cast('20' + right(#d, 2) + '-' + left(#d, 2) + '-01' as datetime) as d2
then convert it to mmm yyyy using rm's answer
select datename(month, GETDATE()) + ' '+ substring(convert(varchar, GETDATE(), 100),8,4)