【发布时间】:2018-12-08 21:04:55
【问题描述】:
我想创建一个 FOR 循环的等价物。我在 SQL 中需要这个。我的目标是创建一个名为 Difference 的新列,它计算每行末尾和下一行开头之间的日期差(以天为单位)。本质上,我需要知道每个 personID 的合同是否有任何中断。 RowID 从 min 到 max 定义了与特定组织的合同,例如与一个组织的每个新合同都以 1 开头。
我的桌子是:
我写的SQL代码是:
select RowID, start_contract, end_contract from table
open the_cursor
fetch next from the_cursor into @id
while @@FETCH_STATUS = 0
begin
select
DATEDIFF(DAY, (select end_contract from table where RowID = @id-1),
(select start_contract from t where RowID = @id)) AS [Difference]
if (select RowID from t) = 1
break
else
continue
fetch next from the_cursor into @id
end
close the_cursor
deallocate the_cursor
但我得到一个错误:
Cursorfetch:INTO 列表中声明的变量数量必须与所选列的数量匹配。
有人可以帮帮我吗?
非常感谢。
【问题讨论】:
-
这篇文章展示了如何在 SQL 中运行
FOR循环:stackoverflow.com/questions/13565093/…
标签: sql while-loop