我正在研究下面的SQL函数,但是无法弄清楚如何使代码条件WHERE根据标志(@PastDueFlag,0或1传递)工作。
请假设此功能内的整个查询工作正常。我想改变的唯一一行是在WHERE 1 = 1“AND DATEDIFF(”d“,InvoiceDueDate,GETDATE())> 0”下。
我喜欢在参数@PastDueFlag = 1时在查询中包含此条件,否则在WHERE查询中不包括此行。
有办法做到这一点吗?
谢谢,
ALTER FUNCTION [dbo].[TotalARDueByCompanyID]
(
-- Add the parameters for the function here
@CompanyID AS INTEGER,
@PastDueFlag AS INTEGER
)
RETURNS Float
AS
BEGIN
DECLARE @TotalARDue AS Float
SET @TotalARDue = (
SELECT SUM(CAST(GrandTotal AS NUMERIC(9,2)) + CAST(ISNULL(LinkedTxnAmount, 0) AS NUMERIC(9,2))) AS TotalARDue
FROM (
select i.OrderID, InvoiceID, cp.CustomerPO, o.CompanyID, i.CreditMemo
, CONVERT(VARCHAR(10),(InvoiceDate + (SELECT TermDays FROM dbo.ERP_CompanyTerms WHERE TermID = i.TermID)), 101) AS InvoiceDueDate
, (isnull(FreightCost,0) + isnull(TaxState,0) + isnull(TaxCounty, 0) + isnull(TaxCity, 0) )
+
(SELECT SUM(ExtQty * UnitSell) FROM ERP_InvoiceDetail WHERE invoiceID = i.InvoiceID) as GrandTotal
--, isnull(i.FreightCost, 0) as FreightCost, i.ShipVia, i.WhoPays, i.Status
, CONVERT(VARCHAR(10), i.CreatedDate, 101) AS CreatedDate
, CONVERT(VARCHAR(10), i.InvoiceDate, 101) AS InvoiceDate
, (select Name from ERP_Company c where c.CompanyID = o.CompanyID) as CompanyName
, (select first_name + ' ' + last_name from employee where tech_id = i.createdBy) as CreatedBy
, (SELECT em2.first_name + ' ' + em2.last_name) AS SalesRep
, (SELECT em2.tech_id) AS SalesRepID
, o.SOTypeInt AS SOType, em2.WH_RegionID AS Region, i.Status, qv.SFOppt
, (
SELECT
(SELECT CASE
WHEN CreditMemo = 1 THEN
SUM(qi.LinkedTxnAmount) * -1
ELSE
SUM(qi.LinkedTxnAmount)
END
)
FROM dbo.ERP_Invoice i2
LEFT JOIN dbo.QuickBooks_InvoiceLinked qi ON RefNumber = CAST(i2.InvoiceID AS VARCHAR(8))
WHERE 1 = 1
AND InvoiceID = i.invoiceID -- 305763, 304990
AND LinkedTxnTxnType <>
CASE
WHEN i2.CreditMemo = 1 THEN
'CreditMemo'
ELSE
''
END
GROUP BY CreditMemo
) AS LinkedTxnAmount
from ERP_Invoice i
LEFT JOIN ERP_Order o on o.OrderID = i.OrderID
INNER JOIN ERP_Company c on o.CompanyID = c.CompanyID
LEFT JOIN Employee em on em.Tech_ID = i.CreatedBy
LEFT JOIN Employee em2 ON em2.Tech_ID = o.SalesPersonID
LEFT JOIN ERP_QuoteVer qv ON qv.QuoteVerID = o.QuoteVerID
LEFT JOIN dbo.ERP_CustomerPO cp ON cp.CustomerPOID = i.CustomerPOID
where 1 = 1
) a
WHERE
1 = 1
AND DATEDIFF("d", InvoiceDueDate, GETDATE()) > 0
AND CAST(GrandTotal AS NUMERIC(9,2)) + CAST(ISNULL(LinkedTxnAmount, 0) AS numeric(9,2)) > 0
AND CompanyID = @CompanyID
AND Status in ('New', 'Completed')
AND SOType = 'Production'
)
-- Return the result of the function
RETURN @TotalARDue
END
答案 0 :(得分:0)
我认为您所要做的就是将参数值整合到where
子句中:
WHERE ( (@PastDueFlag =1 and DATEDIFF("d", InvoiceDueDate, GETDATE()) > 0) or
(@PastDueFlag = 0) ) and ...
另外,您的WHERE
子句