求助:关于使用between日期 and 日期 的效率问题

kid_1982 2007-10-24 09:35:57
在对一段时间内数据进行选择时,同样使用“between日期 and 日期”,日期为常量时快,使用变量时慢。比如:
select * from salesdetails where InvoiceDate between ‘2007-10-21’and ‘2007-10-22’

要比下面用变量的快很多

declare @date1 as datetime,@date2 as datetime
set @date1 = ‘2007-10-21’
set @date2 = ‘2007-20-22’
select * from salesdetails where InvoiceDate between @date1 and @date2
...全文
491 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
Limpire 2007-10-24
  • 打赏
  • 举报
回复
在对一段时间内数据进行选择时,同样使用“between日期 and 日期”,日期为常量时快,使用变量时慢。比如:
select * from salesdetails where InvoiceDate between ‘2007-10-21’and ‘2007-10-22’

要比下面用变量的快很多

declare @date1 as datetime,@date2 as datetime
set @date1 = ‘2007-10-21’
set @date2 = ‘2007-20-22’
select * from salesdetails where InvoiceDate between @date1 and @date2

------------------

那就想办法把变量变成常量:

--declare @date1 as datetime,@date2 as datetime
declare @date1 as varchar(10),@date2 as varchar(10)
set @date1='2007-10-21'
set @date2='2007-20-22'
exec ('select * from salesdetails where InvoiceDate between '''+@date1+''' and '''+@date2+'''')
kid_1982 2007-10-24
  • 打赏
  • 举报
回复
据我所知,使用between会比《= 》=的好,但我现在想知道,常量和变量是否会影响速度哦
而且我的SQL还必须使用变量 55555
fwacky 2007-10-24
  • 打赏
  • 举报
回复
select * from salesdetails where InvoiceDate between ‘2007-10-21’and ‘2007-10-22’
这个好一点!
yuanfang2512 2007-10-24
  • 打赏
  • 举报
回复
都差不多,不过经常习惯用select * from salesdetails where InvoiceDate between ‘2007-10-21’and ‘2007-10-22’
ojuju10 2007-10-24
  • 打赏
  • 举报
回复
用>=和<=试一下:
select * from salesdetails where InvoiceDate >=@date1 and InvoiceDate <= @date2

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧