虽然条件已满足,但T-SQL IF块仍未执行

时间:2011-08-02 16:29:34

标签: sql-server-2008 if-statement

我有以下我正在处理的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,我找不到原因。

3 个答案:

答案 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 )
...