在不使用游标的情况下在SQL中循环插入语句
我在循环中遇到了SQL问题。 我想循环一个startdate直到他到达enddate。在不使用游标的情况下在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 Incorrect syntax near the keyword 'insert'. Msg 128, Level 15, State 1, Line 5 The name "DateValue" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted. Msg 102, Level 15, State 1, Line 9 Incorrect syntax near ')
请尝试:
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
有两个日期时间变量ADN表OBJ_Availability
应该包含在CTE的选择顺序只有5列。
看起来不错,但错误:消息156,级别15,状态1,行11 关键字'选择'附近的语法不正确。 – user2206834 2013-04-09 07:19:09
'StartingDate'应该是一个像'@StartDate'这样的变量,并为其设置一个最小日期值。 – TechDo 2013-04-09 07:29:46
无法回答我自己的问题。 链接:http://stackoverflow.com/questions/15896138/looping-sql-statement-insert – user2206834 2013-04-09 07:44:29
试试这个(未经测试):
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)
你得到的错误是什么? – 2013-04-09 07:10:36
消息156,级别15,状态1,行5 关键字'插入'附近的语法不正确。 Msg 128,Level 15,State 1,Line 5 在此上下文中不允许使用名称“DateValue”。有效表达式是常量,常量表达式和(在某些情况下)变量。列名不被允许。 Msg 102,Level 15,State 1,Line 9 ')'附近的语法不正确。 – user2206834 2013-04-09 07:13:46
请不要将重要信息作为评论发布。编辑您的问题 – 2013-04-09 07:14:49