如何在sql server中为给定的序列号生成日期

时间:2013-03-07 11:03:11

标签: sql-server sql-server-2008

我需要为给定的序列号生成日期值(从getdate开始并增加1)

   SlNr  Date
    1     3/7/2013
    2     ?
    3     ?
    4     ?
    5     ?
    6     ?
    7     ?
    8     3/14/2013
    .     ?
    .     ?

如何编写sql查询。请帮忙

4 个答案:

答案 0 :(得分:1)

试试这个:

with cte as
(select 1 Sno, convert(date,GETDATE(),103) mydate
union all

select Sno+1,DATEADD(dd,1,mydate) from cte where Sno<=10)

select * from cte

更改WHERE子句以获取更多日期。您可以在Insert into之前使用select在一些表格中插入数据。

答案 1 :(得分:0)

查看DATEADD()函数here

SELECT SlNr, DATEADD(DAY, SlNr, GETDATE()) FROM yourTable

答案 2 :(得分:0)

要显示结果:

declare @firstdate date = '20130307' --Your first date in yyyymmdd format

select slnr, dateadd(day, (slnr-1), @firstdate) [date]
from yourTable
order by slnr

如果您使用getdate(),则每天的结果会有所不同。如果您只需要replace @firstdate with getdate()函数。

答案 3 :(得分:0)

您可以使用ROW_NUMBERDATEADD

WITH cte 
     AS (SELECT slnr, 
                date, 
                RN = Row_number() 
                       OVER( 
                         ORDER BY slnr) 
         FROM   dates) 
UPDATE cte 
SET    date = Dateadd(dd, cte.RN - 1, GETDATE()) 
WHERE  date IS NULL; 

DEMO