我如何进出这个循环?

时间:2018-03-24 17:23:18

标签: sql tsql

我正在编写一个小程序来审核表格。

当今日数据中的列/行更新且与昨天不匹配时。它运行一个程序来添加结束日期,然后运行一个带有开始日期的新行。

我希望它循环进入,不再有行

我正在努力绕过TSQL循环..任何人都可以帮助我吗?

    DECLARE 
    @new_date date,
    @change_id int 
    while @@rowcount = 1
    begin
    select distinct @change_id = chrows.id , 
    @new_date = chrows.[dw_from_date], 
    @rowid = chrows.row
    from (
    ------------------------------ get data 13648
    SELECT getdate() [dw_from_date]
    ,'9999-01-01 00:00:00.000' [dw_to_date]
    ,prd.[id]en
    FROM [rhehdv].[dbo].[rda_Account] bi
    join [rda].[dbo].[Account] prd on bi.id = prd.id
    where prd.[versionNo] != bi.[versionNo]
    and bi.dw_to_date = '9999-01-01 00:00:00.000'
    ) chrows;
    ----------------------------- old row
    update rhehdv.dbo.[rda_Account]
    set dw_to_date = @new_date
    where id = @change_id
    ------------------------------ new row
    insert into rhehdv.dbo.[rda_Account]
    select @new_date [dw_from_date], 
    '9999-01-01 00:00:00.000' [dw_to_date]
    , a.* 
    from rda.dbo.Account a
    where a.id = @change_id  

我之前没有编写TSQL循环,而是从可用的信息中挣扎到我的脑袋,循环,进入和退出循环

1 个答案:

答案 0 :(得分:0)

自己想通​​了。

DECLARE 
@new_date date,
@change_id int, 
@countstop int 
set @countstop = 1
while @countstop > 0
begin
select @change_id = chrows.id , @new_date = chrows.[dw_from_date]
from (
-------------------------------------- select data

----------------------------- update old row from varible
------------------------------ insert new row from varible
        ;
------------------------------ count row and pass as @countstop
end
相关问题