Variable Timeperiod with a dash - sql

I need to create a variables called Reporting_Period, which I retrieve from the date variable: Return Closing Date.
Reporting_Period needs to look like 2019 - 2020 or 2020 - 2021 etc
I am having problems incorporating that dash and I tried +' - '+
The error message I am getting is:
Operand type clash: date is incompatible with int
What do I need to do?
The code I am trying is as below:
,((YEAR ([Return Closing Date])) +' - '+ (DATEADD(YEAR, -1,([Return Closing Date])))) AS [Reporting_Period]

Excellent #JohnCappelletti, is worked:
,CONCAT(YEAR ([Return Closing Date]), '-' ,(YEAR(DATEADD(YEAR, -1,([Return Closing Date]))))) AS [Reporting_Period]

Related

Date Manipulation in SQL

I tried different functions to convert Datepart for year, month and day to a date but I am getting errors.
This is what I tried:
SELECT
CONVERT(datetime, CHAR(YEAR(GETDATE()) + CHAR(DATEPART(MM, '02')) + CHAR(DATEPART(DD, '28')));
When running this code, I get an error:
Conversion failed when converting date and/or time from character string.
In case I remove those single quotes on 02 and 28 then SQL will return null.
Thanks in advance
If 2012+ you could also try DateFromParts()
Select DateFromParts(2016,2,28)
Returns
2016-02-28
Try this instead:
SELECT CONVERT(datetime, DATENAME(YEAR, GETDATE()) + '-02-28')
You can't extract a day or month from a string such as '02'. But there is no need to do that anyway.
As you can read in the documentation on DATEPART, the second parameter should be a date parameter:
Returns an integer that represents the specified datepart of the specified date.
In your SQL statement you are misusing this function twice... following are invalid because the second parameter cannot be converted to a date type:
DATEPART(MM,'02')
DATEPART(DD,'28')
You can construct a date from its parts using the DATEFROMPARTS function in SQL Server 2012 and later versions:
Returns a date value for the specified year, month, and day.
Or if you need the time parts filled in as well, DATETIMEFROMPARTS
Returns a datetime value for the specified date and time.
In versions prior to SQL Server 2012, this can be done like this:
DATEADD(MM, (#year - 1900) * 12 + #month - 1 , #day - 1);

SQL Server : convert string to numeric - Conversion failed when converting date and/or time from character string

I got a dataset in SQL Server Management Studio.
The data looks like the following
month Year
-------------
Feb 2016
Jan 2015
I want to create a numeric date using 01 as dd. I tried
CAST('01-'+ month +'-'+ year AS DATE)
also
CONVERT(DATETIME, '01-'+ month +'-'+ year, 106) AS
Both of them cause this error:
Conversion failed when converting date and/or time from character string.
Can anyone teach me how to covert the string into numeric datetime/date please.
Perhaps the reason is the hyphens. You should try with spaces instead:
convert(datetime, '01 '+ month +' '+ year, 106)
Another possibility is that month contains invalid values. In SQL Server 2012+, use try_convert() to avoid that problem:
try_convert(datetime, '01 '+ month +' '+ year, 106)
Another option is to use concat with convert if 2012+
Select convert(datetime, concat(1,month ,year), 106)
Use this code
convert(datetime, concat('01-', mnth , '-',yr), 106) AS d

Converting a Date Format to YYYYMM in Cognos Report Studio

I have a date column in a format 12 May, 2014 I want to convert that into yyyymm/ 201405 format.
i tried multiple options like
extract(year, sys_date)*100 + extract(month, sys_date))*100
cast(extract( year, sys_date), varchar(4)) + cast(extract( month, sys_date), varchar(2))
This one works but returns me in YYY,YMM format.
CAST(to_char(sys_date, 'YYYYMM'), INT )
For the above two, it gives an error:
An error occurred while performing operation 'sqlOpenResult' status='-28'
Can some one please guide. Thank you in advance.
I got what I was looking for. This is what I did:
translate(CAST(to_char(sys_date, 'YYYYMM'), varchar(6) ), ',' , ' ')
I am sure there would be a better way to get the result but for now I would use this SQL as it gives me what I want :)
I did it so.
substring(cast(substring(cast([sys_date];char(7));1;4)||substring(cast([sys_date];char(7));6;2);char(6));1;6 )
to me worked

datetime error when setting filter to current financial year (01July2013 - 30June2014)

a sql script that we written last year has stopped working now that we in the year 2014 with the following error "The conversion of a varchar data type to a datetime data type resulted in an out-of-range value"
I'm not familiar with SQL, the error message is pointing to this section of the script.
declare #current_fiscal datetime
set #current_fiscal =
case
when (month(getdate()) < 7) then
cast(dateadd(year,-1,year(getdate())) as varchar(4)) + '0702'
else
cast(year(getdate()) as varchar(4)) +'0702'
end
I'm not sure what the purpose of '0702' is also. Look forward to hearing from someone.
They obviously wrote this in July or later and never tested the first half of the expression.
cast(dateadd(year,-1,year(getdate())) as varchar(4)) + '0702'
Should be:
cast(year(dateadd(year,-1,getdate())) as varchar(4)) + '0702'
Or even easier:
CAST(YEAR(GETDATE())-1) AS CHAR(4))
As an aside, with a little debugging 101, you could have discovered the issue for yourself immediately:
DECLARE #current_fiscal VARCHAR(32);
SET #current_fiscal = cast(dateadd(year,-1,year(getdate())) as varchar(4)) + '0702';
PRINT #current_fiscal;
Result:
--------
Jul 0702
Now, why is it doing that, you might ask? Let's inspect each part of the expression:
YEAR(GETDATE()) = 2014
DATEADD(YEAR,-1,2014) actually turns 2014 into a date, which is:
DATEADD(DAY, 2014, '19000101') = '1904-07-08'
Now, subtract a year from that, you get '1903-07-08'
Now, cast that as a varchar(32) without a style, you get:
SELECT CONVERT(VARCHAR(32), CONVERT(DATETIME,'1903-07-08'));
Which is Jul 8 1903 12:00AM
The first 4 characters are Jul and a space.
They screwed up the order of the function calls for pre-July. Given the level of this code, I suspect you're going to find other issues down the road. This should work, though:
declare #current_fiscal datetime
set #current_fiscal = case when (month(getdate()) < 7) then cast(year(dateadd(year,-1,getdate())) as varchar(4)) + '0702' else cast(year(getdate()) as varchar(4)) +'0702' end

SQL if statement returning incorrectly

So I have a stored procedure that is working except for how it calculates a certain field. On the tables worked with is a field called DeliveryYearMonth that is simply YYYYMM in its format. I try to compare current month info to previous month info, thus I created the following two variables.
DECLARE #CURDate VARCHAR(50) -- Current time (YYYYMM)
DECLARE #MAGDate VARCHAR(50) -- YearAgo Time (YYYYMM)
SET #CURDate = cast((select max(DeliveryYearMonth) from dbo.datatable) as varchar)
SET #MAGDate = cast((substring(#CURDate,1,4)) as varchar) --For current year
+ cast((substring(#CURDate,5,2) - 1) as varchar) -- To get previous month
This is all fine and dandy unless the the month is January, and thus the month would become 00, and the year would stay the same.
So I tried my hand at an if statement to clear this up.
if(substring(#MAGDate,5,2)) = '00'-- If current Month is January
begin
Set #MAGDate = cast((substring(#CURDate,1,4) - 1) as varchar) --For previous year
+ '12' -- December
end
This always breaks the Month Ago Date (#MAGDate) even if the IF statement isn't true. I cannot figure out why.
Thanks
To get the previous version of your string, you can do the following:
select replace(convert(varchar(7), dateadd(month, -1, CAST(#CURDate+'01' as DATE)), 121), '-', '')
As a comment suggested, though, you should really just store this as a date, assuming you are using SQL Server 2008 or more recent.