SQLServer按行循环表

本文介绍了两种在SQL中处理循环的方法:使用While循环遍历表的唯一标识符和利用游标(Cursor)进行数据表的逐条处理及插入操作。通过具体示例,展示了如何在没有唯一标识符的情况下实现数据的遍历。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、使用While...循环一个表

  • 首先保证表有一个唯一值的列,注意只需要值唯一,不需要保证值连续;
  • 如果列中存在重复的值,那么重复的值,只会有一个会被循环到;
declare @au_id char( 11 )

select @au_id = min( au_id ) from authors

while @au_id is not null
begin
    select * from authors where au_id = @au_id
    select @au_id = min( au_id ) from authors where au_id > @au_id
end

NOTE: Both example 1 and 2 assume that a unique identifier exists for each row in the source table. In some cases, no unique identifier may exist.

2、使用游标Cursor

declare @sql varchar(max)
declare @data_table varchar(50)
declare data  cursor for 
    select data_table   -- name of the table you have to query
    from somewhere      -- where these table names are stored

open data
fetch next from data into @data_table

while (@@fetch_status = 0) 
begin
    -- result_table = name of the table you want the results to be stored
    -- control_table = name of the control table you mentioned
    set @sql = 'insert into result_table
                select *
                from '+@data_table+'
                where AccountId in (select AccountId
                                    from control_table
                                    where Appear_In_View = 1)
                and Most_Recent_Data = 1'
    exec(@sql)
    fetch next from data into @data_table
end

close data 
deallocate data 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值