Loop through range of dates in SQL Server - sql-server

I have a stored procedure that looks like :
CREATE procedure [dbo].[SP_EXEC]
AS
DECLARE #DATE AS varchar(50)
SET #DATE = (SELECT TOP(1) CONVERT(VARCHAR, YEAR(DATEADD(MM, DATEDIFF(MM, '01/01/2000', DATEADD(MM, -1, GETDATE())), '01/01/2000'))) + RIGHT('00'+ CONVERT(VARCHAR, MONTH(DATEADD(MM, DATEDIFF(MM, '01/01/2000', DATEADD(MM, -1, GETDATE())), '01/01/2000'))), 2) + RIGHT('00' + CONVERT(VARCHAR, DAY(DATEADD(MM, DATEDIFF(MM, '01/01/2000', DATEADD(MM, -1, GETDATE())), '01/01/2000'))), 2)
FROM produit)
EXEC SP_DELETE_lIGNE_MOIS_EN_COURS #DATE
The stored procedure works fine, my goal is to do a loop of a range of date from 2012/03/01 to the current date. How to update my stored procedure to do an update on history ?

There's really not enough information here to be sure what you need... but first few observations:
You have a select top 1 from a table, but you're not selecting anything from it
You have quite complex select, which looks like it's the same as this:
convert(dateadd(month, DATEDIFF(month, 0, getdate()), 0), 112)
Which is the first day of current month in YYYYMMDD format
You're assigning that to a varchar(50) -- and passing as a parameter to a procedure. Is the procedure actually using a date or datetime for this?
So, my guess is that you actually need this:
declare #date date
set #date = '20120301'
while (#date < getdate()) begin
exec SP_DELETE_lIGNE_MOIS_EN_COURS #date
set #date = dateadd(month, 1, #date)
end

Related

Generate a stock position report as at each month with a date variable set at a specific month

I am trying to generate a stock position report as at each month. within my query i have a date variable set at a specific month:
declare #date datetime = CONVERT(DATETIME, '2019-08-13 00:00:00', 121)
declare #lastmonth datetime = (select cast(dateadd(day, -day(getdate()), getdate()) as date))
declare #m int = 0
--**my aim is to ensure that #date = #lastmonth**
while #date<= #lastmonth
Begin
set #m = #m + 1
while #m < 12
Begin
set #date = (select dateadd(mm, #m, #date))
End
End
select

sql two monday night between

I have a problem about sql query. Now I have GETDATE() FOR example today is wednesday, I need to have date between tho monday nights. and GETDATE() will be in this two date
Example today is thursday 18.05.2017 I want date between 15.05.2017 and 22.05.2017
I couldn't find any solution. How can I write it in where statement in query.
SELECT * FROM MATCHES
WHERE ...
Thanks in advance
To receive first monday:
SELECT DATEADD(ww, DATEDIFF(ww,0,GETDATE()), 0)
and second one:
SELECT DATEADD(ww, DATEDIFF(ww,0,GETDATE()) + 1, 0)
http://joelabrahamsson.com/getting-the-first-day-in-a-week-with-t-sql/
also
Get first day of week in SQL Server
here is the solution
firstly create a calendar table then
declare #startDate datetime = dateadd(week, datediff(week, 0, getdate()), 0);
declare #endDate datetime = DATEADD(DAYS,7,#startDate)
SELECT Date
FROM dbo.Calendar
WHERE Date >= #startDate
AND Date < #endDate ;
Create a Calendar Table if not exists
IF EXISTS (SELECT * FROM information_schema.tables WHERE Table_Name =
'Calendar' AND Table_Type = 'BASE TABLE')
BEGIN
DROP TABLE [Calendar]
END
CREATE TABLE [Calendar]
(
[CalendarDate] DATETIME
)
DECLARE #StartDate DATETIME
DECLARE #EndDate DATETIME
SET #StartDate = GETDATE()
SET #EndDate = DATEADD(d, 365, #StartDate)
WHILE #StartDate <= #EndDate
BEGIN
INSERT INTO [Calendar]
(
CalendarDate
)
SELECT
#StartDate
SET #StartDate = DATEADD(dd, 1, #StartDate)
END
Then, Use below query to get the output
declare #start datetime = dateadd(week, datediff(week, 0, getdate()), 0);
declare #end datetime = DATEADD(DAY,8,#start)
SELECT [CalendarDate]
FROM Calendar
WHERE CalendarDate BETWEEN #start AND #end

Convert nvarchar to datetime sql server

I try to convert 2016/07/15 (nvarchar format) to this datetime format 2016-07-15 00:00:00 in sql server. But i need the time part to be the current time. can any one help ?
This is my sp:
declare #DateTime varchar(50)
set #DateTime = '2016/07/15'
select convert(varchar, cast(#DateTime as datetime), 120)
You can use this:
declare #DateTime varchar(50)
set #DateTime = CONCAT('2016/07/15' , ' ', CONVERT(TIME, GETDATE()))
select #DateTime
select convert(varchar, cast(#DateTime as datetime2(7)), 120)
Or replace the CONCAT with:
set #DateTime = '2016/07/15' + ' ' + CONVERT(NVARCHAR(50), CONVERT(TIME, GETDATE()))
Try this...
Just concat time with your output
declare #DateTime varchar(50)
set #DateTime = '2016/07/15'
select convert(varchar, cast(#DateTime as datetime), 101) + ' ' + CONVERT(varchar, getdate(),108)
Try like this,
DECLARE #DateTime VARCHAR(50)
SET #DateTime = '2016/07/15'
SELECT DATEADD(day, 0, DATEDIFF(day, 0, #DateTime)) + DATEADD(day, 0 - DATEDIFF(day, 0, getdate()), getdate())

T-SQL Date Difference for WeekDays only

I am trying to get the date difference in a given date excluding the week days.
Here is what I have:
SELECT DATEADD (w, -4, GETDATE())
This returns 2013-05-04 19:01:53.170, which means that it also counts weekends.
Same for
SELECT DATEADD (dw, -4, GETDATE())
Any help will be appreciated.
Thanks in advance.
I'm using these functions that return the non-weekend seconds between two dates:
CREATE FUNCTION [dbo].[DateDiff_NoWeekends](
#date1 DATETIME,
#date2 DATETIME
)
RETURNS INT AS BEGIN
DECLARE #retValue INT
SET #date1 = dbo.__CorrectDate(#date1, 1)
SET #date2 = dbo.__CorrectDate(#date2, 0)
IF (#date1 >= #date2)
SET #retValue = 0
ELSE BEGIN
DECLARE #days INT, #weekday INT
SET #days = DATEDIFF(d, #date1, #date2)
SET #weekday = DATEPART(dw, #date1) - 1
SET #retValue = DATEDIFF(s, #date1, #date2) - 2 * 24 * 3600 * ((#days + #weekday) / 7)
END
RETURN #retValue
END
GO
CREATE FUNCTION [dbo].[__CorrectDate](
#date DATETIME,
#forward INT
)
RETURNS DATETIME AS BEGIN
IF (DATEPART(dw, #date) > 5) BEGIN
IF (#forward = 1) BEGIN
SET #date = #date + (8 - DATEPART(dw, #date))
SET #date = DateAdd(Hour, (8 - DatePart(Hour, #date)), #date)
END ELSE BEGIN
SET #date = #date - (DATEPART(dw, #date)- 5)
SET #date = DateAdd(Hour, (18 - DatePart(Hour, #date)), #date)
END
SET #date = DateAdd(Minute, -DatePart(Minute, #date), #date)
SET #date = DateAdd(Second, -DatePart(Second, #date), #date)
END
RETURN #date
END
Here's a sql-fiddle demo for all non-weekend days in april (22).
SELECT [no weekend days in april] =
(dbo.DateDiff_NoWeekends('2013-04-01','2013-05-01')
/ 3600 / 24)
The query below gives the difference for week days alone , Ie counts the no od days between two days and subtracts the no of weekend days ,
DECLARE #StartDate DATETIME,
#EndDate DATETIME
SELECT #StartDate = '01-July-2008',
#EndDate = '30-July-2008'
;WITH DATE (Date1)
AS (
SELECT DATEADD(DAY, DATEDIFF(DAY, '19000101', #StartDate), '19000101')
UNION ALL
SELECT DATEADD(DAY, 1, Date1)
FROM DATE
WHERE Date1 < #EndDate
)
SELECT count(*) -
(
SELECT count(*)
--CONVERT(VARCHAR(15),d1.DATE1 ,110) as [Working Date],
--DATENAME(weekday, d1.Date1) [Working Day]
from DATE d1 where (DATENAME(weekday, d1.Date1)) in ('Saturday','Sunday')
)
--CONVERT(VARCHAR(15),d1.DATE1 ,110) as [Working Date],
--DATENAME(weekday, d1.Date1) [Working Day]
from DATE d1 where (DATENAME(weekday, d1.Date1)) not in ('Saturday','Sunday')
please let me know for any clarifications
Maybe I am still missing some full testing, but this works for me too: take the difference in days and then subtract 2 days for each weekend
DateDiff(d, d1, d2) - 2*DateDiff(wk, d1, d2)
Could be put in a function as well

Get only the Date part of DateTime in mssql [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Get just the Date from grouping in select from DateTime column in SQL Server
How can I get only the Date part of a DateTime ? I'm searching for something like year() function but for the whole date.
This may also help:
SELECT convert(varchar, getdate(), 100) -- mon dd yyyy hh:mmAM (or PM)
-- Oct 2 2008 11:01AM
SELECT convert(varchar, getdate(), 101) -- mm/dd/yyyy - 10/02/2008
SELECT convert(varchar, getdate(), 102) -- yyyy.mm.dd – 2008.10.02
SELECT convert(varchar, getdate(), 103) -- dd/mm/yyyy
SELECT convert(varchar, getdate(), 104) -- dd.mm.yyyy
SELECT convert(varchar, getdate(), 105) -- dd-mm-yyyy
SELECT convert(varchar, getdate(), 106) -- dd mon yyyy
SELECT convert(varchar, getdate(), 107) -- mon dd, yyyy
SELECT convert(varchar, getdate(), 108) -- hh:mm:ss
SELECT convert(varchar, getdate(), 109) -- mon dd yyyy hh:mm:ss:mmmAM (or PM)
-- Oct 2 2008 11:02:44:013AM
SELECT convert(varchar, getdate(), 110) -- mm-dd-yyyy
SELECT convert(varchar, getdate(), 111) -- yyyy/mm/dd
SELECT convert(varchar, getdate(), 112) -- yyyymmdd
SELECT convert(varchar, getdate(), 113) -- dd mon yyyy hh:mm:ss:mmm
-- 02 Oct 2008 11:02:07:577
SELECT convert(varchar, getdate(), 114) -- hh:mm:ss:mmm(24h)
SELECT convert(varchar, getdate(), 120) -- yyyy-mm-dd hh:mm:ss(24h)
SELECT convert(varchar, getdate(), 121) -- yyyy-mm-dd hh:mm:ss.mmm
SELECT convert(varchar, getdate(), 126) -- yyyy-mm-ddThh:mm:ss.mmm
-- 2008-10-02T10:52:47.513
-- SQL create different date styles with t-sql string functions
SELECT replace(convert(varchar, getdate(), 111), '/', ' ') -- yyyy mm dd
SELECT convert(varchar(7), getdate(), 126) -- yyyy-mm
SELECT right(convert(varchar, getdate(), 106), 8) -- mon yyyy
The Source
The solution you want is the one proposed here:
https://stackoverflow.com/a/542802/50776
Basically, you do this:
cast(floor(cast(#dateVariable as float)) as datetime)
There is a function definition in the link which will allow you to consolidate the functionality and call it anywhere (instead of having to remember it) if you wish.
Another nifty way is:
DATEADD(dd, 0, DATEDIFF(dd, 0, [YourDate]))
Which gets the number of days from DAY 0 to YourDate and the adds it to DAY 0 to set the baseline again. This method (or "derivatives" hereof) can be used for a bunch of other date manipulation.
Edit - other date calculations:
First Day of Month:
DATEADD(mm, DATEDIFF(mm, 0, getdate()), 0)
First Day of the Year:
DATEADD(yy, DATEDIFF(yy, 0, getdate()), 0)
First Day of the Quarter:
DATEADD(qq, DATEDIFF(qq, 0, getdate()), 0)
Last Day of Prior Month:
DATEADD(ms, -3, DATEADD(mm, DATEDIFF(mm, 0, getdate()), 0))
Last Day of Current Month:
DATEADD(ms, -3, DATEADD(mm, DATEDIFF(m, 0, getdate()) + 1, 0))
Last Day of Current Year:
DATEADD(ms, -3, DATEADD(yy, DATEDIFF(yy, 0, getdate()) + 1, 0))
First Monday of the Month:
DATEADD(wk, DATEDIFF(wk, 0, DATEADD(dd, 6 - DATEPART(day, getdate()), getdate())), 0)
Edit:
True, Joe, it does not add it to DAY 0, it adds 0 (days) to the number of days which basically just converts it back to a datetime.
We can use this method:
CONVERT(VARCHAR(10), GETDATE(), 120)
Last parameter changes the format to only to get time or date in specific formats.
This may not be as slick as a one-liner, but I use it to perform date manipulation mainly for reports:
DECLARE #Date datetime
SET #Date = GETDATE()
-- Set all time components to zero
SET #Date = DATEADD(ms, -DATEPART(ms, #Date), #Date) -- milliseconds = 0
SET #Date = DATEADD(ss, -DATEPART(ss, #Date), #Date) -- seconds = 0
SET #Date = DATEADD(mi, -DATEPART(mi, #Date), #Date) -- minutes = 0
SET #Date = DATEADD(hh, -DATEPART(hh, #Date), #Date) -- hours = 0
-- Extra manipulation for month and year
SET #Date = DATEADD(dd, -DATEPART(dd, #Date) + 1, #Date) -- day = 1
SET #Date = DATEADD(mm, -DATEPART(mm, #Date) + 1, #Date) -- month = 1
I use this to get hourly, daily, monthly, and yearly dates used for reporting and performance indicators, etc.

Resources