T-SQL循环查询结果

Jus*_*808 69 t-sql

我运行一个查询select @id=table.id from table,我需要循环结果,所以我可以执行每行的存储过程exec stored_proc @varName=@id,@otherVarName='test'

如何在T-SQL脚本中执行此操作?

XN1*_*N16 162

在这种情况下你可以使用CURSOR:

DECLARE @id INT
DECLARE @name NVARCHAR(100)
DECLARE @getid CURSOR

SET @getid = CURSOR FOR
SELECT table.id,
       table.name
FROM   table

OPEN @getid
FETCH NEXT
FROM @getid INTO @id, @name
WHILE @@FETCH_STATUS = 0
BEGIN
    EXEC stored_proc @varName=@id, @otherVarName='test', @varForName=@name
    FETCH NEXT
    FROM @getid INTO @id, @name
END

CLOSE @getid
DEALLOCATE @getid
Run Code Online (Sandbox Code Playgroud)

修改为显示表中的多个参数.

  • @HenleyChiu我已经修改了答案,包括一个新的参数`@ name`我相信它会起作用,但是因为我现在使用了光标已经有一段时间了! (2认同)

Tar*_*ryn 18

你可以这样做:

create procedure test
as
BEGIN

    create table #ids
    (
        rn int,
        id int
    )

    insert into #ids (rn, id)
    select distinct row_number() over(order by id) as rn, id
    from table

    declare @id int
    declare @totalrows int = (select count(*) from #ids)
    declare @currentrow int = 0

    while @currentrow <  @totalrows  
    begin 
        set @id = (select id from #ids where rn = @currentrow)

        exec stored_proc @varName=@id, @otherVarName='test'

        set @currentrow = @currentrow +1
    end  

END
Run Code Online (Sandbox Code Playgroud)

  • 与set操作相比,游标速度较慢(即制作一个大的select/update语句).与创建临时表和做一些_writes_相比,我不太确定.请参阅http://www.techrepublic.com/blog/the-enterprise-cloud/comparing-cursor-vs-while-loop-performance-in-sql-server-2008/我做了自己的测试,我同意.当您遇到锁定问题时,临时表可能会更快,您可以更快地获取子集然后进行处理.这取决于我猜... (3认同)

小智 7

我更喜欢的解决方案是Microsoft KB 111401 http://support.microsoft.com/kb/111401.

该链接指的是3个例子:

本文介绍了可用于在存储过程,触发器或Transact-SQL批处理中模拟类似游标的FETCH-NEXT逻辑的各种方法.

/*********** example 1 ***********/ 

declare @au_id char( 11 )

set rowcount 0
select * into #mytemp from authors

set rowcount 1

select @au_id = au_id from #mytemp

while @@rowcount <> 0
begin
    set rowcount 0
    select * from #mytemp where au_id = @au_id
    delete #mytemp where au_id = @au_id

    set rowcount 1
    select @au_id = au_id from #mytemp
end
set rowcount 0



/********** example 2 **********/ 

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



/********** example 3 **********/ 

set rowcount 0
select NULL mykey, * into #mytemp from authors

set rowcount 1
update #mytemp set mykey = 1

while @@rowcount > 0
begin
    set rowcount 0
    select * from #mytemp where mykey = 1
    delete #mytemp where mykey = 1
    set rowcount 1
    update #mytemp set mykey = 1
end
set rowcount 0
Run Code Online (Sandbox Code Playgroud)