I am tring to add a year to a date if it is not before today. - sql

I am tring to add a year to a date if it is not before today. So in the statement below I would like to display 4/20/2018
declare #StartDate datetime
set #StartDate='4/20/2015'
select case when dateadd(year,1,#StartDate)> GETDATE() then
dateadd(year,1,#StartDate) else dATEADD(year,1,(datepart(year,GETDATE()))) end

I've changed the else clause so it works out the difference between the start date and today's date +1 to alter make '4/20/2015' become '4/20/2018'
declare #StartDate date
set #StartDate='4/20/2015'
select
case
when dateadd(year,1,#StartDate)> GETDATE() then dateadd(year,1,#StartDate)
else DATEADD(year,(datepart(year,GETDATE())+1-datepart(year,#StartDate)),#StartDate)
end
Also if you are not using the time part of a datetime data type it's best practice to use date instead as it only requires 3 bytes of storage rather than 8 for datetime.
More on date here: https://learn.microsoft.com/en-us/sql/t-sql/data-types/date-transact-sql
And a cheatsheet of sql data types here: https://sqlserverrider.files.wordpress.com/2013/04/pic116.png

Related

SQL Server end of month

Suppose there is one date in int format 20191229, I want to find end of month and check if it's end of month is of 31 days or 30 days in SQL Server
You can try this from the reference. The given answer will not work for the integer data type but it will work in the varchar datatype date value. Storing Date values in integer is not a good idea, so as suggested by Larnu change the data type in either date or varchar.
SELECT
Day(EOMONTH(Cast('20191229' as Date))) end_of_month;
If you want the amount of days within a month, as you need the days as an integer, you should go for this. This is the most robust built, but also the more complex one, as to make sure the Integer value is processed correctly:
SELECT DATEPART(DAY,EOMONTH(CAST(CAST('20191229' AS NCHAR(8)) AS DATE))) AS Days
Result:
Days
31
If you want to add an IF evaluation to your selected date(s), you can do this by add an IIF-clause where it evaluates whether or not the end of month is 31 or not. If you want to use a columnname instead of the date, just substitute #Date with the columnname. I've just added the variable #Date instead of '20191229' to make it more illustrative/understandable. You can change the True/false descriptions to whatever you like in the query.
DECLARE #Date AS int
SET #Date = '20191229'
SELECT
IIF (
DATEPART(DAY,EOMONTH(CAST(CAST(#Date AS NCHAR(8)) AS DATE))) = '31'
,'True'
,'False'
) AS Days
Output:
Days
True

SQL IF statement for todays date

I'm trying to create a condition for my SQL, that shows a 1 if that row reflects today's day.
case when A.EntryDate = GETDATE() then '1' else '0' end as Today
That's accepted but it doesn't show anything but zeros. I've only worked with Access SQL and this one seems to dislike Date()
I've been looking all around for answers and I cannot seem to find one.
The GetDate() method return datetime. To compare today's date you need to convert datetime to date.
case when cast(A.EntryDate as date) = cast(getdate() as date) then 1 else 0 end

Changing UTC Time to Local Time using scalar-valued function with Select statements SQL

I've been trying to get this work over two days and still stuck. Any assistance or tips would be greatly appreciated.
Creating a function for the date conversion:
CREATE FUNCTION LocalDateFromUTCTime
(
#UTCDateTime datetime
)
RETURNS datetime
BEGIN
DECLARE #diff int;
SET #diff = datediff(hh,GetUTCDate(), GetDate());
RETURN DATEADD(day, DATEDIFF(day, 0, DATEADD(hh, #diff, #UTCDateTime)),0);
END
Then select SQL statement I'm trying to use with the function above is below:
SELECT
o.Number AS 'Order#',
o.[guid] as 'guid',
dbo.LocalDateFromUTCTime(o.settlementdate) as 'closing date'
FROM pf.order o
doing this displays the settlement date with no timestamp.
2015-07-15 00:00:00.000
How could I change this to show the correct Local time?
Thanks
Your date conversion is specifically returning the difference in days. The dateadd is adding the number of days between date 0 (which is actually 01-01-1900) and your UTC date onto a different date 0. This means that the hours and minutes are completely ignored.
If you want to include the hours and minutes you just need to drop the dateadd(...datediff( part:
RETURN DATEADD(hh, #diff, #UTCDateTime)

SQL . The SP or function should calculate the next date for friday

I need to write a store procedure that will return a next friday date on a given date? for example - if the date is 05/12/2011, then it should return next friday date as 05/13/2011. If you pass, 05/16/2011, then it should return the date is 5/20/2011 (Friday). If you pass friday as the date, then it should return the same date.
I'd make this a scalar UDF as it is easier to consume the output.
CREATE FUNCTION dbo.GetNextFriday(
#D DATETIME
)
RETURNS DATETIME
WITH SCHEMABINDING, RETURNS NULL ON NULL INPUT
AS
BEGIN
RETURN DATEADD(DAY,(13 - (##DATEFIRST + DATEPART(WEEKDAY,#D)))%7,#D)
END
This is for SQL Server 2008. To use in 2005, just change the date fields to your preference for datetime to date conversions. It also assumes you are not changing the default week begin value.
DECLARE #PassedDate date = '5/21/2011';
SELECT DATEADD(DAY,(CASE DATEPART(DW,#PassedDate) WHEN 7 THEN 6 ELSE 6 - DATEPART(DW,#PassedDate) END),#PassedDate);
Similar to the top answer, but without using ##DATEFIRST in the solution:
DECLARE #Today DATETIME = GETDATE(); -- any date
DECLARE #WeekdayIndex SMALLINT = DATEPART(WEEKDAY, #Today);
DECLARE #DaysUntilFriday SMALLINT = (13 - #WeekdayIndex) % 7;
DECLARE #UpcomingFridayDate DATETIME = DATEADD(DAY, #DaysUntilFriday, #Today);
SELECT #UpcomingFridayDate ;
Great solutions here, but I also recommend looking at time tables: you can generate them easily in Analysis server, and they can be indexed to be very fast, giving you lots of easy ways to get next week days (among other things).
You can find out more about them here
In our case, the same solution would be
Select MIN(PK_Date) from Time Where PK_Date > #SomeDate AND Day_Of_Week= 6
And of course when you're doing this for a large recordset, you can also do joins for maximum speed & efficiency.

Limiting a date range with exactness in MS SQL / SQL Server 2005

I want to limit a report to return records from Date A through Date B. This is what I have been doing:
declare #startDate varchar(20)
declare #endDate varchar(20)
set #startDate = '01/01/2008'
set #endDate = '04/01/2008'
-- test what are the start and end dates
select min(date),max(date) from view_Inspections
where date between #startDate and #endDate
... which I was told returned records from 12 am Jan 1st through 11:59 pm March 31st (that midnight is the default when no time is indicated). But I noticed a discrepancy, which is if a record has a time of 00:00:00 that it will be part of this set.
Is there a more exact way of doing this so it will return exactly the date range I want?*
I tried using time:
declare #startDate varchar(20)
declare #endDate varchar(20)
set #startDate = '01/01/2008 00:00:00'
set #endDate = '04/01/2008 11:59:59'
-- test what are the start and end dates
select min(date),max(date) from view_Inspections
where date between #startDate and #endDate
... but I noticed something wonky: SQL Server will ROUND the hundreth-second up by half. So I get that April 1st record (ha! April Fool's record! grr) if I use any time later than 11:59:29. Why is that?
(I feel sure there is. I'm new at this. Thanks for your help!)
There's always the easy option:
declare #startDate varchar(20)
declare #endDate varchar(20)
set #startDate = '01/01/2008'
set #endDate = '04/01/2008'
-- test what are the start and end dates
select min(date),max(date) from view_Inspections
where date >= #startDate
and date < #endDate
I suspect that the date column in view_Inspections is a SmallDateTime data type. This data type has 1 minute accuracy, which explains your unexpected results (rounding the seconds to the nearest minute).
The method Roland Shaw suggests is the best way to modify your query to accommodate your requirements.
The BETWEEN operator is inclusive, which is why you're seeing the results that you are in your first query. The rounding that you're seeing in your second query is going to be dependent on what exact datetime data type you are using in your table. (BTW, I think you're confusing seconds with hundredths of seconds). It looks like you're probably using a smalldatetime in your table, in which case the time is rounded to the nearest minute.
If your table is using datetime, try explicitly converting your #startDate and #endDate to DATETIME values (CAST(#endDate AS DATETIME)).
A quick note... even for DATETIME values, SQL Server is only accurate to the 3/100ths of a second, so 11:59:59.999 will get rounded up to 12:00:00.000.
You basically have three choices:
1) BETWEEN CAST('01/01/2008 00:00:00.000' AS DATETIME) AND CAST('03/31/2008 12:59:59.997' AS DATETIME)
2) YEAR(my_date) = 2008 AND MONTH(my_date) BETWEEN 1 AND 3
3) my_date >= CAST('01/01/2008 00:00:00.000' AS DATETIME) AND my_date < CAST('04/01/2008 00:00:00.000' AS DATETIME)
The first method isn't very intuitive and is error-prone in my opinion. The second method kills performance since indexes can't be used and it becomes much more complex if you can have searches that span years or begin/end in the middle of months. The third method, which Rowland suggested, is the best I think.
Simply try removing the time from the date field like so:
declare #startDate varchar(20)
declare #endDate varchar(20)
set #startDate = '01/01/2008'
set #endDate = '04/01/2008'
SELECT min(date),max(date) FROM view_Inspections
WHERE CAST(FLOOR(CAST(date AS FLOAT)) AS DATETIME) BETWEEN CAST(#startDate AS DATETIME) And CAST(#startDate AS DATETIME))
This will return everything from 01/01/2008 00:00:00 to 04/01/2008 11:59:59.999.
If you don't want 04/01 included, change your end date to 03/31/2008.
Your best solution is just create a BIGINT(10) field that called "julian", and store it in YYYYMMDD.
Then do the query
where julian >= '20120103' AND julian <= '20120203'