热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

在mssqlserver中循环SELECT语句[重复]-LoopinginSELECTstatementinmssqlserver[duplicate]

PossibleDuplicate:SQLServer2008GenerateaSeriesofdatetimes可能重复:SQLServer2008生成一系列日期

Possible Duplicate:
SQL Server 2008 Generate a Series of date times

可能重复:SQL Server 2008生成一系列日期时间

I have to Loop through a startDate and endDate

我必须遍历startDate和endDate

The SELECT statement should produce result as..

SELECT语句应该生成结果为..

Expected Output :

预期产出:

------------
Date
------------
09/01/2012 -> startDate
09/02/2012
09/03/2012
.
.
.
.
09/30/2012 -> endDate

i tried

我试过了

declare @startDate datetime , @endDate endDate
set @startDate='09/01/2012'
set @endDate='09/30/2012'

while DATEDIFF(@startDate,@endDate)!=-1
begin
select @startDate as Date
set @startDate = DATEADD(day,2,@startDate)
end

But its not working out..

但它没有成功..

it generates 30 outputs..

它产生30个输出..

i want the dates in a single output as in the expected output..

我希望单个输出中的日期与预期输出中的日期相同。

where am i going wrong here guys ?

我在哪里错了?

3 个解决方案

#1


10  

That will give you a resultset for each loop iteration as you select per iteration.

每次迭代选择时,这将为每个循环迭代提供结果集。

If you want a single resultset insert into a temp table/variable per iteration then select from it or

如果您希望每次迭代将单个结果集插入临时表/变量,则从中选择或

;with T(day) as
(
    select @startDate as day
        union all
    select day + 1
        from T
        where day <@endDate
)
select day as [Date] from T

#2


2  

If you want to use a WHILE loop:

如果要使用WHILE循环:

declare @startDate datetime , @endDate datetime
set @startDate='09/01/2012'
set @endDate='09/30/2012'

create table #temp (startDate datetime)   

while @startDate <= @endDate
    begin
        insert into #temp
        select @startDate as Date
        set @startDate = DATEADD(day,1,@startDate)
    end

select *
from #temp

drop table #temp
see SQL Fiddle with Demo

#3


0  

You could create a temp table for the values and select from that in the end, after the iteration.

您可以为值创建临时表,并在迭代后从最后选择。

declare @temp table (TheDate date)

declare @startDate datetime , @endDate datetime
set @startDate='09/01/2012'
set @endDate='09/30/2012'

while DATEDIFF(day, @startDate, @endDate)!=-1
begin
insert into @temp (thedate) values (@startDate)
set @startDate = DATEADD(day,2,@startDate)
end
select * from @temp

edit: The cte Alex suggest is imo a much cleaner way to do it, and more of a sql way to do it, without using loops or cursors.

编辑:亚历克斯建议使用更简洁的方法,以及更多的sql方式,而不使用循环或游标。


推荐阅读
author-avatar
不想不知痛_378
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有