我有以下我正在处理的SQL语句。我把它修剪成说明问题所需的部分。
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
,invoiceDate
,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
我将@startDate和@endDate变量设置为日期值。问题是将日期范围应用于临时表的if块没有执行,尽管这两个变量都不为null,我找不到原因。
答案 0 :(得分:4)
据我所知,TSQL不支持!=运算符进行空检查。试试这个:
IF ( @startDate IS NOT NULL AND @endDate IS NOT NULL )
答案 1 :(得分:0)
IS [NOT] NULL
是将值与NULL
进行比较的正确方法。所有(NULL
!= NULL
),(1!= NULL),(NULL = NULL)计算为NULL
(false)
答案 2 :(得分:0)
您必须使用IS NOT NULL
代替!= NULL
IF ( @startDate IS NOT NULL AND @endDate IS NOT NULL )
...