T-SQL IF Block Not Executing Though Conditions Are Met
I've got the following SQL statement that I am working on. I've trimmed it down to the parts necessary to illustrate the problem.
DECLARE @mwareId as int = 9647,
@startDate as datetime = '2011-07-20',
@endDate as datetime = '2011-07-20'
IF OBJECT_ID('tempdb..#tmpInvoiceList', 'U') IS NOT NULL DROP TABLE #tmpInvoiceList
-- Get base invoice list for customer
SELECT invoiceId
,invoiceNumber
,customerId
,customerName
,customerCode
,createDate
,lastModifiedDate
,invoice开发者_如何学编程Date
,totalInvoiceAmount
,statusId
,isPaid
INTO #tmpInvoiceList
FROM Invoice.Invoice
-- Apply date range if applicable
IF ( @startDate != NULL AND @endDate != NULL )
BEGIN
DELETE FROM #tmpInvoiceList
WHERE invoiceDate NOT BETWEEN @startDate AND @endDate
END
SELECT * FROM #tmpInvoiceList
I have the @startDate and @endDate variables set to date values. The problem is that the if block that applies the date range to the temp table is not executing, though neither of the two variables are null, and I can't find a reason for this.
As far as I'm aware, TSQL doesn't support the != operator for null checks. Try this:
IF ( @startDate IS NOT NULL AND @endDate IS NOT NULL )
IS [NOT] NULL
is the right way to compare value with NULL
. All of (NULL
!= NULL
) , (1!= NULL), (NULL =NULL) evaluate as NULL
(false)
You have to use IS NOT NULL
instead of != NULL
IF ( @startDate IS NOT NULL AND @endDate IS NOT NULL )
...
精彩评论