SQL Server可选参数日期自

时间:2013-05-10 17:53:02

标签: sql sql-server

我有一个存储过程,我想在from和to之间进行搜索,但是:

if @FromDate is not null and @ToDate is not null then 
vSaleDetail.date  between @FromDate and @ToDate 

if @FromDate is not null and @ToDate is null then
vSaleDetail.date = @FromDate

if @FromDate is null and @ToDate is then
Return All

这就是我所拥有但不起作用

where
(((@FromDate is null and @ToDate is null) OR  (vSaleDetail.date  between @FromDate and @ToDate ))
AND ((@FromDate is null) OR  (vSaleDetail.date = @FromDate)))

请帮助 - 我需要做些什么来解决它?

5 个答案:

答案 0 :(得分:3)

我会将null参数用日期超出你需要的范围。因此,如果表单日期为空,我将使用数据库的日期时间数据类型中的可接受日期填充。到目前为止将与最新的可能日期相关联。然后你不需要使用所有那些减慢速度的复杂逻辑。

IF @FromDate is null
Begin 
Set @Fromdate = '17530101'
END

IF @ToDATE is null
BEGIN 
SET @Todate = '99991231'
END

select ...
WHERE  vSaleDetail.date  >=@FromDate and <= @ToDate 

答案 1 :(得分:1)

你可以试试这个:

WHERE (vSaleDetail.date BETWEEN @FromDate AND ISNULL(@ToDate,@FromDate)
    OR COALESCE(@FromDate, @ToDate) IS NULL)

ISNULL(p1, p2)

如果p1 IS NULL则返回p2,否则返回p1

COALESCE(p1, p2, ...)

ISNULL()。返回p1,除非它是NULL,在这种情况下,除非它是NULL,否则返回p2,在这种情况下p3 ....如果COALESCE()中的所有参数都为空,{{1返回。

答案 2 :(得分:0)

试试这个:

    WHERE
    ( 
        ( @FromDate IS NULL AND @ToDate IS NULL)
        OR 
        ( vSaleDetail.date BETWEEN @FromDate AND @ToDate )
    )
    OR <-- @FromDate IS NULL AND @FromDate IS NULL
( @FromDate IS NULL OR vSaleDetail.date = @FromDate )

答案 3 :(得分:0)

declare @default_min_date datetime;
declare @default_max_date datetime;

SET @default_min_date = 0
SET @default_max_date = 2958463;

SELECT  *
FROM    MyTable
WHERE
        myDateColumn >= Isnull(@DateFrom, @default_min_date) AND myDateColumn <= Isnull(@DateTo, @default_max_date)

答案 4 :(得分:0)

AND(@DateFrom IS NULL或CONVERT(DATETIME,[CreationDate],103)BETWEEN CONVERT(DATETIME,@ DateFrom,103)和DATEADD(DAY,1,CONVERT(DATETIME,ISNULL(@DateTo,@ DateFrom)), 103)))