Getting Datetime by Year, Month, Date - sql

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

Related

Dates returned as columns in SQL Select

My user will submit a FromDate and a ToDate. What I want to happen is to select the dates that fall in between these dates, which I have accomplished with the script below. The dates will by dynamic.
DECLARE #fromDateParam DATETIME = '2022-01-24 00:00:00.000'
DECLARE #toDateParam DATETIME = '2022-01-29 00:00:00.000'
;WITH fnDateNow(DayOfDate) AS
(
SELECT #fromDateParam AS TransactionDate
UNION ALL
SELECT DayOfDate + 1
FROM fnDateNow
WHERE DayOfDate < #toDateParam
)
SELECT fnDateNow.DayOfDate AS TransactionDate
FROM fnDateNow
This returns that dates as rows. What I am looking for is a way to make these dates return as the columns for a different script.
This table is called DailyTransactionHeader and it has a column [TransactionDate] and another one called [Amount].
There is the probability that their is not a DailyTransactionHeader with the specified Date for this I am looking to return 0.
So I am trying to have the data look like this (I formatted the date) There would be more than one row, but I just wanted to show an example of what I am trying to accomplish.
I appreciate any help,
Thanks
You can do it using dynamic sql. For example:
CREATE PROCEDURE [GET_DATE_TABLE]
(
#FROMDATE DATETIME,
#TODATE DATETIME
)
AS
DECLARE #PDATE DATETIME
DECLARE #SQL VARCHAR(MAX)
DECLARE #SEP VARCHAR(10)
SET #PDATE = #FROMDATE
SET #SQL = 'SELECT '
SET #SEP = ''
WHILE #PDATE < #TODATE
BEGIN
SET #SQL = #SQL + #SEP + 'NULL as [' + CONVERT(VARCHAR, CONVERT(DATE, #PDATE)) + ']'
SET #PDATE = #PDATE + 1
SET #SEP = ', '
END;
EXEC(#SQL)
Test Example:
DECLARE #fromDateParam DATETIME = '2022-01-24 00:00:00.000'
DECLARE #toDateParam DATETIME = '2022-01-29 00:00:00.000'
exec dbo.GET_DATE_TABLE #fromDateParam, #toDateParam

Want to print declared date and Month

I want to get declared Month and date by the below query, but I am getting something as
Jul 21 1905 12:00AM
I want it as
Dec 31 2015
below is my query
declare #actualMonth int
declare #actualYear int
set #actualYear = 2015
set #actualMonth = 12
DECLARE #DATE DATETIME
SET #DATE = CAST(#actualYear +'-' + #actualMonth AS datetime)
print #DATE
what is wrong here
This will give you as expected output,
DECLARE #actualMonth INT
DECLARE #actualYear INT
SET #actualYear = 2015
SET #actualMonth = 12
DECLARE #DATE DATETIME;
SET #DATE = CAST(
CAST(#actualYear AS VARCHAR)+'-'+CAST(#actualMonth AS VARCHAR)+'-'+'31'
AS DATETIME
);
PRINT Convert(varchar(11),#DATE,109)
Try this,
SET #DATE = CAST(
CAST(#actualYear AS VARCHAR)+'-'+CAST(#actualMonth AS VARCHAR)+'-'+ Cast(Day(DATEADD(DAY,-1,DATEADD(month,#actualMonth,DATEADD(year,#actualYear-1900,0)))) AS VARCHAR)
AS DATETIME
);
Or this one,
SET #DATE = CAST(
CAST(#actualYear AS VARCHAR)+'-'+CAST(#actualMonth AS VARCHAR)+'-'+'01'
AS DATETIME
);
PRINT CONVERT(VARCHAR(11), DATEADD(D, -1, DATEADD(M, 1, #DATE)), 109)
You should convert those month and year to varchar and then convert the final result to datetime. It should be
DECLARE #DATE DATETIME;
SET #DATE = CAST(CAST(#actualYear AS VARCHAR) + '-' + CAST(#actualMonth AS VARCHAR) + '-' + '31' AS DATETIME);
Actually you are actualMonth and actualYear and converting as datetime it wil give other result
Try like this
declare #actualMonth int
declare #actualYear int
set #actualYear = 2015
set #actualMonth = 12
DECLARE #DATE DATETIME
SET #DATE = DATEADD(dd,-1,DATEADD(YY,1,CAST(#actualYear AS varchar(20)) ))
select SUBSTRING(convert (varchar,#DATE),0,CHARINDEX(':',convert (varchar,#DATE))-2)
print #DATE
It is no so trivial as seems. You should handle correct last days for each month.
DECLARE #actualMonth int
DECLARE #actualYear int
SET #actualYear = 2016
SET #actualMonth = 2
DECLARE #tmpDate DATETIME
SET #tmpDate = CAST(CAST(#actualYear AS VARCHAR) + RIGHT('0' + CAST(#actualMonth AS VARCHAR), 2) + '01' AS DATETIME);
SELECT CONVERT(varchar(11), DATEADD(d, -1, DATEADD(m, 1, #tmpDate)), 100)
Update
Ok, I'll try to explain problem more deeper.
What is different between extended (used by #rajeshpanchal) and basic (used by me) formats of ISO 8601?
In fact the SQL Server treats date(datetime) specified in basic and extended formats differently regarding DATEFORMAT setting.
Look at this code:
Declare #str1 varchar(8) = '20160121'
Declare #str2 varchar(10) = '2016-01-21'
Declare #dt1 datetime
Declare #dt2 datetime
--set dateformat ydm ---- 1
set dateformat ymd -----2
set #dt1 = #str1
set #dt2 = #str2
select #dt1
select #dt2
This code will work correctly. But when you uncomment first and comment second set dateformat (dateformat set to ydm) the extended format will fail when basic format will work correctly.

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.

Return Static date using SQL Function

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)

SQL: How to produce next date given month and day

In my table I have a Month(tinyint) and a Day(tinyint) field. I would like to have a function that takes this month and day and produces a datetime for the next date(including year) given this month and day.
So if I had Month = 9, Day = 7 it would produce 9/7/2009.
If I had Month 1, Day 1 it would produce 1/1/2010.
something like this would work. It's variation on your method, but it doesn't use the MM/DD/YYYY literal format, and it won't blowup against bad input (for better or for worse).
declare #month tinyint
declare #day tinyint
set #month = 9
set #day = 1
declare #date datetime
-- this could be inlined if desired
set #date = convert(char(4),year(getdate()))+'0101'
set #date = dateadd(month,#month-1,#date)
set #date = dateadd(day,#day-1,#date)
if #date <= getdate()-1
set #date = dateadd(year,1,#date)
select #date
Alternatively, to create a string in YYYYMMDD format:
set #date =
right('0000'+convert(char(4),year(getdate())),4)
+ right('00'+convert(char(2),#month),2)
+ right('00'+convert(char(2),#day),2)
Another method, which avoids literals all together:
declare #month tinyint
declare #day tinyint
set #month = 6
set #day = 24
declare #date datetime
declare #today datetime
-- get todays date, stripping out the hours and minutes
-- and save the value for later
set #date = floor(convert(float,getdate()))
set #today = #date
-- add the appropriate number of months and days
set #date = dateadd(month,#month-month(#date),#date)
set #date = dateadd(day,#day-day(#date),#date)
-- increment year by 1 if necessary
if #date < #today set #date = dateadd(year,1,#date)
select #date
Here is my sql example so far. I don't really like it though...
DECLARE #month tinyint,
#day tinyint,
#date datetime
SET #month = 1
SET #day = 1
-- SET DATE TO DATE WITH CURRENT YEAR
SET #date = CONVERT(datetime, CONVERT(varchar,#month) + '/' + CONVERT(varchar,#day) + '/' + CONVERT(varchar,YEAR(GETDATE())))
-- IF DATE IS BEFORE TODAY, ADD ANOTHER YEAR
IF (DATEDIFF(DAY, GETDATE(), #date) < 0)
BEGIN
SET #date = DATEADD(YEAR, 1, #date)
END
SELECT #date
Here's a solution with PostgreSQL
your_date_calculated = Year * 10000 + Month * 100 + Day
gives you a date like 20090623.
select cast( cast( your_date_calculated as varchar ) as date ) + 1
Here's my version. The core of it is just two lines, using the DATEADD function, and it doesn't require any conversion to/from strings, floats or anything else:
DECLARE #Month TINYINT
DECLARE #Day TINYINT
SET #Month = 9
SET #Day = 7
DECLARE #Result DATETIME
SET #Result =
DATEADD(month, ((YEAR(GETDATE()) - 1900) * 12) + #Month - 1, #Day - 1)
IF (#Result < GETDATE())
SET #Result = DATEADD(year, 1, #Result)
SELECT #Result