2

我如何使用大于等于和小于等于而不是在 SQL 中使用 between

我正在检查 sql 中的日期变量

我试过这样。

Date between coalesce(@fromDate,Date) and coalesce(@toDate,Date) 

但如果用户没有输入任何日期(fromDate 或 toDate)

所以我需要将上述条件转换为greater than equal to and less than equal to

请帮助在 sql 中的语法。谢谢

4

4 回答 4

3
IF @fromDate IS NULL
  BEGIN
    SET @fromDate = '1900-01-01';
  END;

IF @toDate IS NULL
  BEGIN
    SET @toDate = '2099-01-01';
  END;

SELECT things
FROM   table
WHERE  date_field BETWEEN @toDate AND @fromDate;

这段代码本质上会给你一个任意大的范围来检查哪个应该给你合理的性能并返回所有结果(假设这就是你想要的,当两个值都没有提供时)。

这段代码可以缩短为:

SELECT things
FROM   table
WHERE  date_field BETWEEN Coalesce(@toDate, '1900-01-01') AND Coalesce(@fromDate, '2099-01-01');

但我保留了详细的版本来说明。

于 2013-09-16T09:43:59.020 回答
1

试试这个

SELECT Date FROM TableName WHERE Date > @fromDate AND Date < @toDate
于 2013-09-16T09:45:35.030 回答
1
SELECT *
FROM dbo.Account AS a
WHERE 1 = 1
    AND (
        @toDate IS NULL
        OR a.CreateDate <= @toDate
    )
    AND (
        @fromDate IS NULL
        OR a.CreateDate >= @fromDate
    )

请注意,1 = 1 只是为了使条件明确,绝不需要。

于 2013-09-16T09:47:15.570 回答
0

这应该是 where 子句的样子。

Where
 Date >= @fromDate
And
 Date <= @toDate
于 2013-09-16T09:43:46.617 回答