Want to print declared date and Month - sql

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.

Related

SQL Server: Convert varchar numbers to date

Is it possible to convert a varchar numbers to date? I am fetching data from a table and I want it converted into date. Can you help me figure this out?
There is an error on the last part:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
declare #year varchar(6)
declare #month varchar(2)
declare #test varchar (8)
set #year = right(left('F20160316-1000',5),4)
select #year
set #month = right(left('F20160316-1000',7),2)
select #month
set #test = #month +''+ #year
select #test
SELECT CONVERT (DATETIME, CONVERT(varchar(12),#test))
Anyway, the the result that I want to achieve is MAR2016.
The way you are storing and converting is not good as Jarlh pointed out.You could use datetimefrom parts to get output ,in your case day is missing ,i added it..
declare #year varchar(6)
declare #month varchar(2)
declare #day varchar (8)
set #year = right(left('F20160316-1000',5),4)
set #month = right(left('F20160316-1000',7),2)
Set #day=right(left('F20160316-1000',5),2)
select datetimefromparts(#year,#month,#day)
further if your string pattern is same ,you can do this as well..
declare #string varchar(15)
set #string='F20160316-1000'
select convert(datetime,substring(#string,2,charindex('-',#string,1)-2)
Output:
2016-03-16 00:00:00.000
Try like this,
DECLARE #year VARCHAR(6)
DECLARE #month VARCHAR(2)
DECLARE #test VARCHAR(8)
SET #year = right(left('F20160316-1000', 5), 4)
SET #month = right(left('F20160316-1000', 7), 2)
SET #test = #year + #month + '01'
SELECT UPPER(CONVERT(VARCHAR(3), DATENAME(MM, #test), 100)) + #year AS MonthYear

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 year and month separately from this string in sql server?

I have this string format mm/yyyy-
01/2010
how do i get the month and year separately from it. I want it separately 01 and 2010 in a way i could compare them?
This should hook you up (assumes that #Date represents your date string):
DECLARE #SlashPos int;
SET #SlashPos = CHARINDEX('/', #Date);
Declare #Month varchar(2);
Declare #Year varchar(4);
SET #Month = SUBSTRING(#Date, 1, #SlashPos - 1);
Set #Year = SUBSTRING(#Date, #SlashPos + 1, LEN(#Date) - #SlashPos);
At this point, #Month and #Year will contain strings representing the month and year.
Example:
declare #d char(7);
declare #Month varchar(2);
declare #Year varchar(4);
set #d = '01/2010';
SET #Month = LEFT(#d, 2);
SET #Year = RIGHT(#d, 4);
check out help for substring and charindex functions

SQL how to make this always return the first of the month

I have the following code:
DECLARE #monthPassed VARCHAR(MAX)
SET #monthPassed = '2010'
DECLARE #yearPassed VARCHAR(MAX)
SET #yearPassed = '10'
DECLARE #TempDate DATETIME
SET #TempDate = CAST(#monthPassed + '/' + '1' + '/' + #yearPassed AS DATETIME)
DECLARE #TestDate DATETIME
SET #TestDate = DATEADD(MONTH, 1, #TempDate)
This makes #TestDate 11-02-10. How would I always make this return the first of the month instead?
Might have something to do with #monthPassed and #yearPassed being inverted. Switching them, on my end, resolved the problem.
DECLARE #monthPassed VARCHAR(MAX)
SET #monthPassed = '10'
DECLARE #yearPassed VARCHAR(MAX)
SET #yearPassed = '2010'
DECLARE #TempDate DATETIME
SET #TempDate = CAST(#monthPassed + '/' + '1' + '/' + #yearPassed AS DATETIME)
DECLARE #TestDate DATETIME
SET #TestDate = DATEADD(MONTH, 1, #TempDate)
SELECT #TestDate;
Results in:
+-------------------------+
| (no column name) |
+-------------------------+
| 2010-11-01 00:00:00.000 |
+-------------------------+
You got the month assigned to the year, and vice versa
DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)
Using variables/parameters of appropriate width should have highlighted the problem where you are assigning the year to the month variable and vice versa.
Consider adding validation to ensure the parameter values are digits, are with range, etc.
Using the format 'yyyymmdd' provides immunity to regional settings problems:
DECLARE #yearPassed CHAR(4);
SET #yearPassed = '2010';
DECLARE #monthPassed CHAR(2);
SET #monthPassed = '10';
DECLARE #TestDate DATETIME
SET #TestDate = CAST(#yearPassed + #monthPassed + '01' AS DATETIME);

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