Add days in date in yyyymmdd format SQL server - sql

I have a hard-coded date in a variable in yyyymmdd format
DECLARE #StartDate = 20160101;
Now I want to add 365 days in this date.
When I do this 20160101 + 365, it gives incorrect output 20160466, it should give me answer after adding 365 days which I think is 20160102
Please tell me how to do it in SQL server in DECLARE variable ? I want output in yyyymmdd format
Thanks,
Aiden

DECLARE #StartDate INT = '20161117';
select convert(varchar,CONVERT(datetime,convert(char(8),#StartDate))+365,112)

Put the date in quotes and then use DATEADD:
DECLARE #StartDate = '2016-01-01';
SELECT DATEADD (day, 365, #StartDate)
FROM yourTable

DECLARE #Date DATE= '20160101'SELECT DATEADD(DAY,365,#Date)
FOR INT DATA TYPE :
DECLARE #Date INT = '20160101'
SELECT DATEADD(DAY,365,CONVERT (DATETIME,CONVERT(CHAR(8),#Date)))

DECLARE #StartDate INT = 20161117;
select cast(convert(varchar,cast(cast(#StartDate as varchar) as datetime)+366,112) as INT)

Related

Date losing value when being stored

I'm trying to get a set of dates into a particular format (ddmmyy) so that they can be run against a number of scripts that I have.
I have managed to convert the date into the correct format, but when I try to store this as a variable it just returns as null or the un-formatted date.
DECLARE #CurrentDate SMALLDATETIME
SELECT #CurrentDate = getdate()
SELECT #CurrentDate = DATEADD(day, -1, #CurrentDate)
SELECT #CurrentDate = STR_REPLACE(CONVERT(varchar,#CurrentDate,3),'/',null)
--Returns this:
20-Mar-2002 00:00:00
DECLARE #CurrentDate SMALLDATETIME
SELECT #CurrentDate = getdate()
SELECT #CurrentDate = DATEADD(day, -1, #CurrentDate)
SELECT STR_REPLACE(CONVERT(varchar,#CurrentDate,3),'/',null)
--Returns this:
020320
I believe the problem comes from the fact that my declared variable is a smalldatetime object but I'm not sure of how to convert it correctly into a string that can be stored as a variable?
I've tried having a second variable and declaring it as a varchar and then storing my date as the varchar but this isn't working either:
DECLARE #CurrentDate SMALLDATETIME
DECLARE #CurrentDateFinal VARCHAR
SELECT #CurrentDate = getdate()
SELECT #CurrentDate = DATEADD(day, -1, #CurrentDate)
SELECT #CurrentDateFinal = CAST(STR_REPLACE(#CurrentDate,'/',null) AS VARCHAR)
--Returns this:
03-Mar-2020 00:00:00
You can do the current date amendment with the dateadd all in one line - there's no need to do two lines. The below gives you the DDMMYY output although I wouldn't use that format personally as you can come unstuck with regional differences (e.g. US prefer MMDDYY and UK tends to be DDMMYY). Also always use 4 digit years IMO.
DECLARE #FirstDate SMALLDATETIME
DECLARE #FinalDate varchar(20)
SELECT #FirstDate = DATEADD(day, -1,getdate())
set #FinalDate = STR_REPLACE(CONVERT(varchar,#FirstDate,3),'/',null)
SELECT #FinalDate
--------------------
030320
(1 row affected)

How to write sql query for adding days given by the user to the current date where current date and days to be added need to be taken as parameters

DECLARE #currDate DATETIME
DECLARE #days INT
SELECT DATEADD(dd ,#days ,#currDate)
WHERE #days = 10
AND #currDate = GETDATE()
Assuming SQLServer, this will add 1 day to current date. You can apply further functions to extract only date part etc.
SELECT DATEADD(day, 1, current_timestamp);
Replace current_timestamp with any other date you want.
SQLFiddle example here
It is so simple as below,
DECLARE #days AS INT=10
DECLARE #currDate AS DATE=GETDATE()
SELECT DATEADD(DAY ,#days ,#currDate) AS AddedDate

How to get dates between time range in sql server

I need to write a stored procedure in which i will get begin date and end date. for eg: start date is 05/07/2015 and end date is 28/08/2015. I need to write a query which will fetch details between 01/07/2015 and 31/08/2015. It should fetch details between 1st day of month selected for begin date and last day of month selected for end date.
This is what I tried, but it isn't working:
DATEDIFF(month,'2014-06-05','2014-08-05')
You can compare the dates using the common operators "<" and ">",
Example:
select * from table_name where '2014-06-05' < datefield and datefield < '2014-08-05'
DECLARE #StartDate DATETIME
DECLARE #EndDate DATETIME
SET #StartDate = convert(DATE, '20140705' ,112)
SET #EndDate = convert(DATE, '20140828' ,112)
SELECT * FROM [TableName] WHERE [TableName].DateField BETWEEN
dateadd(d,-(datepart(d, #StartDate)-1),#StartDate) AND
dateadd(d,-1,dateadd(m,1, dateadd(d,-(datepart(d, #EndDate)-1),#EndDate)))
It sounds like you need to find the first day of the month for '05/07/2015' and the last day of the month for '28/08/2015', then use those as the limits for your where clause.
This will easily convert a date to the first of the month:
declare #firstDate datetime = '2015-07-05'
declare #firstOfMonth datetime = dateadd(month,datediff(month,0,#firstDate),0)
select #firstDate
-- returns '2015-07-01 00:00:00.000'
To get to the last day of a month, use this:
declare #lastDate datetime = '2015-08-28'
declare #lastOfMonth datetime = dateadd(second,-1,dateadd(month,datediff(month,0,#lastDate)+1,0))
select #lastOfMonth
-- returns '2015-08-31 23:59:59.000'

How to add 1 day to current date and have result in format yyyymmdd in SQL Server?

I need to add 1 day to the current date and have the output in the format yyyymmdd.
The code needs to be written on a stored procedure on the sql server.
currently my code is as follows:
DECLARE #dat DATE
select #dat = dateadd(DD, 1, getdate())
SELECT #dat =LEFT(CONVERT(VARCHAR(8), #dat, 112),10)
However, it seems like im doing something wrong as my output on the sql table is in the format yyyy-mm-dd. I need to get rid of the hyphens.
any suggestions guys? thanks in advance.
The issue is that you are assigning it back to a date object. You need to assign it to a varchar.
I did the following in SQL Server 2005:
DECLARE #dat DATETIME
DECLARE #string varchar(8)
SET #dat = GetUtcDate()
select #dat = dateadd(DD, 1, getdate())
SELECT #string =CONVERT(VARCHAR(8), #dat, 112)
PRINT #string
Change the declaration of #dat to a STRING
Try this one -
DECLARE #date VARCHAR(8)
SELECT #date = CONVERT(VARCHAR(8), DATEADD(DAY, 1, GETDATE()), 112)
SELECT #date
select #dat = dateadd(DD, 1, getdate())
DECLARE #datCus varchar(8)
select #datCus=LEFT(CONVERT(VARCHAR(8), #dat, 112),10)
The problem was that i assigned #dat to the insert statements values. However having a varchar variable to handle the converting part solved the problem (in this case #datCus).

Best way to compare dates without time in SQL Server

select * from sampleTable
where CONVERT(VARCHAR(20),DateCreated,101)
= CONVERT(VARCHAR(20),CAST('Feb 15 2012 7:00:00:000PM' AS DATETIME),101)
I want to compare date without time
Is above query is ok? or other better solution you suggest
I am using SQL Server 2005
Date saved in UTC format on server
Users against this data belongs different timezone
Simple Cast to Date will resolve the problem.
DECLARE #Date datetime = '04/01/2016 12:01:31'
DECLARE #Date2 datetime = '04/01/2016'
SELECT CAST(#Date as date)
SELECT CASE When (CAST(#Date as date) = CAST(#Date2 as date)) Then 1 Else 0 End
Don't use convert - that involves strings for no reason. A trick is that a datetime is actually a numeric, and the days is the integer part (time is the decimal fraction); hence the day is the FLOOR of the value: this is then just math, not strings - much faster
declare #when datetime = GETUTCDATE()
select #when -- date + time
declare #day datetime = CAST(FLOOR(CAST(#when as float)) as datetime)
select #day -- date only
In your case, no need to convert back to datetime; and using a range allows the most efficent comparisons (especially if indexed):
declare #when datetime = 'Feb 15 2012 7:00:00:000PM'
declare #min datetime = FLOOR(CAST(#when as float))
declare #max datetime = DATEADD(day, 1, #min)
select * from sampleTable where DateCreated >= #min and DateCreated < #max
SELECT .......
FROM ........
WHERE
CAST(#DATETIMEVALUE1 as DATE) = CAST(#DATETIMEVALUE2 as DATE)
The disadvantage is that you are casting the filter column.
If there is an index on the filter column, then, since you are casting, the SQL engine can no longer use indexes to filter the date more efficiently.
Description
Don't convert your Date to a varchar and compare because string comparisson is not fast.
It is much faster if you use >= and < to filter your DateCreated column.
If you have no parameter (like in your sample, a string) you should use the ISO Format <Year><Month><Day>.
Sample
According to your sample
DECLARE #startDate DateTime
DECLARE #endDate DateTime
SET #startDate = '20120215'
SET #endDate = DATEADD(d,1,#startDate)
SELECT * FROM sampleTable
WHERE DateCreated >= #startDate AND DateCreated < #endDate
More Information
MSDN - DATEADD (Transact-SQL)
Use 112 CONVERT's format
select *
from sampleTable
where
CONVERT(VARCHAR(20),DateCreated,112)
= CONVERT(VARCHAR(20),CAST('Feb 15 2012 7:00:00:000PM' AS DATETIME),112)
or
if your sql server version 2008+ use DATE type
select * from sampleTable
where CONVERT(DATE,DateCreated)
= CONVERT(DATE,CAST('Feb 15 2012 7:00:00:000PM' AS DATETIME))
declare #DateToday Date= '2019-10-1';
print #DateToday;
print Abs(datediff(day, #DateToday,CAST('oct 1 2019 7:00:00:000PM' AS DATETIME))) < 3
this is compare whin 3 days.
i test this on SQL Server 2014, it works.
select * from sampleTable
where date_created ='20120215'
This will also compare your column with the particular date
without taking time into account