Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Endless Query with Custom Functiom

Author  Topic 

roberto.armenta
Starting Member

2 Posts

Posted - 2015-04-11 : 18:02:36
I created a function to use in a View, works similar to DATEADD but only with my company's Business days Monday-Thursday.

I am running a query but it never ends to run.

This is the function:


USE [RA_dev]
GO
/****** Object: UserDefinedFunction [Production].[GBDATEADD] Script Date: 4/11/2015 5:58:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Roberto Armenta
-- Create date: 4/11/2015
-- Description: Gulfstream Business Date Add
-- =============================================

ALTER FUNCTION [Production].[GBDATEADD]
(
@FromDate datetime,
@DaysToAdd int
)

RETURNS datetime
AS
BEGIN

DECLARE @Result datetime
DECLARE @Counter as int
DECLARE @DayEvaluated as datetime

SET @DayEvaluated = DATEADD(Day,1,@FromDate)

SET @COUNTER = 0

WHILE @Counter < @DaysToAdd

BEGIN

SET @COUNTER = @COUNTER +

CASE DATEPART(WEEKDAY,@DayEvaluated)
WHEN 2 THEN 1
WHEN 3 THEN 1
WHEN 4 THEN 1
WHEN 5 THEN 1
ELSE 0
END

IF CASE DATEPART(WEEKDAY,@DayEvaluated)
WHEN 2 THEN 1
WHEN 3 THEN 1
WHEN 4 THEN 1
WHEN 5 THEN 1
ELSE 0
END = 1

BEGIN
SET @Result = @DayEvaluated
END

SET @DayEvaluated = DATEADD(Day,1,@DayEvaluated)

END

RETURN @Result

END


This is how I am trying to use it in the View:


Production.GBDATEADD(Production.Schedule.START_DATE, Production.Operations_Data_Pool.MFG_DAY - 1) AS SCH_DATE


Please I would appreciate anyone's help.

Best Regards,

Roberto Armenta
Industrial Engineer
Advanced Aircraft Programs
Gulfstream Aerospace Corporation
roberto.armenta@gulfstream.com

bitsmed
Aged Yak Warrior

545 Posts

Posted - 2015-04-11 : 20:01:16
Try this:
declare @Result datetime;
set @Result=dateadd(dd
,case datepart(dw,@FromDate)
when 1 then 1
when 6 then 3
when 7 then 2
else 0
end
+7*floor(@DaysToAdd/4)
,@FromDate
);
set @Result=dateadd(dd
,case datepart(dw,@Result)+@DaysToAdd%4
when 6 then 3
when 7 then 3
when 8 then 3
else 0
end
+@DaysToAdd%4
,@Result
);
return @Result;
Go to Top of Page

roberto.armenta
Starting Member

2 Posts

Posted - 2015-05-08 : 09:20:10
Thank You sir.

Worked like a charm.

Best Regards,

Roberto Armenta
Industrial Engineer
Advanced Aircraft Programs
Gulfstream Aerospace Corporation
roberto.armenta@gulfstream.com
Go to Top of Page
   

- Advertisement -