使用IF语句来决定执行哪个where子句

时间:2016-02-03 22:58:39

标签: sql-server sql-server-2008 tsql

我正在使用SQL Server 2008.我正在尝试根据WHERE语句决定运行哪个IF语句。这可能不是解决这个问题的正确方法,老实说我不确定。到目前为止,这是我的代码:

SELECT A.[ArTrnDetail].[Invoice]
      ,cast(A.[ArTrnDetail].[InvoiceDate] AS DATE) AS InvoiceDate
      ,A.[ArTrnDetail].[Branch]
      ,A.[ArTrnDetail].[Salesperson]
      ,rtrim(A.[ArTrnDetail].[Customer]) AS Customer
      ,rtrim(A.[ArTrnDetail].[StockCode]) AS StockCode
      ,A.[ArTrnDetail].[QtyInvoiced]
      ,A.[ArTrnDetail].[NetSalesValue]
      ,A.[ArTrnDetail].[SalesOrder]
      ,rtrim(A.[ArTrnDetail].[CustomerPoNumber]) AS CustomerPO
      ,cast(B.[EarliestSalesSeries].[InvoiceDate] as DATE) AS EarliestDate
      ,DATEADD(year, 1, B.[EarliestSalesSeries].[InvoiceDate]) as LatestDate
      ,A.[InvMaster].[Description]
      ,LEFT(A.[InvMaster].[UserField2], 3) AS SalesSeries
      ,DATEDIFF(DAY,B.[EarliestSalesSeries].[InvoiceDate], @enddate) as DateDifference	  
    FROM A.[ArTrnDetail]
    JOIN A.[InvMaster] ON A.[ArTrnDetail].StockCode
    = A.[InvMaster].[StockCode]
    JOIN B.[EarliestSalesSeries] ON A.[InvMaster].[UserField2]
    = B.[EarliestSalesSeries].SalesSeries

我在SELECT之前在代码的开头定义了@firstYearDay。

我需要这样做:

IF LatestDate> @enddate然后运行where where子句:

   WHERE (A.[ArTrnDetail].[InvoiceDate] between @firstYearDay and @enddate)
	AND (DATEDIFF(YEAR,B.[EarliestSalesSeries].[InvoiceDate], @enddate) < 1)

ELSE IF LatestDate&lt; @enddate然后运行where where子句:

   WHERE (A.[ArTrnDetail].[InvoiceDate] between @firstYearDay and LatestDate)
	AND (DATEDIFF(YEAR, B.[EarliestSalesSeries].[InvoiceDate], @firstYearDay) < 1)

如果您需要更多信息,请与我们联系。我是stackoverflow的新手,所以请问!谢谢你的帮助。

2 个答案:

答案 0 :(得分:0)

您可以使用CASE WHENIF子句中执行where逻辑。

   WHERE A.[ArTrnDetail].[InvoiceDate] >= @firstYearDay 
   AND A.[ArTrnDetail].[InvoiceDate] < DATEADD(d, 1 MIN(LatestDate, @enddate))
AND (DATEDIFF(YEAR,B.[EarliestSalesSeries].[InvoiceDate], CASE WHEN LatestDate > @endDate THEN @enddate ELSE @firstYearDay END) < 1)

对于第一个条件,我使用了min而不是CASE WHEN。您也可以使用CASE WHEN

答案 1 :(得分:0)

我相信我让它运转了。我让它变得比它需要的更复杂。我的答案如下:

&#13;
&#13;
WHERE			
			 (A.[ArTrnDetail].[InvoiceDate] < @enddate
			 and
			 A.[ArTrnDetail].[InvoiceDate] 
			 between @firstYearDay and DATEADD(year, 1, B.[EarliestSalesSeries].[InvoiceDate])
			 AND DATEDIFF(day, B.[EarliestSalesSeries].[InvoiceDate], @firstYearDay) < 365)
			 or
			 (A.[ArTrnDetail].[InvoiceDate] > @enddate
			 and
			 A.[ArTrnDetail].[InvoiceDate] between @firstYearDay and @enddate)
			 AND (DATEDIFF(DAY,B.[EarliestSalesSeries].[InvoiceDate], @enddate) < 365)
			 	
&#13;
&#13;
&#13;