【问题标题】:How do I use the results of a stored procedure from within another?如何使用另一个存储过程的结果?
【发布时间】:2009-05-14 01:39:14
【问题描述】:

我有一个存储过程,我想从另一个存储过程中调用它,然后循环遍历结果。有点像使用带有存储过程的游标而不是 SQL 选择语句。我不知道该怎么做。

我可以这样得到整个结果:

DECLARE @result int;
EXEC @result = sp_who;
PRINT @result;

有趣的是,这似乎将@result 的类型更改为int 以外的类型,但无论如何。然后我如何逐行遍历结果?如何访问各个列中的数据?例如,我将如何杀死第四列(登录名)类似于 '%gatesb' 之类的进程?

【问题讨论】:

标签: sql sql-server stored-procedures


【解决方案1】:

您可以声明一个表变量来保存存储过程的结果,然后在 while 循环中循环它们:

declare @temp table (
    idx int identity(1,1),
    field1 int,
    field2 varchar(max))

declare @result int

insert into @temp (field1, field2)
exec @result = sp_who

declare @counter int

set @counter = 1

while @counter < (select max(idx) from @temp)
begin
    -- do what you want with the rows here
    set @counter = @counter + 1
end

【讨论】:

  • 甜蜜 - 行之有效。只需将 '@temp' 替换为 '#temp' 并将 'exec @result = sp_who' 替换为 'exec sp_who'。谢谢你。
  • 您应该能够使用表变量 [@temp] 而不是临时表 [#temp]。如果您必须使用临时表,请确保在完成后放下该表......否则它会挂起。
  • 我将结果声明为什么? Must declare the scalar variable "@result".
  • @PeterX - 您将标量变量声明为整数,这是 SQL Server 存储过程返回的值。如果你调用的存储过程一切顺利,它将返回 0,除非它被写入返回 0 以外的值。另一方面,如果在 sproc 执行时遇到错误,则返回值将是非-零。
【解决方案2】:

将 sp_who 重写为表函数

【讨论】:

  • 我假设您的意思是,“将您的存储过程重写为表值函数。”我不认为重新实现系统存储过程是个好主意;)
  • 我用这个方法解决了我的问题——很干净。
【解决方案3】:

您可以通过插入到具有匹配列的表中来捕获存储过程的结果...

create table #spWhoResults
    (spid smallint,
    ecid smallint,
    status nchar(60),
    loginame nchar(256),
    hostname nchar(256),
    blk char(5),
    dbname nvarchar(128),
    cmd nchar(32),
    request_id int)

go

insert  #spWhoResults
exec    sp_who


select  *
from    #spWhoResults

/* 
put your cursor here to loop #spWhoResults to 
perform whatever it is you wanted to do per row
*/

【讨论】:

    【解决方案4】:

    贾斯汀指出的是你必须做的,而不是做

    while @counter < (select max(idx) from @temp)
    

    这样做

    declare @maxid int
    select @maxid = max(idx), @counter = 1
    from @temp
    while @counter < @maxid begin
    -- go on
      set @counter = @counter + 1
    end
    

    此外,如果将表声明为 @temp 不起作用,您可以将其声明为 #temp。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-21
      • 2011-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多