asked on
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION DaysBetweenInvoices
(
@Client_id int
)
RETURNS int
AS
BEGIN
DECLARE @Records int
DECLARE @Result int
DECLARE @FirstDate datetime
DECLARE @LastDate datetime
SET @LastDate = (SELECT MAX(mactemps.dbo.Order_Invoice.order_invoice_date)
FROM mactemps.dbo.Order_Invoice
WHERE mactemps.dbo.Order_Invoice.Client_id = @Client_id)
SET @Records = (SELECT COUNT(*) FROM mactemps.dbo.Order_Invoice WHERE mactemps.dbo.Order_Invoice.Client_id = @Client_id)
IF @Records = 1
BEGIN
Set @FirstDate = @LastDate
Set @LastDate = GetDate()
END
ELSE
SET @FirstDate = (SELECT MAX(mactemps.dbo.Order_Invoice.order_invoice_date)
FROM mactemps.dbo.Order_Invoice WHERE mactemps.dbo.Order_Invoice.Client_id = @Client_id AND mactemps.dbo.Order_Invoice.order_invoice_date < @LastDate)
SET @Result = DATEDIFF(d,@FirstDate,@LastDate)
-- Return the result of the function
RETURN @Result
END
GO
ASKER
Microsoft SQL Server 2005 is a suite of relational database management system (RDBMS) products providing multi-user database access functionality.Component services include integration (SSIS), reporting (SSRS), analysis (SSAS), data quality, master data, T-SQL and performance tuning. It includes support for managing XML data and allows a database server to be exposed over web services using Tabular Data Stream (TDS) packets encapsulated within SOAP (protocol) requests.
TRUSTED BY
you can do it with a simple sql statement
with cte as
(select row_number() over(partition by client_id order by order_invoice_date desc) as rown , order_invoice_date as dt , client_id
from order_invoice)
select client_id
from cte t1
inner join cte t2
on t1.rown = t2.rown + 1
where t1.rown = 1
and t2.rown = 2
and datediff(d, t1.order_invoice_date , t2.order_invoice_date ) > 100