How to properly write a SET DATE - sql

I'm creating a function were I provide 3 inputs #FiscalYEar, #StartDate, #EndDate, I also declare a DATE parameter that the year will be -1 of #FiscalYear
SET #fyLowerBound = OCT 1 OF (#FiscalYear - 1)
how do I properly write the SET statement to make it work?

This should work:
DECLARE #FiscalYear INT = 2014,
#fyLowerBound DATE;
SET #fyLowerBound = CAST(CAST((#FiscalYear - 1) AS CHAR(4)) + '1001' AS DATE)
SELECT #fyLowerBound;
This gives 1st October 2013.
The premise being creating a string date in the format yyyyMMdd, in SQL Server this is the only culture insensitive date for DATETIME (yyyy-MM-dd will work for DATE), you then cast that string to a date (or datetime whatever your preference).
So the first step is to turn your integer date into a CHAR(4), you can then create october 1st of this year by concatenating '1001'. You now have a string that will be cast to a date.

SET #fyLowerBound = DATEADD(yy, -1, #FiscalYear)
This will give you a date that's a year less than #FiscalYear. Although I'm not entirely sure this is what you need, given that 'OCT' in your original statement.

Related

How to subtract one month from a date using SQL Server

I have a date in format dd/mm/yyyy. I want to subtract one month from it.
I am using this code but the output is "09/10/2020" I don't know why my code does the subtraction of the year -2 also.
This is my request
SELECT
FORMAT(CONVERT (DATE, DATEADD(MONTH, -1, CONVERT(char(9), GETDATE()))), 'dd/MM/yyyy')
you need to change it to:
select format(CONVERT (date,DATEADD(MONTH, -1,GETDATE())), 'dd/MM/yyyy' )
but as Larnu stated. it seems like you need to change the column.
Your current code doesn't work as expected because:
SELECT CONVERT(char(9), GETDATE());
Returns this (at least in my language):
Nov 9 20
Which is, unfortunately, and again in my language, a valid date (but in {20}20, not {20}22).
Even in the right style (103), char(9) would yield 10/11/202 tomorrow, since 9 digits is only enough if either the day or month is a single digit.
Don't know why you are converting GETDATE() to a string. Just perform date math on it and then format it if you need to (using a specific style number, e.g. 103 for d/m/y):
SELECT CONVERT(char(10), DATEADD(MONTH, -1, GETDATE()), 103);
I really wouldn't use FORMAT() for such simple output, as the CLR overhead really isn't worth it. Ideally you leave it as a date/time type until presentation time - surely your presentation layer can present your date as d/m/y if that's really a wise idea.
And if you are storing or passing dates as strings (and worse, in regional formats like d/m/y) you really should consider fixing that.
First of all,
You should be storing your Date as a string for easier manipulation. If you don't want to change the column, you can always convert from Date to Varchar and then (re)convert it.
Example:
First, convert Date to varchar using the style code '112' ISO for formatting as yyyyMMdd:
DECLARE #date DATE = GETDATE();
DECLARE #dateConverted as VARCHAR (8) = (SELECT CONVERT(VARCHAR, #date, 112));
Then you just subtract the month using DATEADD():
DECLARE #previousMonth AS VARCHAR (8) = (SELECT FORMAT(DATEADD(month, -1, #dateConverted), 'yyyyMMdd'));
Finally, convert varchar do Date again:
DECLARE #previousMonthConverted AS DATE = (SELECT CONVERT(CHAR(10), CONVERT(date, #previousMonth), 120));

SQL Update query to replace last 4 characters in column

I am needing to replace the last four characters in a column.
It is currently a year in a char format and I need to replace with the current year.
The code I am using now is successful in removing the old year but is failing to input the new year that is needed.
My Current Code:
DECLARE #NewYear as Char
SELECT #NewYear = cast(YEAR(GETDATE()) as char(4))
UPDATE MyTable
SET ENDDATE = (substring(ENDDATE, -5, len(ENDDATE)) +#NewYear)
WHERE EndDate < StartDate
Original Value - 01/01/2017
Result - 01/01/
Desired Result - 01/01/2020
This is being used in SAS Proc SQl pass through - ANSI Standard SQL
Any help would be appreciated.
Thank you!
There is a problem in the declaration of your variable. It should be declared as char(4) - otherwise it defaults to char(1) and ends up with value '2' instead of 2020.
Also, you can use left instead o substring.
Here is one way to do it:
DECLARE #NewYear as Char(4)
SELECT #NewYear = CAST(YEAR(GETDATE()) as char(4))
UPDATE MyTable
SET ENDDATE = LEFT(ENDDATE , len(ENDDATE) - 4) + #NewYear
WHERE EndDate < StartDate
Note there is little benefit using a variable here. Very likely, the database will optimize the expression and not do the getdate()-based computation for each row.
UPDATE MyTable
SET ENDDATE = LEFT(ENDDATE , len(ENDDATE) - 4) + cast(YEAR(GETDATE()) as char(4))
WHERE EndDate < StartDate
I would suggest:
UPDATE MyTable
SET ENDDATE = STUFF(ENDDATE, 7, 4, DATENAME(year, GETDATE()))
WHERE EndDate < StartDate;
The WHERE clause makes no sense, because you are doing date comparisons.
Note that variables are not helpful here. You don't have to convert anything to a string, if you use DATENAME(), because it returns a string.
I thought for a moment they might be stored as dates, but you would never get 01/01/ as a valid date.

Error converting data type varchar to date converting an int year into a string

I have SchoolYear variable as an INT, and I'm trying to set a variable to this:
SET #BeginDate = '07/01/' + CONVERT(VARCHAR(4), #SchoolYear - 1)
It gives me the 'Error converting data type varchar to date' error.
Example:
#SchoolYear INT = 2019,
#BeginDate Date - NULL
Desired result:
07/01/2018
What am I doing wrong please?
Check out DATEFROMPARTS (available from SQL 2012), and bypass strings altogether.
SET #BeginDate = DATEFROMPARTS(#SchoolYear - 1, 1, 7)
1st arg = year, 2nd = month, 3rd = day.
The format you are using is simply not understood by your sql server.
When dealing with dates in varchar columns/variables it is best to use a date format that is language neutral.
yyyyMMdd is such a format, it will always work no matter what regional settings are used on your server.
See also this http://karaszi.com/the-ultimate-guide-to-the-datetime-datatypes
in your case you should use
SET #BeginDate = CONVERT(VARCHAR(4), #SchoolYear - 1) + '0107'
that is assuming that 01 is the month, and 07 is the day so you end up with 20180107
Better would be off course to avoid varchar complete when converting, like this
set #BeginDate = DATEFROMPARTS(#SchoolYear - 1, 1, 7)
Maybe you should use the yyyy-mm-dd format and change the set as:
SET #BeginDate = CONVERT(VARCHAR(4), #SchoolYear - 1)+ '-01-07'
Declare #SchoolYear int
Set #SchoolYear = 2019
Declare #BeginDate varchar(50)
SET #BeginDate = '07/01/' + CONVERT(VARCHAR(4), #SchoolYear - 1)
--Once You have you varchar populated, you can use Convert Function to convert
--to datetime and select the format you want
Select CONVERT (Datetime,#BeginDate, 101)

Format varchar type and convert it to date variable

I have a varchar value in this format “YYYYMM-LL” where: YYYY is four digit year; MM is two digit month.LL is two digit length of reporting period. This is the number of whole months included in the calculations (from first to last day of each month).
My questions is how I could use this varchar value to decide two variables:#First_Date and #Last_Date.
Example: 201409-06
This scenario is for the six months ending in September of 2014.
The range of calendar dates in this scenario is 04/01/2014 through 09/30/2014.
So how could I use t-sql to find this two dates #First_Date : 04/01/2014 and #Last_Date: 09/30/2014.
Any help would be really appreciated!
You can do something like this:
select #firstdate = dateadd(month, 1 - cast(right('201409-06', 2) as int),
convert(date, left('201409-06', 6) + '01')
),
#lastdate = dateadd(day, -1,
dateadd(month, 1,
convert(date, left('201409-06', 6) + '01')
)
)
This parses the string to do the date arithmetic that you want. SQL Server recognizes a string in the form of "YYYYMMDD" as a date, regardless of internationalization settings.
And a SQL Fiddle.

How to get month/day to compare with another month/day without year

I need to select month/day to compare with another month/day to determine which day is greater. For example, to compare 2/28 with 3/18. What would be the date format I can use to compare the days.
In SQL Server, you can convert dates to strings using the convert function:
https://msdn.microsoft.com/en-us/library/ms187928.aspx
The format you want to use is mm/dd/yy, which is style 1 on the convert function. Then you can simply take the left 5 characters:
select left(convert(char(8),YourDate,1),5) as mm_dd
If you're only trying to display the month and day, you can use this:
DECLARE #myDate DATETIME2 = '02/28/2015'
SELECT CAST(MONTH(#myDate) AS VARCHAR(2)) + '/' + CAST(DAY(#myDate) AS VARCHAR(2))
SELECT LEFT(CONVERT(VARCHAR,#DATE,1),5)
You can use the format function?
select format(getdate(),'dd/MM')
Try using the DATEPART function to get the day of year for your dates.
DECLARE #StartDate DATETIME = '20150130';
DECLARE #EndDate DATETIME = '20141225';
SELECT
#StartDate AS StartDate,
DATEPART(DY, #StartDate) AS StartDy,
#EndDate AS EndDate,
DATEPART(DY, #EndDate) AS EndDy;