Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 带有两个where条件的DateTime范围参数_Sql_Sql Server_Tsql - Fatal编程技术网

Sql 带有两个where条件的DateTime范围参数

Sql 带有两个where条件的DateTime范围参数,sql,sql-server,tsql,Sql,Sql Server,Tsql,我想使用datefrom和dateto参数选择日期范围,或者我可以在datefrom参数中键入日期,如2014年6月1日,在这种情况下dateto将为null 这意味着我想对两个过滤器使用datefrom参数,但当我在datefrom参数中键入特定日期且dateto为空时,根据键入的日期,数据不正确 请帮助解决这个问题。为了清楚起见。如果同时输入了@datefrom和@dateto,则进行范围检查。如果只输入了@datefrom,则执行相等性检查。如果是这样,这应该是可行的: Select *

我想使用
datefrom
dateto
参数选择日期范围,或者我可以在
datefrom
参数中键入日期,如
2014年6月1日
,在这种情况下
dateto
将为
null

这意味着我想对两个过滤器使用
datefrom
参数,但当我在
datefrom
参数中键入特定日期且
dateto为空时,根据键入的日期,数据不正确


请帮助解决这个问题。

为了清楚起见。如果同时输入了
@datefrom
@dateto
,则进行范围检查。如果只输入了
@datefrom
,则执行相等性检查。如果是这样,这应该是可行的:

Select * from order as o
where (@datefrom is null or @dateto is null  
              or o.orderdate between @datefrom and @dateto)      
       or (@datefrom = o.orderdate)  

我注意到在您的示例中,您也在测试@fromdate是否为null。这有什么特别的意思吗?

您的问题是当
@datefrom
null
时,整个
where
子句的每一行计算结果都是
True
,因此
where
子句没有做任何事情

以下是实现您想要的目标的一种方法:

select
    *
from
    order o
where (
    @dateto is not null and
    o.orderdate between @datefrom and @dateto
) or (
    @dateto is null and
    o.orderdate = @datefrom
)
如果@dateto为空,则设置@dateto=@datefrom;
从订单中选择*作为o
其中o.orderdate>=@datefrom
o.orderdate

请注意,我没有在
之间使用
,因为它可能会非常模糊,并且会与日期混淆-请参阅了解原因。

对于这样的查询,更好的解决方案是动态sql,类似这样的

IF @dateto IS NULL SET @dateto = @datefrom;

Select * from order as o
where o.orderdate >= @datefrom
  and o.orderdate < DATEADD(DAY, 1, @dateto);
DECLARE@datefrom DATETIME='20140101'
声明@DateToDateTime='20140303'
声明@Sql NVARCHAR(最大值);
设置@Sql=N“从[订单]中选择*”
+N'其中1=1'
+@datefrom不为空时的大小写
然后N'和orderdate>=@datefrom'ELSE N'结束
+@dateto不为NULL时的大小写
然后是N'和orderdate
DECLARE @datefrom DATETIME = '20140101' 
DECLARE @dateto   DATETIME = '20140303'

DECLARE @Sql NVARCHAR(MAX);

SET @Sql  = N' Select * from [order] '
          + N' WHERE 1 = 1 '
          + CASE WHEN @datefrom IS NOT NULL 
                  THEN N' AND orderdate >=  @datefrom ' ELSE N' ' END
          + CASE WHEN @dateto IS NOT NULL 
                  THEN N' AND orderdate <=  @dateto   ' ELSE N' ' END 


EXECUTE sp_executesql @Sql
                     ,N'@datefrom DATETIME , @dateto DATETIME'
                     ,@datefrom
                     ,@dateto