我在SQL中循环有问题。 我想循环一个开始日期,直到他到达结束日期。
他们告诉我不要使用光标,所以我找到了一个这样的例子:
with mycte as
(
select cast('2007-01-01' as datetime) DateValue
union all
select DateValue + 1
from mycte
where DateValue + 1 < '2030-12-31'
)
select * from mcte
这样可行,所以我将变量更改为我的情况:
with View_Solidnet_Training as
(
select StartingDate as DateValue
union all
insert into OBJ_Availability values(34, DateValue + 1, 'AM', 2, 'Test')
select DateValue + 1
from View_Solidnet_Training
where DateValue + 1 < EndingDate
)
select * from View_Solidnet_Training
但是我收到以下错误:
Msg 156,Level 15,State 1,Line 5关键字'insert'附近的语法不正确。消息128,级别15,状态1,行5在此上下文中不允许使用名称“DateValue”。有效表达式是常量,常量表达式和(在某些上下文中)变量。不允许使用列名。消息102,级别15,状态1,行9''
附近的语法不正确
答案 0 :(得分:0)
试试这个(未经测试):
with mycte as
(
select 34, cast('2007-01-01' as datetime) DateValue, 'AM', 2, 'Test'
union all
select 34, DateValue + 1, 'AM', 2, 'Test'
from mycte
where DateValue + 1 < '2030-12-31'
)
insert into OBJ_Availability (select * from mcte)
答案 1 :(得分:0)
请尝试:
with View_Solidnet_Training as
(
select @StartingDate as DateValue
union all
select DateValue + 1
from View_Solidnet_Training
where DateValue + 1 < @EndingDate
)
insert into OBJ_Availability
select 34, DateValue + 1, 'AM', 2, 'Test' from View_Solidnet_Training
如果@StartingDate
和@EndingDate
是两个日期时间变量,则表格OBJ_Availability
应仅包含选定CTE顺序中的5列。