Return Static date using SQL Function - sql

I have a situation where i need to return a date.Here for this function i will be supplying month number and i need to return result like "3/13/2012".
declare #date varchar(20)
select #date=datepart(month,getdate())+'/13/'+datepart(year,getdate())
return #date(#date)

This should do it for ya.
CREATE FUNCTION dbo.fnStaticDate(#month varchar(2))
RETURNS DATETIME
AS
BEGIN
DECLARE #year VARCHAR(4)
SET #year = DATEPART(year, GETDATE())
RETURN CONVERT(DATETIME, #year + '-' + #month + '-' + '13')
END

Here is the working solution which i have used for one of my project.
created a store procedure with input parameter of month
declare #mon varchar(2)
set #mon = '3'
select CONVERT(varchar, #mon + '/13/' + convert(varchar, datepart(year, getdate())), 111 )
execute the above lines in SQL server you will get the result.
test by changing the #mon value in set statement.
Hope it helps you.

conversion error it gives
declare #date varchar(20)
select #date=convert(varchar(2),datepart(month,getdate()))+'/13/'+convert(varchar(4),datepart(year,ge tdate()))
print (#date)

Related

How to create a Date in SQL Server given the Day, Month and Year as Integers

FOR Example if I have:
DECLARE #Day int = 25
DECLARE #Month int = 10
DECLARE #Year int = 2016
I want to return
2016-10-25
As Date or datetime
In SQL Server 2012+, you can use datefromparts():
select datefromparts(#year, #month, #day)
In earlier versions, you can cast a string. Here is one method:
select cast(cast(#year*10000 + #month*100 + #day as varchar(255)) as date)
In SQL Server 2012+, you can use DATEFROMPARTS():
DECLARE #Year int = 2016, #Month int = 10, #Day int = 25;
SELECT DATEFROMPARTS (#Year, #Month, #Day);
In earlier versions, one method is to create and convert a string.
There are a few string date formats which SQL Server reliably interprets regardless of the date, language, or internationalization settings.
A six- or eight-digit string is always interpreted as ymd. The month
and day must always be two digits.
https://learn.microsoft.com/en-us/sql/t-sql/data-types/datetime-transact-sql
So a string in the format 'yyyymmdd' will always be properly interpreted.
(ISO 8601-- YYYY-MM-DDThh:mm:ss-- also works, but you have to specify time and therefore it's more complicated than you need.)
While you can simply CAST this string as a date, you must use CONVERT in order to specify a style, and you must specify a style in order to be deterministic (if that matters to you).
The "yyyymmdd" format is style 112, so your conversion looks like this:
DECLARE #Year int = 2016, #Month int = 10, #Day int = 25;
SELECT CONVERT(date,CONVERT(varchar(50),(#Year*10000 + #Month*100 + #Day)),112);
And it results in:
2016-10-25
Technically, the ISO/112/yyyymmdd format works even with other styles specified. For example, using that text format with style 104 (German, dd.mm.yyyy):
DECLARE #Year int = 2016, #Month int = 10, #Day int = 25;
SELECT CONVERT(date,CONVERT(varchar(50),(#Year*10000 + #Month*100 + #Day)),104);
Also still results in:
2016-10-25
Other formats are not as robust. For example this:
SELECT CASE WHEN CONVERT(date,'01-02-1900',110) = CONVERT(date,'01-02-1900',105) THEN 1 ELSE 0 END;
Results in:
0
As a side note, with this method, beware that nonsense inputs can yield valid but incorrect dates:
DECLARE #Year int = 2016, #Month int = 0, #Day int = 1025;
SELECT CONVERT(date,CONVERT(varchar(50),(#Year*10000 + #Month*100 + #Day)),112);
Also yields:
2016-10-25
DATEFROMPARTS protects you from invalid inputs. This:
DECLARE #Year int = 2016, #Month int = 10, #Day int = 32;
SELECT DATEFROMPARTS (#Year, #Month, #Day);
Yields:
Msg 289, Level 16, State 1, Line 2 Cannot construct data type date,
some of the arguments have values which are not valid.
Also beware that this method does not work for dates prior to 1000-01-01. For example:
DECLARE #Year int = 900, #Month int = 1, #Day int = 1;
SELECT CONVERT(date,CONVERT(varchar(50),(#Year*10000 + #Month*100 + #Day)),112);
Yields:
Msg 241, Level 16, State 1, Line 2 Conversion failed when converting
date and/or time from character string.
That's because the resulting string, '9000101', is not in the 'yyyymmdd' format. To ensure proper formatting, you'd have to pad it with leading zeroes, at the sacrifice of some small amount of performance. For example:
DECLARE #Year int = 900, #Month int = 1, #Day int = 1;
SELECT CONVERT(date,RIGHT('000' + CONVERT(varchar(50),(#Year*10000 + #Month*100 + #Day)),8),112);
Results in:
0900-01-01
There are other methods aside from string conversion. Several are provided in answers to "Create a date with T-SQL". A notable example involves creating the date by adding years, months, and days to the "zero date".
(This answer was inspired by Gordon Linoff's answer, which I expanded on and provided additional documentation and notes.)
Old Microsoft Sql Sever (< 2012)
RETURN dateadd(month, 12 * #year + #month - 22801, #day - 1)
The following code should work on all versions of sql server I believe:
SELECT CAST(CONCAT(CAST(#Year AS VARCHAR(4)), '-',CAST(#Month AS VARCHAR(2)), '-',CAST(#Day AS VARCHAR(2))) AS DATE)
Simple and most flexible solution
Use FORMAT function to make any type of format you like.
Here is copy paste working example:
DECLARE #year int = 2021, #month int = 12, #day int = 16
DECLARE #date varchar(20)
SET #date = cast((format(#year,'####') +'-'+format(#month,'##')+'-'+format(#day,'##')) as date)
SELECT #date
It will also display leading zeros for days and months.
So, you can try this solution:
DECLARE #DAY INT = 25
DECLARE #MONTH INT = 10
DECLARE #YEAR INT = 2016
DECLARE #DATE AS DATETIME
SET #DATE = CAST(RTRIM(#YEAR * 10000 + #MONTH * 100 + #DAY) AS DATETIME)
SELECT REPLACE(CONVERT(VARCHAR(10), #DATE, 102), '.', '-') AS EXPECTDATE
Or you can try this a few lines of code:
DECLARE #DAY INT = 25
DECLARE #MONTH INT = 10
DECLARE #YEAR INT = 2016
SELECT CAST(RTRIM(#YEAR * 10000 +'-' + #MONTH * 100+ '-' + #DAY) AS DATE) AS EXPECTDATE
select convert(varchar(11), transfer_date, 106)
got me my desired result of date formatted as 07 Mar 2018
My column 'transfer_date' is a datetime type column and I am using SQL Server 2017 on azure
CREATE DATE USING MONTH YEAR IN SQL::
DECLARE #FromMonth int=NULL,
#ToMonth int=NULL,
#FromYear int=NULL,
#ToYear int=NULL
/**Region For Create Date**/
DECLARE #FromDate DATE=NULL
DECLARE #ToDate DATE=NULL
SET #FromDate=DateAdd(day,0, DateAdd(month, #FromMonth - 1,DateAdd(Year, #FromYear-1900, 0)))
SET #ToDate=DateAdd(day,-1, DateAdd(month, #ToMonth - 0,DateAdd(Year, #ToYear-1900, 0)))
/**Region For Create Date**/
For SQL Server 2008 users, I made a custom function:
CREATE FUNCTION sql2012_datefromparts
(
#Year int, #Month int, #Day int
)
RETURNS DATETIME
AS
BEGIN
RETURN convert(datetime,convert(varchar,#year)+right('0'+convert(varchar,#month),2)+right('0'+convert(varchar,#day),2))
END
GO
To use it:
DECLARE #day int=29, #month int=10, #year int=1971
SELECT dbo.sql2012_datefromparts(#year,#month,#day)

Declare a date variable from month and year SQL

I want to make a new variable of type Date by passing the Month and Year
I don't know the syntax, but maybe something like:
DECLARE #Date Date
SET #Month(Date) = #Month
SET #Year(Date) = #Year
The Month and Year are some parameters of my application.
Do you mean DATEFROMPARTS ?
DECLARE #Date Date = DATEFROMPARTS ( #Year, #Month, #Day )
EDIT: This function only available after SQL Server 2012.
For SQL Server 2008. You may use the following
SET #Date = CAST(CONVERT(VARCHAR, #year) + '-' + CONVERT(VARCHAR, #month) + '-' + CONVERT(VARCHAR, #day) AS DATE)
you can do a number of things to accomplish this task...
an easy way is to just declare the variables, then in the select statement where clause you can add them. so:
declare #year as int (or whatever data type you need to use)
as
select * from yourtable
where year = #year and month = #month

How to Convert int value 20140401 to 'April 2014' in SQL Server 2008

This is what I tried .....
declare #date varchar(8)
set #date = (select max(convert(varchar(10), fileextractperiod))
from [info-CentralReturns-DEV].CentralReturns.FactCancer)
select CONVERT(varchar(10), cast(#date as DATE), 103)
Resulting output: 01/04/2014
But I need output as April 2014
SQL Server 2008 only supports the limited set of system-provided styles for CONVERT - if none of those match your needs, you'll need to handle it yourself. SQL Server 2012 has a FORMAT function for this purpose..
So in SQL Server 2008, you could create a function like this:
CREATE FUNCTION dbo.FormatDateMonthYear(#input DATE)
RETURNS VARCHAR(50)
AS BEGIN
DECLARE #Year INT = YEAR(#input)
DECLARE #MonthName VARCHAR(15) = DATENAME(MONTH, #input)
DECLARE #Result VARCHAR(50)
SET #Result = #MonthName + ' ' + CAST(#Year AS VARCHAR(4))
RETURN #Result
END
and then call it to get the format you need:
SELECT dbo.FormatDateMonthYear('2014-04-22')
and you should get
April 2014
SELECT
CONVERT(CHAR(4), #date, 100) + CONVERT(CHAR(4), #date, 120)
SELECT
DateName( month , DateAdd( month , cast(SUBSTRING(#date, 5, 2) as int), -1 ) )
+ ' ' + SUBSTRING(#date, 1, 4)
Select DATENAME(MONTH,#date)+' '+CONVERT(VARCHAR(4),YEAR(#Date))

Getting Datetime by Year, Month, Date

I want to get date by Using Year, Month and Day functions. Example
declare #Date smalldatetime
select #Date = Year('20140530') + Month('20140530') + Day('20140530')
What I want is to assign #Date = '20140530' as smalldatetime. But I want to do this by means of somwething similar to above expression. How can Ido this. Thanks in advance.
Instead try something like below
declare #Date varchar(20)
select #Date = cast(Year('20140530') as varchar) +
cast(Month('20140530') as varchar) +
cast(Day('20140530') as varchar)
select #Date
results in: 2014530.
(OR) like below
declare #Date VARCHAR(20)
select #Date = cast(Year('20140530') as varchar) + '-' +
cast(Month('20140530') as varchar) + '-' +
cast(Day('20140530') as varchar)
select cast(#Date as smalldatetime)
results in: 2014-05-30 00:00:00
Year()/Month()/DaY() functions returns the year/Month/Day as Integer. What you are actually doing can be simulated as below
declare #Date smalldatetime
set #Date = 2049
select #Date
which will result in : 1905-08-12 00:00:00
Use Like, Set will give the Date in #Date instead of select
declare #Date smalldatetime
set #Date = Year('20140530') + Month('20140530') + Day('20140530')
print #Date

How to get month and year from the date

Using SQL Server 2000
Date like 20120101, 20120201, 20120301...
Fomat is yyyymmdd
I want to display month and year from the date like 01/2012, 02/2012, 03/2012...
Expected Output
01/2012
02/2012
03/2012
I don't want 1/2012, 2/2012, 3/2012...
Can any one give me a idea or query help....
You can use something like this:
DECLARE #input VARCHAR(20)
SET #input = '20120101'
-- convert the 20120101 to a DATETIME
DECLARE #thedate DATETIME
SELECT #thedate = CONVERT(DATETIME, #input, 112)
-- reformat that DATETIME to your needs
DECLARE #output VARCHAR(20)
SET #output = RIGHT('00' + CAST(DATEPART(MONTH, #thedate) AS VARCHAR(2)), 2) +
'/' + CAST(DATEPART(YEAR, #thedate) AS VARCHAR(4))
SELECT #output
You could "hide" this functionality into a user-defined function to make it more easily usable in your code:
CREATE FUNCTION dbo.MonthYearFromDate (#input VARCHAR(20))
RETURNS VARCHAR(20)
AS BEGIN
DECLARE #thedate DATETIME
SELECT #thedate = CONVERT(DATETIME, #input, 112)
DECLARE #output VARCHAR(20)
SET #output = RIGHT('00' + CAST(DATEPART(MONTH, #thedate) AS VARCHAR(2)), 2) + '/' + CAST(DATEPART(YEAR, #thedate) AS VARCHAR(4))
RETURN #output
END
and then you can call this like so:
SELECT dbo.MonthYearFromDate('20120515')
and get the output
05/2012
SELECT CAST(datepart(month,getdate()) AS CHAR) + '/' + CAST(datepart(year,getdate()) AS CHAR)
Instead of the function getdate() you need your date field.
have a look at the SUBSTRING function http://msdn.microsoft.com/en-us/library/ms187748.aspx
You should also consider storing your dates as a DATETIME (I assume you are using VARCHAR?)
Search on extract() function. It will solve your problem.