Sql server 使用日期在SQL Server中循环

Sql server 使用日期在SQL Server中循环,sql-server,database,sql-server-2008,Sql Server,Database,Sql Server 2008,我有个问题要问你 我需要一个与我的项目相关的脚本,应该是这样的 表1包含2016年的所有日期,即20160101、20160102、 每天,我必须插入6个个人id 像这样 'date_id' 'personal_id' “20160101” “1001”,“20160101” “1002”,“20160101” “1003”,“20160101” “1004”,“20160101” “1005”,“20160101” “1006”--for example “20160102” “1001”

我有个问题要问你

我需要一个与我的项目相关的脚本,应该是这样的

表1包含2016年的所有日期,即20160101、20160102、

每天,我必须插入6个个人id

像这样

'date_id' 'personal_id'
“20160101” “1001”,“20160101” “1002”,“20160101” “1003”,“20160101” “1004”,“20160101” “1005”,“20160101” “1006”--for example

“20160102” “1001”
“20160102” “1002”
“20160102” “1003”
“20160102” “1004”
“20160102” “1005”
“20160102” “1006”

我想将这些数据插入到2016年年底的日期引用表中。

您可以使用以下查询循环日期并完成作业:

        declare @firstofmonth as smalldatetime
        declare @endofmonth as smalldatetime

        --Set the inital month to loop
        set @firstofmonth = '01/01/2016'
        set @endofmonth = '12/31/2016'

        WHILE @firstofmonth >= '01/01/2016' --This would be the condition to end the loop

        Begin
---Check  here if dates exist in dates table and do insert


         Insert into Table_Day (blah blah black sheep)

         --Increment Date
        SET @firstofmonth = DateAdd(m,1,@firstofmonth)
        SET @endofmonth = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@firstofmonth())+1,0))

        End
这是我搜索时得到的第一个堆栈溢出结果


以上只是一种方法,您可以使用循环获取具体日期,然后插入。

感谢您告诉我们您的要求。现在是什么阻止了你实现它们?