当datetime过滤器为NULL时,存储过程不返回任何记录?

时间:2016-03-21 10:12:04

标签: sql sql-server stored-procedures sql-server-2012

考虑这个存储过程:

CREATE PROCEDURE [dbo].[sp_getclients]
    @FromDate datetime, @ToDate datetime
AS
BEGIN
    SET NOCOUNT ON;

    SELECT * 
    FROM CM.Clients
    --If both dates are not NULL then also check PurchaseDate to be between them
    WHERE
        (@FromDate IS NOT NULL AND @ToDate IS NOT NULL 
         AND Clients.PurchaseDate >= @FromDate 
         AND Clients.PurchaseDate <= @ToDate)
        OR
        --If @FromDate is not NULL AND @ToDate IS NULL then also check PurchaseDate to be greater than @FromDate
        (@FromDate IS NOT NULL AND @ToDate IS NULL 
         AND Clients.PurchaseDate >= @FromDate)
        OR
        --If @FromDate is NULL AND @ToDate IS NOT NULL then also check Trans_Date to be less than @ToDate 
        (@FromDate IS NULL AND @ToDate IS NOT NULL 
         AND Clients.PurchaseDate <= @ToDate)
END

当我使用NULL参数执行此存储过程时,不会返回任何记录。

我知道我在哪里出错了吗?

1 个答案:

答案 0 :(得分:2)

添加:

OR
(@FromDate IS NULL AND @ToDate IS NULL)