【发布时间】:2021-03-02 18:41:29
【问题描述】:
我有一个包含日期的表格
declare @x date ='01-jan-2021'
declare @y date ='31-jan-2021'
create table hdate( a date)
while @x <= @y
begin
insert into hdate(a) values( @x)
set @x = dateadd(day,1,@x)
end
如何循环遍历每条记录?
例如
declare @start_no int =1
declare @end_no int
select @end_no = count(*) from hdate where a between '05-jan-2021 and '10-jan-2020'
while @start_no <= @end_no
begin
select a from hdate
set @start_no = @start_no+1
--how do I get next record?
end
预期结果是
a
05-jan-2021
06-jan-2021
07-jan-2021
08-jan-2021
09-jan-2021
10-jan-2021
我想使用 while 循环。请帮忙
【问题讨论】:
-
为什么要使用while循环? SQL 针对基于集合的操作进行了优化。
-
需要在这些日期获得余额,Jim 先生已经向我展示了如何做到这一点,谢谢先生
-
但为什么是循环而不是 CTE?
标签: sql sql-server tsql